@netgreener/runtime 0.1.9 → 0.1.11
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/CHANGELOG.md +20 -0
- package/dist/aggregator.d.ts +2 -0
- package/dist/aggregator.js +33 -13
- package/dist/analyze/buildResourceFindings.d.ts +1 -1
- package/dist/analyze/buildResourceFindings.js +4 -2
- package/dist/analyze/findingGuidance.d.ts +14 -0
- package/dist/analyze/findingGuidance.js +52 -0
- package/dist/analyze/index.d.ts +3 -2
- package/dist/analyze/index.js +3 -2
- package/dist/analyze/projectScan.d.ts +3 -1
- package/dist/analyze/projectScan.js +29 -6
- package/dist/analyze/resourceFindingCandidate.d.ts +6 -0
- package/dist/analyze/resourceFindingCandidate.js +11 -0
- package/dist/analyze/serviceDiscovery.d.ts +23 -1
- package/dist/analyze/serviceDiscovery.js +164 -4
- package/dist/externalApiMeter.d.ts +8 -1
- package/dist/externalApiMeter.js +118 -25
- package/dist/index.d.ts +3 -1
- package/dist/index.js +3 -1
- package/dist/managedCollectorLauncher.d.ts +2 -1
- package/dist/managedCollectorLauncher.js +2 -1
- package/dist/mcpToolMeter.d.ts +101 -0
- package/dist/mcpToolMeter.js +496 -0
- package/dist/next.d.ts +28 -0
- package/dist/next.js +143 -10
- package/dist/nextConfig.d.ts +34 -0
- package/dist/nextConfig.js +73 -0
- package/dist/nextEntryTransform.d.ts +9 -0
- package/dist/nextEntryTransform.js +181 -0
- package/dist/runtime.d.ts +12 -6
- package/dist/runtime.js +113 -52
- package/dist/runtimeHealth.js +1 -1
- package/dist/tenantContext.d.ts +3 -0
- package/dist/tenantContext.js +35 -9
- package/dist/types.d.ts +8 -0
- package/examples/azure-functions-gate/.funcignore +6 -0
- package/examples/azure-functions-gate/README.md +25 -0
- package/examples/azure-functions-gate/host.json +15 -0
- package/examples/azure-functions-gate/package-lock.json +161 -0
- package/examples/azure-functions-gate/package.json +14 -0
- package/examples/azure-functions-gate/src/functions/health.js +27 -0
- package/fixtures/git/canonical_git_key_vectors.v1.json +66 -0
- package/loaders/next-entry-loader.cjs +14 -0
- package/package.json +3 -1
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
|
|
135
|
+
headers: headersAsRecord(req?.headers),
|
|
115
136
|
};
|
|
116
|
-
|
|
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
|
-
|
|
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
|
-
|
|
190
|
-
|
|
191
|
-
|
|
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
|
-
|
|
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
|
@@ -37,11 +37,9 @@ export declare class NetGreenerRuntime {
|
|
|
37
37
|
/** In-flight HTTP/task units — gates ephemeral idle flush. */
|
|
38
38
|
private inFlight;
|
|
39
39
|
private invokeFlushScheduled;
|
|
40
|
-
/**
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
*/
|
|
44
|
-
private stickyWindowId;
|
|
40
|
+
/** Exact pending window; observations arriving during retries stay separate. */
|
|
41
|
+
private pendingPayload;
|
|
42
|
+
private cpuWindowMark;
|
|
45
43
|
constructor(opts?: NetGreenerRuntimeOptions);
|
|
46
44
|
get lifecycle(): ResolvedRuntimeLifecycle['lifecycle'];
|
|
47
45
|
get enabled(): boolean;
|
|
@@ -54,8 +52,14 @@ export declare class NetGreenerRuntime {
|
|
|
54
52
|
/**
|
|
55
53
|
* Mark end of an inbound request/task. In ephemeral mode, schedules a flush
|
|
56
54
|
* when no requests remain in flight (safe under concurrency).
|
|
55
|
+
*
|
|
56
|
+
* ``deferInvokeFlush`` only skips that idle flush. The Next.js adapter uses
|
|
57
|
+
* it so the upload runs from ``after()`` / ``waitUntil`` after the response
|
|
58
|
+
* closes. Express, Fastify, and Lambda callers keep the default.
|
|
57
59
|
*/
|
|
58
|
-
endRequest(
|
|
60
|
+
endRequest(opts?: {
|
|
61
|
+
deferInvokeFlush?: boolean;
|
|
62
|
+
}): void;
|
|
59
63
|
/** Explicit serverless invoke-end flush (Lambda finally / platform adapter). */
|
|
60
64
|
flushForInvokeEnd(): Promise<UploadResult | null>;
|
|
61
65
|
/** Test helper: in-flight request counter. */
|
|
@@ -70,6 +74,7 @@ export declare class NetGreenerRuntime {
|
|
|
70
74
|
cpuTimeMs?: number;
|
|
71
75
|
/** Measured RSS KiB at request end. */
|
|
72
76
|
peakRssKb?: number;
|
|
77
|
+
unitType?: string;
|
|
73
78
|
}): void;
|
|
74
79
|
/** Record a background job / worker task sample (BullMQ, cron, scripts). */
|
|
75
80
|
recordTask(sample: {
|
|
@@ -80,6 +85,7 @@ export declare class NetGreenerRuntime {
|
|
|
80
85
|
cpuTimeMs?: number;
|
|
81
86
|
peakRssKb?: number;
|
|
82
87
|
}): void;
|
|
88
|
+
private exportPendingWindow;
|
|
83
89
|
flush(kind?: FlushKind): Promise<UploadResult | null>;
|
|
84
90
|
shutdown(): Promise<UploadResult | null>;
|
|
85
91
|
}
|