@netgreener/runtime 0.1.9 → 0.1.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.
package/dist/next.js CHANGED
@@ -6,13 +6,30 @@
6
6
  * Does not change NETGREENER_EXPORT_MODE defaults.
7
7
  */
8
8
  import { randomUUID } from 'node:crypto';
9
+ import { createRequire } from 'node:module';
9
10
  import { getRuntime, } from './runtime.js';
10
- import { getTenantStore, resolveTenantFromHttpRequest, runWithTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
11
+ import { getTenantStore, resolveTenantFromHttpRequest, normalizeTenantId, runWithTenantContext, tenantConfigFromRuntime, } from './tenantContext.js';
11
12
  import { runWithRequestAttribution } from './requestContext.js';
12
13
  import { beginProcessResourceSample, endProcessResourceSample, } from './processResources.js';
13
14
  import { getOccupancyTracker } from './occupancyTracker.js';
15
+ import { _awaitPendingUsageParses, outboundHttpInFlight, whenOutboundHttpIdle, } from './externalApiMeter.js';
16
+ export { withNetGreener } from './nextConfig.js';
17
+ /**
18
+ * Sibling ``after()`` callbacks start in parallel with ours (Next.js p-queue).
19
+ * A short quiet window lets those callbacks start their ``fetch`` before upload.
20
+ */
21
+ let invokeFlushQuietMs = 25;
22
+ /** Test hook. ``undefined`` loads ``next/server`` ``after`` when the app provides it. */
23
+ let nextAfterOverride;
24
+ export function _setNextAfterForTests(fn) {
25
+ nextAfterOverride = fn;
26
+ }
27
+ export function _setInvokeFlushQuietMsForTests(ms) {
28
+ invokeFlushQuietMs = ms;
29
+ }
14
30
  export const UNKNOWN_NEXT_ROUTE_TEMPLATE = '<unmatched>';
15
31
  const MAX_ROUTE_TEMPLATE_LEN = 512;
32
+ let installedTenantResolver;
16
33
  /**
17
34
  * Call from ``instrumentation.ts`` ``register()`` to start the Runtime singleton.
18
35
  *
@@ -29,6 +46,8 @@ export function registerNetGreenerNext(opts = {}) {
29
46
  framework: 'next',
30
47
  ...opts,
31
48
  });
49
+ if (opts.resolveTenant)
50
+ installedTenantResolver = opts.resolveTenant;
32
51
  runtime.start();
33
52
  if (runtime.lifecycle === 'persistent') {
34
53
  const onSignal = () => {
@@ -106,14 +125,27 @@ export function withNetGreenerRoute(handler, opts = {}) {
106
125
  if (!runtime.enabled) {
107
126
  return handler(req, ...args);
108
127
  }
109
- const method = (req.method || 'GET').toUpperCase();
110
128
  const path = nextRouteTemplate(req, opts.routeTemplate);
129
+ const cron = opts.unitType === 'cron' || path === '/api/cron' || path.startsWith('/api/cron/');
130
+ const method = (opts.recordMethod || (cron ? 'CRON' : req?.method || 'GET')).toUpperCase();
131
+ const unitType = opts.unitType || (cron ? 'cron' : 'http_route');
111
132
  const resolveServiceUnit = () => `${method} ${path}`;
112
133
  const fakeHttpReq = {
113
134
  method,
114
- headers: headersAsRecord(req.headers),
135
+ headers: headersAsRecord(req?.headers),
115
136
  };
116
- const entryTenant = resolveTenantFromHttpRequest(fakeHttpReq, tenantConfig);
137
+ let entryTenant = resolveTenantFromHttpRequest(fakeHttpReq, tenantConfig);
138
+ const resolver = opts.resolveTenant ?? installedTenantResolver;
139
+ if (resolver) {
140
+ try {
141
+ const tenantId = normalizeTenantId(await resolver(req));
142
+ if (tenantId)
143
+ entryTenant = { tenantId, tenantSource: 'callback' };
144
+ }
145
+ catch {
146
+ /* fail-open: a tenant callback must not break the request */
147
+ }
148
+ }
117
149
  return runWithTenantContext(entryTenant, () => runWithRequestAttribution({
118
150
  resolveServiceUnit,
119
151
  serviceUnit: resolveServiceUnit(),
@@ -148,18 +180,45 @@ export function withNetGreenerRoute(handler, opts = {}) {
148
180
  path,
149
181
  statusCode,
150
182
  durationMs,
183
+ unitType,
151
184
  cpuTimeMs: resources.cpuTimeMs,
152
185
  peakRssKb: resources.rssKb,
153
186
  });
154
187
  });
155
- runtime.endRequest();
188
+ runtime.endRequest({
189
+ deferInvokeFlush: runtime.lifecycle === 'ephemeral',
190
+ });
156
191
  if (runtime.lifecycle === 'ephemeral') {
157
- void runtime.flushForInvokeEnd();
192
+ scheduleEphemeralInvokeFlush(runtime, readWaitUntil(req));
158
193
  }
159
194
  }
160
195
  }));
161
196
  };
162
197
  }
198
+ /**
199
+ * Loader target for an App Router route handler.
200
+ * ``cron: true`` records the service unit as ``CRON <template>``.
201
+ */
202
+ export function observeNextRoute(handler, _method, routeTemplate, opts) {
203
+ return withNetGreenerRoute(handler, {
204
+ routeTemplate,
205
+ unitType: opts?.cron ? 'cron' : 'http_route',
206
+ recordMethod: opts?.cron ? 'CRON' : undefined,
207
+ });
208
+ }
209
+ /** Loader target for a server page. */
210
+ export function observeNextPage(component, routeTemplate) {
211
+ return withNetGreenerRoute(((props) => component(props)), { routeTemplate, unitType: 'page', recordMethod: 'GET' });
212
+ }
213
+ /** Loader target for a `'use server'` export. */
214
+ export function observeNextAction(action, name, routeTemplate) {
215
+ const template = `${routeTemplate}#${name}`.slice(0, 512);
216
+ return withNetGreenerRoute(action, {
217
+ routeTemplate: template,
218
+ unitType: 'action',
219
+ recordMethod: 'ACTION',
220
+ });
221
+ }
163
222
  function statusFromResult(result) {
164
223
  if (result &&
165
224
  typeof result === 'object' &&
@@ -184,12 +243,86 @@ export async function flushNetGreenerNext(kind = 'manual') {
184
243
  /**
185
244
  * Schedule a best-effort flush after the response (Vercel ``waitUntil`` when present).
186
245
  * Fail-open: never throws into the customer path.
246
+ *
247
+ * Prefers Next.js ``after()``, which runs once the response (including a stream)
248
+ * has closed and is already passed to platform ``waitUntil``.
187
249
  */
188
250
  export function scheduleNetGreenerFlush(waitUntil) {
189
- const p = flushNetGreenerNext('invoke_end').catch(() => null);
190
- if (typeof waitUntil === 'function') {
191
- waitUntil(p);
251
+ scheduleEphemeralInvokeFlush(getNextRuntime(), waitUntil);
252
+ }
253
+ function readWaitUntil(req) {
254
+ const maybe = req.waitUntil;
255
+ return typeof maybe === 'function' ? maybe : undefined;
256
+ }
257
+ const requireFromHere = createRequire(import.meta.url);
258
+ let cachedNextAfter;
259
+ function scheduleEphemeralInvokeFlush(runtime, waitUntil) {
260
+ // Start the upload only when Next runs the callback. ``after(promise)`` does
261
+ // not wait for the response to close; ``after(fn)`` does.
262
+ const start = () => finishEphemeralInvoke(runtime);
263
+ if (scheduleWithNextAfter(start))
192
264
  return;
265
+ const work = start();
266
+ if (typeof waitUntil === 'function') {
267
+ try {
268
+ waitUntil(work);
269
+ return;
270
+ }
271
+ catch {
272
+ /* fall through; the promise is already running */
273
+ }
274
+ }
275
+ void work;
276
+ }
277
+ function scheduleWithNextAfter(start) {
278
+ const afterFn = resolveNextAfter();
279
+ if (!afterFn)
280
+ return false;
281
+ try {
282
+ afterFn(() => start());
283
+ return true;
284
+ }
285
+ catch {
286
+ return false;
287
+ }
288
+ }
289
+ function resolveNextAfter() {
290
+ if (nextAfterOverride !== undefined)
291
+ return nextAfterOverride;
292
+ if (cachedNextAfter !== undefined)
293
+ return cachedNextAfter;
294
+ try {
295
+ const mod = requireFromHere('next/server');
296
+ cachedNextAfter = typeof mod.after === 'function' ? mod.after : null;
297
+ }
298
+ catch {
299
+ cachedNextAfter = null;
193
300
  }
194
- void p;
301
+ return cachedNextAfter;
302
+ }
303
+ async function finishEphemeralInvoke(runtime) {
304
+ try {
305
+ await waitForOutboundQuiet();
306
+ await _awaitPendingUsageParses();
307
+ await runtime.flushForInvokeEnd();
308
+ }
309
+ catch {
310
+ /* fail-open: metering must not break the customer response */
311
+ }
312
+ }
313
+ async function waitForOutboundQuiet() {
314
+ await delay(0);
315
+ for (;;) {
316
+ if (outboundHttpInFlight() === 0) {
317
+ await delay(invokeFlushQuietMs);
318
+ if (outboundHttpInFlight() === 0)
319
+ return;
320
+ }
321
+ await whenOutboundHttpIdle();
322
+ }
323
+ }
324
+ function delay(ms) {
325
+ return new Promise((resolve) => {
326
+ setTimeout(resolve, ms);
327
+ });
195
328
  }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Public Next.js config wrapper. Registers the entry loader on the Node
3
+ * server build (webpack and Turbopack). Does not change export mode.
4
+ */
5
+ export type NextConfigLike = {
6
+ webpack?: (config: WebpackConfigLike, options: WebpackOptionsLike) => WebpackConfigLike;
7
+ turbopack?: {
8
+ rules?: Record<string, unknown>;
9
+ [key: string]: unknown;
10
+ };
11
+ [key: string]: unknown;
12
+ };
13
+ type WebpackConfigLike = {
14
+ module?: {
15
+ rules?: unknown[];
16
+ };
17
+ [key: string]: unknown;
18
+ };
19
+ type WebpackOptionsLike = {
20
+ isServer?: boolean;
21
+ nextRuntime?: string;
22
+ };
23
+ /**
24
+ * Wrap an existing Next config so Node route, page, and server-action modules
25
+ * are observed. Compose outside other config wrappers:
26
+ *
27
+ * ```ts
28
+ * export default withNextIntl(withNetGreener(nextConfig))
29
+ * ```
30
+ *
31
+ * Also call ``registerNetGreenerNext`` from ``instrumentation.ts``.
32
+ */
33
+ export declare function withNetGreener<T extends NextConfigLike>(nextConfig?: T): T;
34
+ export {};
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Public Next.js config wrapper. Registers the entry loader on the Node
3
+ * server build (webpack and Turbopack). Does not change export mode.
4
+ */
5
+ import { fileURLToPath } from 'node:url';
6
+ const ENTRY_GLOBS = [
7
+ '**/route.ts',
8
+ '**/route.tsx',
9
+ '**/route.js',
10
+ '**/route.jsx',
11
+ '**/page.ts',
12
+ '**/page.tsx',
13
+ '**/page.js',
14
+ '**/page.jsx',
15
+ '**/*action.ts',
16
+ '**/*action.tsx',
17
+ '**/*actions.ts',
18
+ '**/*actions.tsx',
19
+ ];
20
+ function loaderFile() {
21
+ return fileURLToPath(new URL('../loaders/next-entry-loader.cjs', import.meta.url));
22
+ }
23
+ function turbopackRule(loader) {
24
+ return {
25
+ loaders: [loader],
26
+ condition: {
27
+ all: ['node', { not: 'browser' }, { not: 'edge-light' }],
28
+ },
29
+ };
30
+ }
31
+ /**
32
+ * Wrap an existing Next config so Node route, page, and server-action modules
33
+ * are observed. Compose outside other config wrappers:
34
+ *
35
+ * ```ts
36
+ * export default withNextIntl(withNetGreener(nextConfig))
37
+ * ```
38
+ *
39
+ * Also call ``registerNetGreenerNext`` from ``instrumentation.ts``.
40
+ */
41
+ export function withNetGreener(nextConfig = {}) {
42
+ const loader = loaderFile();
43
+ const prevTurbo = nextConfig.turbopack ?? {};
44
+ const prevRules = (prevTurbo.rules ?? {});
45
+ const rules = { ...prevRules };
46
+ for (const glob of ENTRY_GLOBS) {
47
+ if (rules[glob] == null)
48
+ rules[glob] = turbopackRule(loader);
49
+ }
50
+ const prevWebpack = nextConfig.webpack;
51
+ return {
52
+ ...nextConfig,
53
+ turbopack: {
54
+ ...prevTurbo,
55
+ rules,
56
+ },
57
+ webpack(config, options) {
58
+ const serverNode = options.isServer === true && options.nextRuntime !== 'edge';
59
+ if (serverNode) {
60
+ config.module = config.module ?? {};
61
+ config.module.rules = config.module.rules ?? [];
62
+ config.module.rules.push({
63
+ test: /([\\/](route|page)\.(tsx?|jsx?)$)|([\\/][^\\/]*actions?\.(tsx?|jsx?)$)/,
64
+ enforce: 'pre',
65
+ use: [loader],
66
+ });
67
+ }
68
+ if (typeof prevWebpack === 'function')
69
+ return prevWebpack(config, options);
70
+ return config;
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Source transform for the Next.js config wrapper.
3
+ *
4
+ * Turns route, page, and `'use server'` exports into calls to the public
5
+ * runtime helpers. Does not read Next.js internals. Client modules are left
6
+ * unchanged so the server runtime is not pulled into the browser bundle.
7
+ */
8
+ export declare function routeTemplateFromAppFile(filePath: string): string;
9
+ export declare function transformNextEntrySource(source: string, filePath: string): string;
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Source transform for the Next.js config wrapper.
3
+ *
4
+ * Turns route, page, and `'use server'` exports into calls to the public
5
+ * runtime helpers. Does not read Next.js internals. Client modules are left
6
+ * unchanged so the server runtime is not pulled into the browser bundle.
7
+ */
8
+ const HTTP_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'];
9
+ const IMPORT_LINE = "import { observeNextAction as __ngObserveAction, observeNextPage as __ngObservePage, observeNextRoute as __ngObserveRoute } from '@netgreener/runtime/next'\n";
10
+ export function routeTemplateFromAppFile(filePath) {
11
+ const norm = filePath.replace(/\\/g, '/');
12
+ const marker = '/app/';
13
+ const idx = norm.lastIndexOf(marker);
14
+ if (idx < 0) {
15
+ const base = norm.split('/').pop() || 'module';
16
+ return `/${base.replace(/\.(tsx?|jsx?)$/, '')}`;
17
+ }
18
+ let rel = norm.slice(idx + marker.length - 1);
19
+ rel = rel.replace(/\/(route|page)\.(tsx?|jsx?)$/, '');
20
+ rel = rel.replace(/\/\([^/]+\)/g, '');
21
+ if (!rel.startsWith('/'))
22
+ rel = `/${rel}`;
23
+ if (rel.length > 1)
24
+ rel = rel.replace(/\/+$/, '');
25
+ return rel || '/';
26
+ }
27
+ export function transformNextEntrySource(source, filePath) {
28
+ if (isClientModule(source))
29
+ return source;
30
+ if (source.includes('__ngObserveRoute') || source.includes('withNetGreenerRoute')) {
31
+ return source;
32
+ }
33
+ const norm = filePath.replace(/\\/g, '/');
34
+ const isRoute = /\/route\.(tsx?|jsx?)$/.test(norm);
35
+ const isPage = /\/page\.(tsx?|jsx?)$/.test(norm);
36
+ const isAction = isServerActionModule(source);
37
+ if (!isRoute && !isPage && !isAction)
38
+ return source;
39
+ const template = routeTemplateFromAppFile(filePath);
40
+ let next = source;
41
+ const tails = [];
42
+ if (isRoute) {
43
+ const cron = template === '/api/cron' || template.startsWith('/api/cron/');
44
+ for (const method of HTTP_METHODS) {
45
+ const wrapped = wrapHttpExport(next, method, template, cron);
46
+ if (!wrapped)
47
+ continue;
48
+ next = wrapped.code;
49
+ tails.push(wrapped.tail);
50
+ }
51
+ }
52
+ if (isPage) {
53
+ const wrapped = wrapDefaultPage(next, template);
54
+ if (wrapped) {
55
+ next = wrapped.code;
56
+ tails.push(wrapped.tail);
57
+ }
58
+ }
59
+ if (isAction && !isRoute && !isPage) {
60
+ const wrapped = wrapServerActions(next, template);
61
+ next = wrapped.code;
62
+ tails.push(...wrapped.tails);
63
+ }
64
+ if (!tails.length)
65
+ return source;
66
+ return `${insertImport(next)}\n${tails.join('\n')}\n`;
67
+ }
68
+ function insertImport(source) {
69
+ const directive = /^(\uFEFF?\s*['"]use server['"]\s*;?\s*)/;
70
+ const match = directive.exec(source);
71
+ if (!match)
72
+ return `${IMPORT_LINE}${source}`;
73
+ return `${source.slice(0, match[0].length)}${IMPORT_LINE}${source.slice(match[0].length)}`;
74
+ }
75
+ function isClientModule(source) {
76
+ return /^\uFEFF?\s*['"]use client['"]/.test(source);
77
+ }
78
+ function isServerActionModule(source) {
79
+ return /^\uFEFF?\s*['"]use server['"]/.test(source);
80
+ }
81
+ function jsString(value) {
82
+ return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
83
+ }
84
+ function wrapHttpExport(source, method, template, cron) {
85
+ const fn = new RegExp(`export\\s+(async\\s+)?function\\s+${method}\\b`);
86
+ const fnMatch = fn.exec(source);
87
+ if (fnMatch) {
88
+ const code = source.replace(fn, `${fnMatch[1] || ''}function __ng_${method}`);
89
+ const tail = `export const ${method} = __ngObserveRoute(__ng_${method}, ${jsString(method)}, ${jsString(template)}, { cron: ${cron ? 'true' : 'false'} })`;
90
+ return { code, tail };
91
+ }
92
+ const decl = new RegExp(`export\\s+const\\s+${method}\\s*=\\s*`);
93
+ const declMatch = decl.exec(source);
94
+ if (!declMatch || declMatch.index === undefined)
95
+ return null;
96
+ const exprStart = declMatch.index + declMatch[0].length;
97
+ const exprEnd = endOfAssignment(source, exprStart);
98
+ const expr = source.slice(exprStart, exprEnd).replace(/;\s*$/, '');
99
+ const code = source.slice(0, declMatch.index) +
100
+ `const __ng_${method} = ${expr}\n` +
101
+ source.slice(exprEnd);
102
+ const tail = `export const ${method} = __ngObserveRoute(__ng_${method}, ${jsString(method)}, ${jsString(template)}, { cron: ${cron ? 'true' : 'false'} })`;
103
+ return { code, tail };
104
+ }
105
+ function wrapDefaultPage(source, template) {
106
+ const fn = /export\s+default\s+(async\s+)?function\s+([A-Za-z0-9_]+)\b/;
107
+ const fnMatch = fn.exec(source);
108
+ if (fnMatch) {
109
+ const code = source.replace(fn, `${fnMatch[1] || ''}function ${fnMatch[2]}`);
110
+ return {
111
+ code,
112
+ tail: `export default __ngObservePage(${fnMatch[2]}, ${jsString(template)})`,
113
+ };
114
+ }
115
+ const ident = /export\s+default\s+([A-Za-z0-9_]+)\s*;?/;
116
+ const identMatch = ident.exec(source);
117
+ if (!identMatch)
118
+ return null;
119
+ const code = source.replace(ident, '');
120
+ return {
121
+ code,
122
+ tail: `export default __ngObservePage(${identMatch[1]}, ${jsString(template)})`,
123
+ };
124
+ }
125
+ function wrapServerActions(source, template) {
126
+ let code = source;
127
+ const tails = [];
128
+ const fn = /export\s+(async\s+)?function\s+([A-Za-z0-9_]+)\b/g;
129
+ const names = [];
130
+ for (const match of code.matchAll(fn)) {
131
+ const name = match[2];
132
+ if (!name || HTTP_METHODS.includes(name))
133
+ continue;
134
+ names.push({ name, asyncKw: match[1] || '' });
135
+ }
136
+ for (const { name, asyncKw } of names) {
137
+ const one = new RegExp(`export\\s+(async\\s+)?function\\s+${name}\\b`);
138
+ if (!one.test(code))
139
+ continue;
140
+ code = code.replace(one, `${asyncKw}function __ng_action_${name}`);
141
+ tails.push(`export const ${name} = __ngObserveAction(__ng_action_${name}, ${jsString(name)}, ${jsString(template)})`);
142
+ }
143
+ return { code, tails };
144
+ }
145
+ function endOfAssignment(source, exprStart) {
146
+ let i = exprStart;
147
+ let depth = 0;
148
+ let quote = null;
149
+ while (i < source.length) {
150
+ const c = source[i];
151
+ if (quote) {
152
+ if (c === '\\') {
153
+ i += 2;
154
+ continue;
155
+ }
156
+ if (c === quote)
157
+ quote = null;
158
+ i += 1;
159
+ continue;
160
+ }
161
+ if (c === '"' || c === "'" || c === '`') {
162
+ quote = c;
163
+ i += 1;
164
+ continue;
165
+ }
166
+ if (c === '(' || c === '[' || c === '{') {
167
+ depth += 1;
168
+ i += 1;
169
+ continue;
170
+ }
171
+ if (c === ')' || c === ']' || c === '}') {
172
+ depth = Math.max(0, depth - 1);
173
+ i += 1;
174
+ continue;
175
+ }
176
+ if (depth === 0 && (c === ';' || c === '\n'))
177
+ return i;
178
+ i += 1;
179
+ }
180
+ return source.length;
181
+ }
package/dist/runtime.d.ts CHANGED
@@ -54,8 +54,14 @@ export declare class NetGreenerRuntime {
54
54
  /**
55
55
  * Mark end of an inbound request/task. In ephemeral mode, schedules a flush
56
56
  * when no requests remain in flight (safe under concurrency).
57
+ *
58
+ * ``deferInvokeFlush`` only skips that idle flush. The Next.js adapter uses
59
+ * it so the upload runs from ``after()`` / ``waitUntil`` after the response
60
+ * closes. Express, Fastify, and Lambda callers keep the default.
57
61
  */
58
- endRequest(): void;
62
+ endRequest(opts?: {
63
+ deferInvokeFlush?: boolean;
64
+ }): void;
59
65
  /** Explicit serverless invoke-end flush (Lambda finally / platform adapter). */
60
66
  flushForInvokeEnd(): Promise<UploadResult | null>;
61
67
  /** Test helper: in-flight request counter. */
@@ -70,6 +76,7 @@ export declare class NetGreenerRuntime {
70
76
  cpuTimeMs?: number;
71
77
  /** Measured RSS KiB at request end. */
72
78
  peakRssKb?: number;
79
+ unitType?: string;
73
80
  }): void;
74
81
  /** Record a background job / worker task sample (BullMQ, cron, scripts). */
75
82
  recordTask(sample: {
package/dist/runtime.js CHANGED
@@ -8,10 +8,31 @@ import { attachWindowTenantToRunContext, getTenantContext, tenantConfigFromRunti
8
8
  import { enrichRunContextForAnomaly } from './runContextEnrichment.js';
9
9
  import { getOccupancyTracker } from './occupancyTracker.js';
10
10
  import { getExternalAggregator, getOriginalFetch, installOutboundInstrumentation, } from './externalApiMeter.js';
11
+ import { buildMcpLatencyV0, getMcpToolLedger, } from './mcpToolMeter.js';
11
12
  import { CPU_SOURCE_PROCESS, MEMORY_SOURCE_PROCESS, } from './processResources.js';
12
13
  import { CPU_SOURCE_DURATION_PROXY } from './n4/missingnessInventory.js';
13
14
  import { buildRuntimeHealthV0, markHooksActive, mergeHealthIntoMetadata, noteExportAttempt, noteExportMode, noteExportResult, noteFlushSkippedInFlight, _resetRuntimeHealthForTests, } from './runtimeHealth.js';
14
15
  import { resolveLifecycle, } from './lifecycle.js';
16
+ function vercelDeploymentHosts() {
17
+ const hosts = [];
18
+ for (const key of ['VERCEL_URL', 'VERCEL_BRANCH_URL', 'VERCEL_PROJECT_PRODUCTION_URL']) {
19
+ const raw = String(process.env[key] || '').trim();
20
+ if (!raw)
21
+ continue;
22
+ try {
23
+ const host = (raw.includes('://') ? new URL(raw).hostname : raw.split('/')[0] || '')
24
+ .toLowerCase()
25
+ .replace(/^\*\./, '')
26
+ .replace(/^www\./, '');
27
+ if (host)
28
+ hosts.push(host);
29
+ }
30
+ catch {
31
+ /* ignore a malformed deployment host */
32
+ }
33
+ }
34
+ return hosts;
35
+ }
15
36
  /**
16
37
  * Process-wide runtime controller: record samples, periodic flush, shutdown flush.
17
38
  * Ephemeral lifecycle skips the periodic timer and flushes at invoke/request idle.
@@ -60,10 +81,13 @@ export class NetGreenerRuntime {
60
81
  if (this.outboundInstalled || !this.enabled)
61
82
  return;
62
83
  this.outboundInstalled = true;
63
- const firstPartyHosts = String(process.env.NETGREENER_FIRST_PARTY_HOSTS || '')
64
- .split(',')
65
- .map((h) => h.trim().toLowerCase().replace(/^\*\./, '').replace(/^www\./, ''))
66
- .filter(Boolean);
84
+ const firstPartyHosts = [
85
+ ...String(process.env.NETGREENER_FIRST_PARTY_HOSTS || '')
86
+ .split(',')
87
+ .map((h) => h.trim().toLowerCase().replace(/^\*\./, '').replace(/^www\./, ''))
88
+ .filter(Boolean),
89
+ ...vercelDeploymentHosts(),
90
+ ];
67
91
  try {
68
92
  const apiHost = new URL(this.config.apiUrl).hostname;
69
93
  const excluded = [...(apiHost ? [apiHost] : []), ...firstPartyHosts];
@@ -109,12 +133,18 @@ export class NetGreenerRuntime {
109
133
  /**
110
134
  * Mark end of an inbound request/task. In ephemeral mode, schedules a flush
111
135
  * when no requests remain in flight (safe under concurrency).
136
+ *
137
+ * ``deferInvokeFlush`` only skips that idle flush. The Next.js adapter uses
138
+ * it so the upload runs from ``after()`` / ``waitUntil`` after the response
139
+ * closes. Express, Fastify, and Lambda callers keep the default.
112
140
  */
113
- endRequest() {
141
+ endRequest(opts) {
114
142
  if (this.inFlight > 0)
115
143
  this.inFlight -= 1;
116
144
  if (this.lifecycle !== 'ephemeral')
117
145
  return;
146
+ if (opts?.deferInvokeFlush)
147
+ return;
118
148
  if (this.invokeFlushScheduled)
119
149
  return;
120
150
  this.invokeFlushScheduled = true;
@@ -151,7 +181,7 @@ export class NetGreenerRuntime {
151
181
  const serviceUnit = `${sample.method.toUpperCase()} ${sample.path}`;
152
182
  this.aggregator.record({
153
183
  serviceUnit,
154
- unitType: 'http_route',
184
+ unitType: sample.unitType || 'http_route',
155
185
  durationMs: sample.durationMs,
156
186
  error: sample.statusCode >= 400,
157
187
  tenantId: getTenantContext()?.tenantId ?? null,
@@ -191,6 +221,7 @@ export class NetGreenerRuntime {
191
221
  if (!hasRuntime && !hasExternal)
192
222
  return null;
193
223
  this.flushing = true;
224
+ let mcpSnapshot = null;
194
225
  noteExportMode(this.exporter.mode);
195
226
  const snapshot = hasRuntime ? this.aggregator.takeSnapshot() : null;
196
227
  const externalSnapshot = hasExternal ? externalAgg.takeSnapshot() : null;
@@ -230,6 +261,14 @@ export class NetGreenerRuntime {
230
261
  return null;
231
262
  }
232
263
  const externalV0 = externalSnapshot ? externalSnapshot.buildV0() : null;
264
+ const mcpLedger = getMcpToolLedger();
265
+ mcpSnapshot = mcpLedger.hasCalls() ? mcpLedger.takeSnapshot() : null;
266
+ const mcpV0 = mcpSnapshot ? mcpSnapshot.buildV0() : null;
267
+ if (mcpSnapshot && !mcpV0) {
268
+ mcpLedger.mergeSnapshot(mcpSnapshot);
269
+ mcpSnapshot = null;
270
+ }
271
+ const latencyV0 = buildMcpLatencyV0(mcpV0, externalV0 ?? null, windowSeconds);
233
272
  const end = new Date();
234
273
  const start = new Date(end.getTime() - windowSeconds * 1000);
235
274
  // Reuse sticky id until success so retries do not mint a new window.
@@ -264,6 +303,8 @@ export class NetGreenerRuntime {
264
303
  run_context: runContext,
265
304
  ...(runtimeV0 ? { service_runtime_v0: runtimeV0 } : {}),
266
305
  ...(externalV0 ? { external_api_v0: externalV0 } : {}),
306
+ ...(mcpV0 ? { mcp_tool_v0: mcpV0 } : {}),
307
+ ...(latencyV0 ? { mcp_latency_v0: latencyV0 } : {}),
267
308
  measurement_provenance: {
268
309
  cpu_source: runtimeV0
269
310
  ? measuredCpu
@@ -316,6 +357,8 @@ export class NetGreenerRuntime {
316
357
  this.aggregator.mergeSnapshot(snapshot);
317
358
  if (externalSnapshot)
318
359
  externalAgg.mergeSnapshot(externalSnapshot);
360
+ if (mcpSnapshot)
361
+ getMcpToolLedger().mergeSnapshot(mcpSnapshot);
319
362
  // Keep stickyWindowId so the next flush retries the same window id.
320
363
  }
321
364
  else {
@@ -330,6 +373,8 @@ export class NetGreenerRuntime {
330
373
  this.aggregator.mergeSnapshot(snapshot);
331
374
  if (externalSnapshot)
332
375
  externalAgg.mergeSnapshot(externalSnapshot);
376
+ if (mcpSnapshot)
377
+ getMcpToolLedger().mergeSnapshot(mcpSnapshot);
333
378
  const result = {
334
379
  ok: false,
335
380
  error: err instanceof Error ? err.message : String(err),