@ruyalab/webmonitor-nextjs 0.0.0-stage → 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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ruyalab
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @ruyalab/webmonitor-nextjs
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Connect a Next.js site to **[Web Monitor](https://webmonitor.ruyalab.com)** — uptime, response time,
4
+ performance, SEO and security checks every minute.
5
+
6
+ ## Install
7
+
8
+ ```bash
9
+ npm install @ruyalab/webmonitor-nextjs
10
+ npx webmonitor-nextjs init
11
+ ```
12
+
13
+ `init` creates the API route (`app/api/webmonitor/[...slug]/route` for the App Router, or
14
+ `pages/api/webmonitor/[...slug]` for the Pages Router) and saves a new `WEBMONITOR_API_KEY` in `.env.local`.
15
+
16
+ Then:
17
+
18
+ 1. Add the same `WEBMONITOR_API_KEY` to your hosting environment variables and deploy.
19
+ 2. In the Web Monitor dashboard click **Add site**, choose **Next.js**, and paste the key.
20
+
21
+ Optional: `WEBMONITOR_SITE_URL=https://your-site.com` sets the public URL used for SEO/security checks
22
+ (defaults to the URL the request came in on). `WEBMONITOR_LOG_FILE` shows an error log in the dashboard.
23
+
24
+ ## What it reports
25
+
26
+ All values are measured on your server at request time:
27
+
28
+ | Endpoint | Data |
29
+ |---|---|
30
+ | `health` | status, Node and Next.js versions, memory, load |
31
+ | `performance` | memory, CPU load per core, disk space, production build |
32
+ | `seo` | homepage title, meta description, H1, image alt text, `lang`, canonical, links |
33
+ | `security` | HTTPS, supported Node version, production mode, security headers, `X-Powered-By` |
34
+ | `libraries` | dependencies with installed versions |
35
+ | `analytics` | `null` — visitor analytics need an analytics provider |
36
+
37
+ Requests must send `Authorization: Bearer <WEBMONITOR_API_KEY>`. Without a key (or with a short key) the
38
+ endpoint refuses to run.
39
+
40
+ ## Manual setup
41
+
42
+ ```ts
43
+ // app/api/webmonitor/[...slug]/route.ts
44
+ export { GET } from '@ruyalab/webmonitor-nextjs/app-router';
45
+ export const dynamic = 'force-dynamic';
46
+ export const runtime = 'nodejs';
47
+ ```
48
+
49
+ ```ts
50
+ // pages/api/webmonitor/[...slug].ts
51
+ export { default } from '@ruyalab/webmonitor-nextjs/pages-router';
52
+ ```
53
+
54
+ MIT License · © Ruyalab
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ // npx webmonitor-nextjs init [--new] [--force]
3
+ // Creates the Web Monitor API route in your Next.js project and saves WEBMONITOR_API_KEY in .env.local.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { randomBytes } from 'node:crypto';
7
+
8
+ const args = process.argv.slice(2);
9
+ const command = args.find((a) => !a.startsWith('-')) || 'help';
10
+ const flag = (name) => args.includes(`--${name}`);
11
+ const root = process.cwd();
12
+
13
+ const color = (code) => (text) => (process.stdout.isTTY ? `\x1b[${code}m${text}\x1b[0m` : text);
14
+ const green = color(32);
15
+ const yellow = color(33);
16
+ const red = color(31);
17
+
18
+ function fail(message) {
19
+ console.error(red(`✖ ${message}`));
20
+ process.exit(1);
21
+ }
22
+
23
+ function findRouterDir() {
24
+ for (const dir of ['app', 'src/app']) {
25
+ if (fs.existsSync(path.join(root, dir))) return { type: 'app', dir };
26
+ }
27
+ for (const dir of ['pages', 'src/pages']) {
28
+ if (fs.existsSync(path.join(root, dir))) return { type: 'pages', dir };
29
+ }
30
+ return null;
31
+ }
32
+
33
+ function writeRoute() {
34
+ const router = findRouterDir();
35
+ if (!router) fail('No app/ or pages/ folder found. Run this in the root of your Next.js project.');
36
+ const ext = fs.existsSync(path.join(root, 'tsconfig.json')) ? 'ts' : 'js';
37
+ const file = router.type === 'app'
38
+ ? path.join(router.dir, 'api', 'webmonitor', '[...slug]', `route.${ext}`)
39
+ : path.join(router.dir, 'api', 'webmonitor', `[...slug].${ext}`);
40
+ const contents = router.type === 'app'
41
+ ? [
42
+ '// Web Monitor endpoint (created by `npx webmonitor-nextjs init`)',
43
+ "export { GET } from '@ruyalab/webmonitor-nextjs/app-router';",
44
+ "export const dynamic = 'force-dynamic';",
45
+ "export const runtime = 'nodejs';",
46
+ '',
47
+ ].join('\n')
48
+ : [
49
+ '// Web Monitor endpoint (created by `npx webmonitor-nextjs init`)',
50
+ "export { default } from '@ruyalab/webmonitor-nextjs/pages-router';",
51
+ '',
52
+ ].join('\n');
53
+
54
+ const fullPath = path.join(root, file);
55
+ if (fs.existsSync(fullPath) && !flag('force')) {
56
+ console.log(green(`✔ Route already exists: ${file}`));
57
+ return;
58
+ }
59
+ fs.mkdirSync(path.dirname(fullPath), { recursive: true });
60
+ fs.writeFileSync(fullPath, contents);
61
+ console.log(green(`✔ Created ${file}`));
62
+ }
63
+
64
+ function ensureKey() {
65
+ const envFile = path.join(root, '.env.local');
66
+ let env = fs.existsSync(envFile) ? fs.readFileSync(envFile, 'utf8') : '';
67
+ const existing = env.match(/^WEBMONITOR_API_KEY=(.*)$/m)?.[1]?.trim().replace(/^["']|["']$/g, '');
68
+ if (existing && !flag('new')) {
69
+ console.log(green('✔ WEBMONITOR_API_KEY already set in .env.local (use --new to replace it)'));
70
+ return existing;
71
+ }
72
+ const key = randomBytes(32).toString('hex');
73
+ const line = `WEBMONITOR_API_KEY=${key}`;
74
+ env = /^WEBMONITOR_API_KEY=/m.test(env)
75
+ ? env.replace(/^WEBMONITOR_API_KEY=.*$/m, line)
76
+ : `${env.replace(/\n*$/, '')}${env ? '\n\n' : ''}${line}\n`;
77
+ fs.writeFileSync(envFile, env);
78
+ console.log(green('✔ Saved WEBMONITOR_API_KEY in .env.local'));
79
+ return key;
80
+ }
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
+
106
+ if (command === 'init') {
107
+ const pkgFile = path.join(root, 'package.json');
108
+ if (!fs.existsSync(pkgFile)) fail('No package.json here. Run this in the root of your Next.js project.');
109
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
110
+ if (!pkg.dependencies?.next && !pkg.devDependencies?.next) {
111
+ console.log(yellow('! "next" is not in package.json — make sure you are in your Next.js project root.'));
112
+ }
113
+ writeRoute();
114
+ writeInstrumentation();
115
+ const key = ensureKey();
116
+ console.log(`
117
+ Next steps
118
+ 1. Add the same variable to your hosting provider (e.g. Vercel → Settings → Environment Variables):
119
+ ${yellow('WEBMONITOR_API_KEY')}=${key}
120
+ 2. Deploy, then add the site in your Web Monitor dashboard:
121
+ Platform: ${yellow('Next.js')} API key: ${key}
122
+ 3. Test: curl -H "Authorization: Bearer ${key}" https://your-site.com/api/webmonitor/health
123
+ `);
124
+ } else {
125
+ console.log(`Web Monitor for Next.js
126
+
127
+ Usage:
128
+ npx webmonitor-nextjs init Create the API route and WEBMONITOR_API_KEY
129
+ npx webmonitor-nextjs init --new Replace the API key with a new one
130
+ npx webmonitor-nextjs init --force Re-create the route file
131
+ `);
132
+ }
package/index.d.ts ADDED
@@ -0,0 +1,20 @@
1
+ export declare const VERSION: string;
2
+ export declare const ENDPOINTS: string[];
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
+
9
+ export declare function handleWebMonitorRequest(
10
+ endpoint: string,
11
+ request: { authorization?: string | null; origin: string; forwardedProto?: string | null },
12
+ ): Promise<{ status: number; body: Record<string, unknown> }>;
13
+
14
+ /** App Router route handler (app/api/webmonitor/[...slug]/route.ts) */
15
+ export declare function GET(request: Request): Promise<Response>;
16
+
17
+ /** Pages Router API handler (pages/api/webmonitor/[...slug].ts) */
18
+ declare function pagesHandler(req: unknown, res: unknown): Promise<void>;
19
+ export { pagesHandler };
20
+ export default pagesHandler;
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@ruyalab/webmonitor-nextjs",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.2.0",
4
+ "description": "Connect a Next.js site to Web Monitor (webmonitor.ruyalab.com): uptime, performance, SEO and security checks.",
5
+ "keywords": [
6
+ "nextjs",
7
+ "monitoring",
8
+ "uptime",
9
+ "health-check",
10
+ "webmonitor"
11
+ ],
12
+ "homepage": "https://webmonitor.ruyalab.com/integrations#nextjs",
13
+ "license": "MIT",
14
+ "author": "Ruyalab",
15
+ "type": "module",
16
+ "main": "./src/index.js",
17
+ "types": "./index.d.ts",
18
+ "exports": {
19
+ ".": {
20
+ "types": "./index.d.ts",
21
+ "default": "./src/index.js"
22
+ },
23
+ "./app-router": {
24
+ "types": "./index.d.ts",
25
+ "default": "./src/app-router.js"
26
+ },
27
+ "./pages-router": {
28
+ "types": "./index.d.ts",
29
+ "default": "./src/pages-router.js"
30
+ },
31
+ "./instrumentation": {
32
+ "types": "./index.d.ts",
33
+ "default": "./src/instrumentation.js"
34
+ }
35
+ },
36
+ "bin": {
37
+ "webmonitor-nextjs": "bin/webmonitor-nextjs.js"
38
+ },
39
+ "files": [
40
+ "src",
41
+ "bin",
42
+ "index.d.ts",
43
+ "README.md",
44
+ "LICENSE"
45
+ ],
46
+ "peerDependencies": {
47
+ "next": ">=13.4"
48
+ },
49
+ "engines": {
50
+ "node": ">=18.17"
51
+ },
52
+ "publishConfig": {
53
+ "access": "public"
54
+ }
55
+ }
@@ -0,0 +1,16 @@
1
+ // App Router route handler: app/api/webmonitor/[...slug]/route.(js|ts)
2
+ // export { GET } from '@ruyalab/webmonitor-nextjs/app-router';
3
+ // export const dynamic = 'force-dynamic';
4
+ // export const runtime = 'nodejs';
5
+ import { handleWebMonitorRequest } from './core.js';
6
+
7
+ export async function GET(request) {
8
+ const url = new URL(request.url);
9
+ const endpoint = url.pathname.split('/').filter(Boolean).pop();
10
+ const { status, body } = await handleWebMonitorRequest(endpoint, {
11
+ authorization: request.headers.get('authorization'),
12
+ origin: url.origin,
13
+ forwardedProto: request.headers.get('x-forwarded-proto'),
14
+ });
15
+ return Response.json(body, { status, headers: { 'Cache-Control': 'no-store' } });
16
+ }
package/src/core.js ADDED
@@ -0,0 +1,451 @@
1
+ // Web Monitor integration core for Next.js (Node.js runtime).
2
+ // Every value is measured at request time; what can't be measured (visitor analytics, malware scans)
3
+ // is reported as null / "not_available", never guessed.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import v8 from 'node:v8';
7
+ import path from 'node:path';
8
+ import { createRequire } from 'node:module';
9
+ import { timingSafeEqual } from 'node:crypto';
10
+ import { errorStore } from './instrumentation.js';
11
+
12
+ export const VERSION = '1.2.0';
13
+ export const ENDPOINTS = ['health', 'analytics', 'performance', 'seo', 'security', 'libraries', 'logs', 'recommendations'];
14
+
15
+ const projectRoot = () => process.cwd();
16
+
17
+ function readJson(file) {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ const installedVersion = (name) => readJson(path.join(projectRoot(), 'node_modules', name, 'package.json'))?.version ?? null;
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
+
37
+ function safeEqual(a, b) {
38
+ const left = Buffer.from(String(a));
39
+ const right = Buffer.from(String(b));
40
+ return left.length === right.length && timingSafeEqual(left, right);
41
+ }
42
+
43
+ const round = (value, digits = 2) => (value == null ? null : Number(value.toFixed(digits)));
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
+
58
+ function systemMemoryPercent() {
59
+ return round(((os.totalmem() - os.freemem()) / os.totalmem()) * 100);
60
+ }
61
+
62
+ // 1-minute load average per CPU core, as a percentage (null on Windows, where it isn't available)
63
+ function cpuUsagePercent() {
64
+ if (process.platform === 'win32') return null;
65
+ const cores = os.cpus().length || 1;
66
+ return round(Math.min(100, (os.loadavg()[0] / cores) * 100));
67
+ }
68
+
69
+ function trafficStats() {
70
+ try {
71
+ const lines = fs.readFileSync('/proc/net/dev', 'utf8').split('\n');
72
+ let tx = 0;
73
+ let rx = 0;
74
+ let found = false;
75
+ for (const line of lines) {
76
+ const split = line.split(':');
77
+ if (split.length < 2) continue;
78
+ const iface = split[0].trim();
79
+ if (!iface || iface === 'lo') continue;
80
+ const cols = split.slice(1).join(':').trim().split(/\s+/);
81
+ if (cols.length < 9) continue;
82
+ rx += Number(cols[0]);
83
+ tx += Number(cols[8]);
84
+ found = true;
85
+ }
86
+ if (!found) return { txBytes: null, rxBytes: null };
87
+ return { txBytes: tx, rxBytes: rx };
88
+ } catch {
89
+ return { txBytes: null, rxBytes: null };
90
+ }
91
+ }
92
+
93
+ function diskStats() {
94
+ try {
95
+ const stats = fs.statfsSync(projectRoot());
96
+ const free = stats.bavail * stats.bsize;
97
+ const total = stats.blocks * stats.bsize;
98
+ if (!total) return { freeBytes: null, totalBytes: null, freePercent: null };
99
+ return {
100
+ freeBytes: free,
101
+ totalBytes: total,
102
+ freePercent: round((stats.bavail / stats.blocks) * 100, 1),
103
+ };
104
+ } catch {
105
+ return { freeBytes: null, totalBytes: null, freePercent: null };
106
+ }
107
+ }
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
+
159
+ // ---- endpoints ------------------------------------------------------------------------------
160
+
161
+ function getHealth() {
162
+ const start = performance.now();
163
+ const memory = systemMemoryPercent();
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';
167
+ return {
168
+ status,
169
+ message: failing ? `${failing.name}: ${failing.message}` : memory >= 95 ? 'Server memory usage is above 95%' : 'Site is healthy',
170
+ timestamp: new Date().toISOString(),
171
+ response_time: round(performance.now() - start),
172
+ node_version: process.version,
173
+ nextjs_version: nextVersion(),
174
+ framework: 'Next.js',
175
+ integration_version: VERSION,
176
+ security_config: securityConfig(),
177
+ uptime_seconds: Math.round(os.uptime()),
178
+ checks: {
179
+ memory_usage: `${memory}%`,
180
+ load_average: process.platform === 'win32' ? null : round(os.loadavg()[0]),
181
+ },
182
+ components,
183
+ };
184
+ }
185
+
186
+ function getAnalytics() {
187
+ // Visitors, page views, bounce rate and sessions need an analytics source (Vercel Analytics, GA4...).
188
+ return {
189
+ totalVisitors: null,
190
+ pageViews: null,
191
+ bounceRate: null,
192
+ avgSessionDuration: null,
193
+ analytics_source: 'unavailable',
194
+ analytics_note: 'Connect an analytics provider for visitor data. The server cannot measure visits on its own.',
195
+ top_pages: [],
196
+ content_stats: {},
197
+ };
198
+ }
199
+
200
+ function getPerformance() {
201
+ const start = performance.now();
202
+ const memory = systemMemoryPercent();
203
+ const cpu = cpuUsagePercent();
204
+ const disk = diskStats();
205
+ const traffic = trafficStats();
206
+ const processMemory = process.memoryUsage();
207
+ const elapsed = round(performance.now() - start);
208
+
209
+ let score = 100;
210
+ const recommendations = [];
211
+ if (memory > 80) { score -= 15; recommendations.push('Server memory usage is high — add memory or reduce usage'); }
212
+ if (cpu != null && cpu > 80) { score -= 20; recommendations.push('Server CPU load is high — optimize heavy work or add capacity'); }
213
+ if (disk.freePercent != null && disk.freePercent < 10) { score -= 15; recommendations.push('Less than 10% disk space left on the server'); }
214
+ if (process.env.NODE_ENV !== 'production') { score -= 10; recommendations.push('Run the site with a production build (next build && next start)'); }
215
+
216
+ return {
217
+ load_time: elapsed,
218
+ server_response_time: elapsed,
219
+ database_query_time: null,
220
+ memory_usage: memory,
221
+ memory_peak: round(processMemory.rss / 1048576),
222
+ heap_used_mb: round(processMemory.heapUsed / 1048576),
223
+ cpu_usage: cpu,
224
+ disk_free_percent: disk.freePercent,
225
+ disk_free_bytes: disk.freeBytes,
226
+ disk_total_bytes: disk.totalBytes,
227
+ bandwidth_tx_bytes: traffic.txBytes,
228
+ bandwidth_rx_bytes: traffic.rxBytes,
229
+ performance_score: Math.max(0, score),
230
+ active_plugins: null,
231
+ recommendations,
232
+ };
233
+ }
234
+
235
+ async function fetchHomepage(ctx) {
236
+ if (ctx.homepage) return ctx.homepage;
237
+ const url = `${ctx.siteUrl}/`;
238
+ try {
239
+ const response = await fetch(url, { headers: { 'User-Agent': `WebMonitor/${VERSION}` }, signal: AbortSignal.timeout(5000) });
240
+ const html = await response.text();
241
+ ctx.homepage = { url, html, headers: Object.fromEntries([...response.headers].map(([k, v]) => [k.toLowerCase(), v])) };
242
+ } catch (error) {
243
+ ctx.homepage = { url, html: null, headers: null, error: error.message };
244
+ }
245
+ return ctx.homepage;
246
+ }
247
+
248
+ function countLinks(html, siteUrl) {
249
+ const host = new URL(siteUrl).host;
250
+ let internal = 0;
251
+ let external = 0;
252
+ for (const [, href] of html.matchAll(/<a\b[^>]*href=["']([^"'#]+)["']/gi)) {
253
+ try {
254
+ const target = new URL(href, siteUrl);
255
+ if (target.host === host) internal += 1;
256
+ else if (/^https?:$/.test(target.protocol)) external += 1;
257
+ } catch {
258
+ // ignore malformed links
259
+ }
260
+ }
261
+ return [internal, external];
262
+ }
263
+
264
+ async function getSeo(ctx) {
265
+ const page = await fetchHomepage(ctx);
266
+ if (page.html == null) {
267
+ return { score: null, ssl_enabled: ctx.https, seo_issues: [], recommendations: [], note: `Homepage could not be read for analysis: ${page.error}` };
268
+ }
269
+ const { html } = page;
270
+ const issues = [];
271
+ const recommendations = [];
272
+ let score = 100;
273
+
274
+ const title = (html.match(/<title[^>]*>([\s\S]*?)<\/title>/i)?.[1] || '').replace(/<[^>]+>/g, '').trim();
275
+ const description = (html.match(/<meta[^>]+name=["']description["'][^>]*content=["']([^"']*)["']/i)
276
+ || html.match(/<meta[^>]+content=["']([^"']*)["'][^>]*name=["']description["']/i))?.[1]?.trim() || '';
277
+ const h1Count = (html.match(/<h1[\s>]/gi) || []).length;
278
+ const images = html.match(/<img\b[^>]*>/gi) || [];
279
+ const imagesWithAlt = images.filter((tag) => /\balt=["'][^"']+["']/i.test(tag)).length;
280
+ const hasLang = /<html[^>]+\blang=["'][^"']+["']/i.test(html);
281
+ const hasCanonical = /<link[^>]+rel=["']canonical["']/i.test(html);
282
+ const [internal, external] = countLinks(html, ctx.siteUrl);
283
+
284
+ if (!title) { score -= 20; issues.push('Homepage has no <title>'); recommendations.push('Add a descriptive page title (metadata.title)'); }
285
+ else if (title.length > 65) { score -= 5; issues.push('Title is longer than 65 characters'); }
286
+ if (!description) { score -= 15; issues.push('Homepage has no meta description'); recommendations.push('Add a meta description (metadata.description)'); }
287
+ if (h1Count === 0) { score -= 10; issues.push('Homepage has no <h1> heading'); recommendations.push('Add one <h1> heading'); }
288
+ else if (h1Count > 1) { score -= 5; issues.push(`Homepage has ${h1Count} <h1> headings`); }
289
+ if (images.length > imagesWithAlt) { score -= 10; issues.push(`${images.length - imagesWithAlt} of ${images.length} images have no alt text`); recommendations.push('Add alt text to images'); }
290
+ if (!hasLang) { score -= 5; issues.push('<html> has no lang attribute'); }
291
+ if (!hasCanonical) { score -= 5; issues.push('No canonical link'); }
292
+ if (!ctx.https) { score -= 10; issues.push('Site is not served over HTTPS'); recommendations.push('Enable SSL certificate'); }
293
+
294
+ return {
295
+ score: Math.max(0, score),
296
+ meta_tags: title && description ? 'complete' : 'incomplete',
297
+ alt_tags: images.length ? Math.round((imagesWithAlt / images.length) * 100) : null,
298
+ heading_structure: h1Count === 1 ? 'good' : 'needs_improvement',
299
+ internal_links: internal,
300
+ external_links: external,
301
+ ssl_enabled: ctx.https,
302
+ site_title: title,
303
+ site_description: description,
304
+ total_content: null,
305
+ seo_issues: issues,
306
+ recommendations,
307
+ analyzed_url: page.url,
308
+ };
309
+ }
310
+
311
+ async function getSecurity(ctx) {
312
+ const checks = {};
313
+ const recommendations = [];
314
+ const add = (name, passed, advice) => {
315
+ checks[name] = passed;
316
+ if (passed === false) recommendations.push(advice);
317
+ };
318
+
319
+ add('https', ctx.https, 'Enable SSL certificate (serve the site over HTTPS)');
320
+ add('supported_node', Number(process.versions.node.split('.')[0]) >= 20, 'Upgrade Node.js to a supported LTS version (20 or newer)');
321
+ add('production_mode', process.env.NODE_ENV === 'production', 'Run a production build (NODE_ENV=production)');
322
+
323
+ const { headers } = await fetchHomepage(ctx);
324
+ if (headers) {
325
+ add('no_powered_by_header', !headers['x-powered-by'], 'Hide the X-Powered-By header (poweredByHeader: false in next.config)');
326
+ add('hsts_header', Boolean(headers['strict-transport-security']), 'Send a Strict-Transport-Security header');
327
+ add('nosniff_header', Boolean(headers['x-content-type-options']), 'Send X-Content-Type-Options: nosniff');
328
+ add('frame_protection', Boolean(headers['x-frame-options'] || headers['content-security-policy']), 'Protect against clickjacking (X-Frame-Options or CSP)');
329
+ }
330
+
331
+ const known = Object.values(checks).filter((v) => v !== null && v !== undefined);
332
+ return {
333
+ ssl_status: ctx.https ? 'enabled' : 'disabled',
334
+ firewall: 'unknown',
335
+ malware_scan: 'not_available',
336
+ vulnerability_scan: 'not_available',
337
+ security_score: known.length ? Math.round((known.filter(Boolean).length / known.length) * 100) : null,
338
+ security_checks: checks,
339
+ security_plugins: null,
340
+ total_plugins: null,
341
+ outdated_plugins: null,
342
+ node_version: process.version,
343
+ nextjs_version: nextVersion(),
344
+ recommendations,
345
+ };
346
+ }
347
+
348
+ function getLibraries() {
349
+ const pkg = readJson(path.join(projectRoot(), 'package.json'));
350
+ if (!pkg) return { total_libraries: 0, all_libraries: [], message: 'package.json not found' };
351
+ const format = (deps = {}, isDev) => Object.entries(deps).map(([name, range]) => ({
352
+ name,
353
+ version: installedVersion(name),
354
+ rawVersion: range,
355
+ isDev,
356
+ type: isDev ? 'devDependency' : 'dependency',
357
+ outdated: null,
358
+ }));
359
+ const dependencies = format(pkg.dependencies, false);
360
+ const devDependencies = format(pkg.devDependencies, true);
361
+ return {
362
+ total_libraries: dependencies.length + devDependencies.length,
363
+ dependencies_count: dependencies.length,
364
+ devDependencies_count: devDependencies.length,
365
+ dependencies,
366
+ devDependencies,
367
+ all_libraries: [...dependencies, ...devDependencies],
368
+ outdated_count: null,
369
+ node_version: process.version,
370
+ nextjs_version: nextVersion(),
371
+ };
372
+ }
373
+
374
+ function getLogs() {
375
+ const candidates = [process.env.WEBMONITOR_LOG_FILE, path.join(projectRoot(), 'logs', 'error.log')].filter(Boolean);
376
+ for (const file of candidates) {
377
+ try {
378
+ const lines = fs.readFileSync(file, 'utf8').split('\n').filter(Boolean).slice(-100);
379
+ return {
380
+ error_log: {
381
+ enabled: true,
382
+ message: '',
383
+ lines: lines.map((raw) => ({ raw, time: raw.slice(0, 40).match(/\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}/)?.[0] ?? '' })),
384
+ count: lines.length,
385
+ },
386
+ access_summary: {},
387
+ };
388
+ } catch {
389
+ // try the next location
390
+ }
391
+ }
392
+ return {
393
+ error_log: { enabled: false, message: 'No log file found. Set WEBMONITOR_LOG_FILE to show your error log here.', lines: [], count: 0 },
394
+ access_summary: {},
395
+ };
396
+ }
397
+
398
+ async function getRecommendations(ctx) {
399
+ const sections = { performance: getPerformance(), seo: await getSeo(ctx), security: await getSecurity(ctx) };
400
+ const recommendations = Object.entries(sections).flatMap(([source, data]) => (data.recommendations || []).map((text) => ({ text, source })));
401
+ return { recommendations, count: recommendations.length };
402
+ }
403
+
404
+ const HANDLERS = {
405
+ health: getHealth,
406
+ analytics: getAnalytics,
407
+ performance: getPerformance,
408
+ seo: getSeo,
409
+ security: getSecurity,
410
+ libraries: getLibraries,
411
+ plugins: getLibraries,
412
+ logs: getLogs,
413
+ recommendations: getRecommendations,
414
+ };
415
+
416
+ /**
417
+ * Framework-neutral request handler.
418
+ * @param {string} endpoint last path segment, e.g. "health"
419
+ * @param {{ authorization?: string|null, origin: string, forwardedProto?: string|null }} request
420
+ * @returns {Promise<{ status: number, body: object }>}
421
+ */
422
+ export async function handleWebMonitorRequest(endpoint, request) {
423
+ const apiKey = process.env.WEBMONITOR_API_KEY || '';
424
+ if (!apiKey) {
425
+ return { status: 503, body: { error: 'WEBMONITOR_API_KEY is not set on this site. Run: npx webmonitor-nextjs init' } };
426
+ }
427
+ // A short or placeholder key would be guessable: refuse to run with it
428
+ if (apiKey.length < 16 || /^paste-/i.test(apiKey)) {
429
+ return { status: 503, body: { error: 'WEBMONITOR_API_KEY is too short or still the placeholder. Use a long random key.' } };
430
+ }
431
+ const token = /^Bearer\s+(.+)$/i.exec(request.authorization || '')?.[1]?.trim() || '';
432
+ if (!safeEqual(token, apiKey)) {
433
+ return { status: 401, body: { error: 'Invalid API key. Please check your authorization header.' } };
434
+ }
435
+ const handler = HANDLERS[endpoint];
436
+ if (!handler) {
437
+ return { status: 404, body: { error: `Unknown endpoint. Available: ${ENDPOINTS.join(', ')}` } };
438
+ }
439
+
440
+ const siteUrl = (process.env.WEBMONITOR_SITE_URL || request.origin).replace(/\/$/, '');
441
+ const ctx = {
442
+ siteUrl,
443
+ https: siteUrl.startsWith('https://') || request.forwardedProto === 'https',
444
+ homepage: null,
445
+ };
446
+ try {
447
+ return { status: 200, body: await handler(ctx) };
448
+ } catch (error) {
449
+ return { status: 500, body: { error: `Web Monitor check failed: ${error.message}` } };
450
+ }
451
+ }
package/src/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { handleWebMonitorRequest, ENDPOINTS, VERSION, getComponents } from './core.js';
2
+ export { onRequestError, register } from './instrumentation.js';
3
+ export { GET } from './app-router.js';
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
+ }
@@ -0,0 +1,19 @@
1
+ // Pages Router API route: pages/api/webmonitor/[...slug].(js|ts)
2
+ // export { default } from '@ruyalab/webmonitor-nextjs/pages-router';
3
+ import { handleWebMonitorRequest } from './core.js';
4
+
5
+ export default async function webMonitorHandler(req, res) {
6
+ if (req.method !== 'GET') {
7
+ res.setHeader('Allow', 'GET');
8
+ return res.status(405).json({ error: 'Method not allowed' });
9
+ }
10
+ const slug = [].concat(req.query.slug || []);
11
+ const proto = req.headers['x-forwarded-proto'] || (req.socket?.encrypted ? 'https' : 'http');
12
+ const { status, body } = await handleWebMonitorRequest(slug[slug.length - 1], {
13
+ authorization: req.headers.authorization,
14
+ origin: `${proto}://${req.headers.host}`,
15
+ forwardedProto: req.headers['x-forwarded-proto'],
16
+ });
17
+ res.setHeader('Cache-Control', 'no-store');
18
+ return res.status(status).json(body);
19
+ }