@lensmcp/node-instrumentation 1.25.79 → 1.26.1

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Zero-touch Node runtime taps for [LensMCP](https://github.com/kiwiapps-ltd/lensmcp) — the observability lens for coding agents.
4
4
 
5
- `@lensmcp/node-instrumentation` instruments a running Node.js service **without touching its source**. It is loaded by the runner via `node --require @lensmcp/node-instrumentation/register`, before your app bundle, so it can patch Node built-ins and external modules (`fs`, `fetch`/`http(s)`, `child_process`, `pg`, `ioredis`, `bullmq`, `@nestjs/core`, `@nestjs/common`) and the process streams **in place**. As your service runs, those patches emit LensMCP events onto the bus that the dashboard and MCP server consume.
5
+ `@lensmcp/node-instrumentation` instruments a running Node.js service **without touching its source**. It is loaded by the runner via `node --require @lensmcp/node-instrumentation/register`, before your app bundle, so it can patch Node built-ins and external modules (`fs`, `fetch`/`http(s)`, `child_process`, `pg`, `mysql2`, `ioredis`, `bullmq`, `kafkajs`, `@nestjs/core`, `@nestjs/common`) and the process streams **in place**. As your service runs, those patches emit LensMCP events onto the bus that the dashboard and MCP server consume.
6
6
 
7
7
  The whole point is that the host stays completely ordinary. There are no emit helpers, no `createLensmcpNestApp`, no dual-mode bootstrap — your `main.ts` looks exactly like an uninstrumented service. Requiring the module *is* the installation: it must run before the app loads so the require hook sees every external on first `require`/`import`. Every tap is wrapped in `try/catch` and the bus writer fails silently, so instrumentation can never throw into — or break — the host.
8
8
 
@@ -69,7 +69,7 @@ lensEmitCustom({ kind: 'traffic', name: 'meta', event: 'inbound', channel: 'webh
69
69
 
70
70
  ## What it taps
71
71
 
72
- Built-ins and globals are patched at install; external modules (`pg`, `ioredis`, `bullmq`, `@nestjs/core`, `@nestjs/common`) are patched lazily through a require hook the first time they load.
72
+ Built-ins and globals are patched at install; external modules (`pg`, `mysql2`, `ioredis`, `bullmq`, `kafkajs`, `@nestjs/core`, `@nestjs/common`) are patched lazily through a require hook the first time they load.
73
73
 
74
74
  | Layer | How it's patched | Emits (source / kind) |
75
75
  |---|---|---|
@@ -77,8 +77,10 @@ Built-ins and globals are patched at install; external modules (`pg`, `ioredis`,
77
77
  | Network egress | global `fetch` + `http`/`https.request` wrap | `external` / `egress` — outbound method, host, status, duration (internal/loopback/RFC1918 destinations skipped) |
78
78
  | Child processes | `child_process` spawn/fork/exec/execFile (+ sync forms) | `exec` / `exec` — command, exit code/signal, duration |
79
79
  | Postgres | require hook → `pg` `Client.prototype.query` | `db` / `db-query` — op, table, query, params, row count, duration |
80
+ | MySQL | require hook → `mysql2` / `mysql2/promise` connection `query`/`execute`/prepared `execute`, pool checkouts | `db` / `db-query` (`name: 'mysql'`, `driver: 'mysql2'`) — the Postgres row's fields, plus `affectedRows` for a write |
80
81
  | Redis | require hook → `ioredis` `Redis.prototype.sendCommand` | `redis` / `redis-op` — op, key, command (BullMQ traffic and housekeeping excluded; rate-capped) |
81
- | Queues | require hook → `bullmq` `Queue`/`Worker` prototypes | `queue` / `queue-enqueued`, `queue-active`, `queue-completed`, `queue-failed`, `queue-process`, plus a 2s `queue-state` snapshot |
82
+ | Queues | require hook → `bullmq` `Queue`/`Worker`/`Job` prototypes | `queue` / `queue-enqueued`, `queue-active`, `queue-completed`, `queue-failed`, `queue-process`, plus a 2s `queue-state` snapshot. `queue-process` says how the run ended (`status`): `ok`; `error` (with `attempt`, and `attempts` when the job retries); or, at `info`, what the processor asked the queue for by throwing — `delayed` (`DelayedError` after `moveToDelayed`, with `delayMs`), `waiting-children`, `waiting`, `rate-limited` |
83
+ | Kafka | require hook → `kafkajs` producers (`send`, `sendBatch`, transactions) and consumers (`run` → `eachMessage`/`eachBatch`) | `queue` / `queue-enqueued`, `queue-process`, `queue-failed` (`broker: 'kafka'`, `queue` = topic); the flow rides the message in `x-lensmcp-*` headers |
82
84
  | NestJS | require hook → `@nestjs/core` `NestFactory.create` grafts `LensmcpModule` | the events from [`@lensmcp/nest-instrumentation`](https://github.com/kiwiapps-ltd/lensmcp) — class traces, request flows, memory |
83
85
  | stdout / stderr | `process.stdout`/`stderr` `write` wrap | `nestjs` / `runtime` — one log event per line (original output is preserved) |
84
86
  | Logger calls | require hook → `@nestjs/common` `Logger` prototype + statics | `nestjs` / `runtime` — one log event per call made **inside a request or a job**, at every level, before the app's own level filter (`raw.stream: "logger"`, with the logger's context and level); redacted at capture; flood-guarded per logger and message shape. A line both logged and printed is one event. |
@@ -0,0 +1,56 @@
1
+ type ResolveContext = {
2
+ conditions: string[];
3
+ parentURL: string | undefined;
4
+ importAttributes?: Record<string, string>;
5
+ };
6
+ type ResolveOut = {
7
+ url: string;
8
+ format?: string | null;
9
+ shortCircuit?: boolean;
10
+ };
11
+ type LoadOut = {
12
+ format: string | null | undefined;
13
+ source?: string | ArrayBuffer | NodeJS.TypedArray;
14
+ shortCircuit?: boolean;
15
+ };
16
+ type ResolveNext<R> = (s: string, c?: Partial<ResolveContext>) => R;
17
+ type LoadNext<R> = (u: string, c?: never) => R;
18
+ export interface Tap {
19
+ /** The specifier as imported: a tapped package or a subpath of one. */
20
+ name: string;
21
+ /** The importing file's URL: `require` resolves from there, as a CommonJS importer's would. */
22
+ from: string;
23
+ /** The tapped package a subpath belongs to — required first, so its tap runs. */
24
+ pkg?: string;
25
+ }
26
+ /** The resolved file's own URL, marked: `import.meta.resolve` still names a file, and the load hook knows to route it. */
27
+ export declare function tapUrl(name: string, parentURL: string, resolvedURL?: string, pkg?: string): string;
28
+ export declare function parseTapUrl(url: string): Tap | undefined;
29
+ /** The module text that hands an ESM importer what `require` loaded: its exports as default, each key by name. */
30
+ export declare function tapModuleSource(name: string, from: string, exportsObject: unknown, pkg?: string): string;
31
+ /** In-thread resolve hook (`module.registerHooks`). */
32
+ export declare function esmTapResolve(specifier: string, context: ResolveContext, next: ResolveNext<ResolveOut>): ResolveOut;
33
+ /** In-thread load hook (`module.registerHooks`). */
34
+ export declare function esmTapLoad(url: string, context: unknown, next: LoadNext<LoadOut>): LoadOut;
35
+ /** Off-thread hooks (`module.register`, Node without `registerHooks`): the packages come from the main thread. */
36
+ export declare function initialize(data?: {
37
+ packages?: string[];
38
+ }): void;
39
+ export declare function resolve(specifier: string, context: ResolveContext, next: ResolveNext<Promise<ResolveOut>>): Promise<ResolveOut>;
40
+ export declare function load(url: string, context: unknown, next: LoadNext<Promise<LoadOut>>): Promise<LoadOut>;
41
+ export type EsmTapMode = 'in-thread' | 'off-thread';
42
+ interface ModuleHooksApi {
43
+ registerHooks?: (hooks: {
44
+ resolve: typeof esmTapResolve;
45
+ load: typeof esmTapLoad;
46
+ }) => unknown;
47
+ register?: (specifier: string, options: {
48
+ data: unknown;
49
+ }) => void;
50
+ }
51
+ /**
52
+ * Install the hooks: in-thread where Node has `module.registerHooks` (22.15+, 23.5+), else off-thread through
53
+ * `module.register` (20.6+, 22.x), whose thread reads each package once more for its export names. Undefined: neither.
54
+ */
55
+ export declare function installEsmTaps(mod?: ModuleHooksApi): EsmTapMode | undefined;
56
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";var c=Object.defineProperty;var s=(e,t)=>c(e,"name",{value:t,configurable:!0});var u=Object.defineProperty,o=s((e,t)=>u(e,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tapUrl=tapUrl,exports.parseTapUrl=parseTapUrl,exports.tapModuleSource=tapModuleSource,exports.esmTapResolve=esmTapResolve,exports.esmTapLoad=esmTapLoad,exports.initialize=initialize,exports.resolve=resolve,exports.load=load,exports.installEsmTaps=installEsmTaps;const node_module_1=require("node:module"),node_url_1=require("node:url"),tapped_packages_1=require("./tapped-packages"),MARK="lensmcp-tap",NOT_CODE=/\.(?:json|node|wasm)$/i;function tapUrl(e,t,r="file:///",a=e){const n=new URLSearchParams({[MARK]:e,from:t,...a!==e?{pkg:a}:{}});return`${r}${r.includes("?")?"&":"?"}${n}`}s(tapUrl,"tapUrl"),o(tapUrl,"tapUrl");function parseTapUrl(e){if(!e.startsWith("file:")||!e.includes(`${MARK}=`))return;let t;try{t=new URL(e).searchParams}catch{return}const r=t.get(MARK),a=t.get("from"),n=t.get("pkg");return r&&a?{name:r,from:a,...n?{pkg:n}:{}}:void 0}s(parseTapUrl,"parseTapUrl"),o(parseTapUrl,"parseTapUrl");function tapModuleSource(e,t,r,a=e){const n=r&&(typeof r=="object"||typeof r=="function")?Object.keys(r).filter(i=>i!=="default"&&i!=="module.exports"):[];return["import { createRequire } from 'node:module';",`const r = createRequire(${JSON.stringify(t)});`,...a!==e?[`try { r(${JSON.stringify(a)}); } catch {}`]:[],`const m = r(${JSON.stringify(e)});`,"export default m;","export { m as 'module.exports' };",...n.map((i,p)=>`const e${p} = m[${JSON.stringify(i)}];`),...n.length?[`export { ${n.map((i,p)=>`e${p} as ${JSON.stringify(i)}`).join(", ")} };`]:[]].join(`
2
+ `)}s(tapModuleSource,"tapModuleSource"),o(tapModuleSource,"tapModuleSource");const pathOf=o(e=>e.startsWith("file:")?(0,node_url_1.fileURLToPath)(e):e,"pathOf");function requireReaches(e,t){try{return!NOT_CODE.test((0,node_module_1.createRequire)(pathOf(t)).resolve(e))}catch{return!1}}s(requireReaches,"requireReaches"),o(requireReaches,"requireReaches");function routeOf(e,t){if(!(!t.parentURL?.startsWith("file:")||t.conditions.includes("require"))&&!t.importAttributes?.type)return(0,tapped_packages_1.tappedPackageOf)(e)}s(routeOf,"routeOf"),o(routeOf,"routeOf");function routed(e,t,r,a){return!a.url.startsWith("file:")||NOT_CODE.test(a.url.split("?")[0])||!requireReaches(e,t)?a:{url:tapUrl(e,t,a.url,r),format:"module",shortCircuit:!0}}s(routed,"routed"),o(routed,"routed");function tapLoad(e){const t=pathOf(e.from),r=(0,node_module_1.createRequire)(t);if(e.pkg)try{r(e.pkg)}catch{}return{format:"module",source:tapModuleSource(e.name,t,r(e.name),e.pkg),shortCircuit:!0}}s(tapLoad,"tapLoad"),o(tapLoad,"tapLoad");function esmTapResolve(e,t,r){const a=routeOf(e,t);return a?routed(e,t.parentURL,a,r(e,t)):r(e,t)}s(esmTapResolve,"esmTapResolve"),o(esmTapResolve,"esmTapResolve");function esmTapLoad(e,t,r){const a=parseTapUrl(e);return a?tapLoad(a):r(e,t)}s(esmTapLoad,"esmTapLoad"),o(esmTapLoad,"esmTapLoad");function initialize(e){e?.packages&&(0,tapped_packages_1.addTappedPackages)(e.packages)}s(initialize,"initialize"),o(initialize,"initialize");async function resolve(e,t,r){const a=routeOf(e,t);return a?routed(e,t.parentURL,a,await r(e,t)):r(e,t)}s(resolve,"resolve"),o(resolve,"resolve");async function load(e,t,r){const a=parseTapUrl(e);return a?tapLoad(a):r(e,t)}s(load,"load"),o(load,"load");const INSTALLED=Symbol.for("lensmcp.esmTaps");function installEsmTaps(e=require("node:module")){const t=globalThis;if(t[INSTALLED])return t[INSTALLED];if(typeof e.registerHooks=="function")return e.registerHooks({resolve:esmTapResolve,load:esmTapLoad}),t[INSTALLED]="in-thread";if(typeof e.register=="function")return e.register((0,node_url_1.pathToFileURL)(__filename).href,{data:{packages:[...(0,tapped_packages_1.tappedPackages)()]}}),t[INSTALLED]="off-thread"}s(installEsmTaps,"installEsmTaps"),o(installEsmTaps,"installEsmTaps");
@@ -34,6 +34,15 @@ interface LiveCtx {
34
34
  dbCallCount?: number;
35
35
  /** Its DB calls by second — nest-instrumentation's `dbSeconds`, read by its loop detector. */
36
36
  dbSeconds?: Map<number, number>;
37
+ /** Its DB calls in order, by statement shape — nest-instrumentation's `dbShapes`: a loop is one shape repeated. */
38
+ dbShapes?: {
39
+ base: number;
40
+ entries: Array<{
41
+ s: string;
42
+ v?: number;
43
+ r?: true;
44
+ }>;
45
+ };
37
46
  redisCallCount?: number;
38
47
  externalCallCount?: number;
39
48
  /** Hops this request made to the cluster's own services (tap-egress `hopHeaders`, `nextHopHeaders`): `<request>.<n>`. */
@@ -45,6 +54,10 @@ type CtxGetter = () => LiveCtx | undefined;
45
54
  * this package reads that one only by its context, never imports it.
46
55
  */
47
56
  export declare function countDbSecond(ctx: LiveCtx, at: number): void;
57
+ /** One DB call by shape and values' hash — nest-instrumentation's `noteDbShape`, kept in step (1,024 kept). */
58
+ export declare function noteDbShape(ctx: LiveCtx, shape: string, value?: number): void;
59
+ /** FNV-1a of a call's values as text (nest-instrumentation's `hashDbValues`): never emitted, only compared. */
60
+ export declare function hashDbValues(values: readonly string[] | undefined): number;
48
61
  type CtxRunner = <T>(ctx: {
49
62
  sessionId: string;
50
63
  requestId: string;
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var r=(t,e)=>l(t,"name",{value:e,configurable:!0});var d=Object.defineProperty,o=r((t,e)=>d(t,"name",{value:e,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.FLOW_START=exports.CONTEXT_END=void 0,exports.countDbSecond=countDbSecond,exports.flowContextStatus=flowContextStatus,exports.resetFlowContextForTests=resetFlowContextForTests,exports.isRequireEsmError=isRequireEsmError,exports.isModuleNotFoundError=isModuleNotFoundError,exports.primeFlowContext=primeFlowContext,exports.attachContextEnd=attachContextEnd,exports.contextEndOf=contextEndOf,exports.startLiveFlow=startLiveFlow,exports.runInFlowContext=runInFlowContext,exports.liveFlowContext=liveFlowContext,exports.flowContext=flowContext;function countDbSecond(t,e){let n=t.dbSeconds;n||(t.dbSeconds=n=new Map);const s=Math.floor(e/1e3);n.set(s,(n.get(s)??0)+1),n.size>4096&&n.delete(n.keys().next().value)}r(countDbSecond,"countDbSecond"),o(countDbSecond,"countDbSecond");let getCtx=null,runWith=null,status={state:"not-primed"},warned=!1;function flowContextStatus(){return status}r(flowContextStatus,"flowContextStatus"),o(flowContextStatus,"flowContextStatus");function resetFlowContextForTests(){getCtx=null,runWith=null,status={state:"not-primed"},warned=!1}r(resetFlowContextForTests,"resetFlowContextForTests"),o(resetFlowContextForTests,"resetFlowContextForTests");function isRequireEsmError(t){const e=t?.code;return e==="ERR_REQUIRE_ESM"||e==="ERR_REQUIRE_ASYNC_MODULE"}r(isRequireEsmError,"isRequireEsmError"),o(isRequireEsmError,"isRequireEsmError");function isModuleNotFoundError(t){const e=t;return e?.code!=="MODULE_NOT_FOUND"&&e?.code!=="ERR_MODULE_NOT_FOUND"?!1:String(e?.message??"").includes("@lensmcp/nest-instrumentation")}r(isModuleNotFoundError,"isModuleNotFoundError"),o(isModuleNotFoundError,"isModuleNotFoundError");function requireNestInstrumentation(){return require("@lensmcp/nest-instrumentation")}r(requireNestInstrumentation,"requireNestInstrumentation"),o(requireNestInstrumentation,"requireNestInstrumentation");function primeFlowContext(t=requireNestInstrumentation){try{const e=t();getCtx=e.currentLensmcpContext,runWith=e.runInLensmcpContext,status={state:"ready"}}catch(e){if(getCtx=null,runWith=null,isModuleNotFoundError(e)){status={state:"absent"};return}const n=e instanceof Error?e.message:String(e);if(status=isRequireEsmError(e)?{state:"runtime-too-old",detail:n}:{state:"failed",detail:n},!warned){warned=!0;const s=status.state==="runtime-too-old"?`this Node (${process.version}) cannot require an ESM package; @lensmcp/node-instrumentation needs >=20.19`:n;console.warn(`[lensmcp] flow correlation is OFF \u2014 could not load @lensmcp/nest-instrumentation: ${s}`)}}}r(primeFlowContext,"primeFlowContext"),o(primeFlowContext,"primeFlowContext"),exports.CONTEXT_END=Symbol.for("lensmcp.contextEnd");function attachContextEnd(t){let e=!1;const n=[],s={get ended(){return e},onEnd(u){e?runEndListener(u):n.push(u)}};return Object.defineProperty(t,exports.CONTEXT_END,{value:s}),()=>{if(!e){e=!0;for(const u of n.splice(0))runEndListener(u)}}}r(attachContextEnd,"attachContextEnd"),o(attachContextEnd,"attachContextEnd");function runEndListener(t){try{t()}catch{}}r(runEndListener,"runEndListener"),o(runEndListener,"runEndListener");function contextEndOf(t){const e=t?.[exports.CONTEXT_END];return e&&typeof e.onEnd=="function"?e:void 0}r(contextEndOf,"contextEndOf"),o(contextEndOf,"contextEndOf"),exports.FLOW_START=Symbol.for("lensmcp.flowStart");function startLiveFlow(){const t=liveFlowContext();if(!t)return;if(t.flowId)return t.flowId;const e=t[exports.FLOW_START];if(typeof e=="function")try{return e()??t.flowId}catch{return t.flowId}}r(startLiveFlow,"startLiveFlow"),o(startLiveFlow,"startLiveFlow");function runInFlowContext(t,e){if(!runWith)return e();const n={sessionId:"pending",requestId:t.requestId,...t.flowId?{flowId:t.flowId}:{}},s=attachContextEnd(n);let u;try{u=runWith(n,e)}catch{return s(),e()}const i=u;return i&&typeof i.then=="function"?i.then(c=>(s(),c),c=>{throw s(),c}):(s(),u)}r(runInFlowContext,"runInFlowContext"),o(runInFlowContext,"runInFlowContext");function liveFlowContext(){try{return getCtx?.()}catch{return}}r(liveFlowContext,"liveFlowContext"),o(liveFlowContext,"liveFlowContext");function flowContext(){const t=liveFlowContext();if(t)return{...t.flowId?{flowId:t.flowId}:{},...t.requestId?{requestId:t.requestId}:{},...t.runId?{runId:t.runId}:{},...t.originNodeId?{originNodeId:t.originNodeId}:{}}}r(flowContext,"flowContext"),o(flowContext,"flowContext");
1
+ "use strict";var d=Object.defineProperty;var s=(e,t)=>d(e,"name",{value:t,configurable:!0});var l=Object.defineProperty,r=s((e,t)=>l(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.FLOW_START=exports.CONTEXT_END=void 0,exports.countDbSecond=countDbSecond,exports.noteDbShape=noteDbShape,exports.hashDbValues=hashDbValues,exports.flowContextStatus=flowContextStatus,exports.resetFlowContextForTests=resetFlowContextForTests,exports.isRequireEsmError=isRequireEsmError,exports.isModuleNotFoundError=isModuleNotFoundError,exports.primeFlowContext=primeFlowContext,exports.attachContextEnd=attachContextEnd,exports.contextEndOf=contextEndOf,exports.startLiveFlow=startLiveFlow,exports.runInFlowContext=runInFlowContext,exports.liveFlowContext=liveFlowContext,exports.flowContext=flowContext;function countDbSecond(e,t){let n=e.dbSeconds;n||(e.dbSeconds=n=new Map);const o=Math.floor(t/1e3);n.set(o,(n.get(o)??0)+1),n.size>4096&&n.delete(n.keys().next().value)}s(countDbSecond,"countDbSecond"),r(countDbSecond,"countDbSecond");function noteDbShape(e,t,n){let o=e.dbShapes;o||(e.dbShapes=o={base:0,entries:[]}),o.entries.push(n===void 0?{s:t}:{s:t,v:n}),o.entries.length>1024&&(o.entries.splice(0,512),o.base+=512)}s(noteDbShape,"noteDbShape"),r(noteDbShape,"noteDbShape");function hashDbValues(e){let t=2166136261;if(e)for(const n of e){for(let o=0;o<n.length;o++)t=Math.imul(t^n.charCodeAt(o),16777619);t=Math.imul(t^31,16777619)}return t>>>0}s(hashDbValues,"hashDbValues"),r(hashDbValues,"hashDbValues");let getCtx=null,runWith=null,status={state:"not-primed"},warned=!1;function flowContextStatus(){return status}s(flowContextStatus,"flowContextStatus"),r(flowContextStatus,"flowContextStatus");function resetFlowContextForTests(){getCtx=null,runWith=null,status={state:"not-primed"},warned=!1}s(resetFlowContextForTests,"resetFlowContextForTests"),r(resetFlowContextForTests,"resetFlowContextForTests");function isRequireEsmError(e){const t=e?.code;return t==="ERR_REQUIRE_ESM"||t==="ERR_REQUIRE_ASYNC_MODULE"}s(isRequireEsmError,"isRequireEsmError"),r(isRequireEsmError,"isRequireEsmError");function isModuleNotFoundError(e){const t=e;return t?.code!=="MODULE_NOT_FOUND"&&t?.code!=="ERR_MODULE_NOT_FOUND"?!1:String(t?.message??"").includes("@lensmcp/nest-instrumentation")}s(isModuleNotFoundError,"isModuleNotFoundError"),r(isModuleNotFoundError,"isModuleNotFoundError");function requireNestInstrumentation(){return require("@lensmcp/nest-instrumentation")}s(requireNestInstrumentation,"requireNestInstrumentation"),r(requireNestInstrumentation,"requireNestInstrumentation");function primeFlowContext(e=requireNestInstrumentation){try{const t=e();getCtx=t.currentLensmcpContext,runWith=t.runInLensmcpContext,status={state:"ready"}}catch(t){if(getCtx=null,runWith=null,isModuleNotFoundError(t)){status={state:"absent"};return}const n=t instanceof Error?t.message:String(t);if(status=isRequireEsmError(t)?{state:"runtime-too-old",detail:n}:{state:"failed",detail:n},!warned){warned=!0;const o=status.state==="runtime-too-old"?`this Node (${process.version}) cannot require an ESM package; @lensmcp/node-instrumentation needs >=20.19`:n;console.warn(`[lensmcp] flow correlation is OFF \u2014 could not load @lensmcp/nest-instrumentation: ${o}`)}}}s(primeFlowContext,"primeFlowContext"),r(primeFlowContext,"primeFlowContext"),exports.CONTEXT_END=Symbol.for("lensmcp.contextEnd");function attachContextEnd(e){let t=!1;const n=[],o={get ended(){return t},onEnd(u){t?runEndListener(u):n.push(u)}};return Object.defineProperty(e,exports.CONTEXT_END,{value:o}),()=>{if(!t){t=!0;for(const u of n.splice(0))runEndListener(u)}}}s(attachContextEnd,"attachContextEnd"),r(attachContextEnd,"attachContextEnd");function runEndListener(e){try{e()}catch{}}s(runEndListener,"runEndListener"),r(runEndListener,"runEndListener");function contextEndOf(e){const t=e?.[exports.CONTEXT_END];return t&&typeof t.onEnd=="function"?t:void 0}s(contextEndOf,"contextEndOf"),r(contextEndOf,"contextEndOf"),exports.FLOW_START=Symbol.for("lensmcp.flowStart");function startLiveFlow(){const e=liveFlowContext();if(!e)return;if(e.flowId)return e.flowId;const t=e[exports.FLOW_START];if(typeof t=="function")try{return t()??e.flowId}catch{return e.flowId}}s(startLiveFlow,"startLiveFlow"),r(startLiveFlow,"startLiveFlow");function runInFlowContext(e,t){if(!runWith)return t();const n={sessionId:"pending",requestId:e.requestId,...e.flowId?{flowId:e.flowId}:{}},o=attachContextEnd(n);let u;try{u=runWith(n,t)}catch{return o(),t()}const i=u;return i&&typeof i.then=="function"?i.then(c=>(o(),c),c=>{throw o(),c}):(o(),u)}s(runInFlowContext,"runInFlowContext"),r(runInFlowContext,"runInFlowContext");function liveFlowContext(){try{return getCtx?.()}catch{return}}s(liveFlowContext,"liveFlowContext"),r(liveFlowContext,"liveFlowContext");function flowContext(){const e=liveFlowContext();if(e)return{...e.flowId?{flowId:e.flowId}:{},...e.requestId?{requestId:e.requestId}:{},...e.runId?{runId:e.runId}:{},...e.originNodeId?{originNodeId:e.originNodeId}:{}}}s(flowContext,"flowContext"),r(flowContext,"flowContext");
package/lib/http-store.js CHANGED
@@ -1 +1 @@
1
- "use strict";var x=Object.defineProperty;var c=(e,t)=>x(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,r=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.exchangeTime=exports.MAX_QUEUED=exports.PRUNE_EVERY_MS=exports.DEFAULT_HTTP_MAX_AGE_MS=exports.DEFAULT_HTTP_MAX_FILES=exports.newExchangeId=exports.MAX_AI_KEPT_BYTES=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.proofBoundHeaders=proofBoundHeaders,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,exports.pruneHttpExchanges=pruneHttpExchanges,exports.claimPrune=claimPrune,exports.primeHttpStore=primeHttpStore,exports.queueHttpExchange=queueHttpExchange,exports.flushHttpExchangesSync=flushHttpExchangesSync,exports.flushHttpExchanges=flushHttpExchanges,exports.httpExchangeStats=httpExchangeStats;const tslib_1=require("tslib"),node_async_hooks_1=require("node:async_hooks"),nodeFs=tslib_1.__importStar(require("node:fs")),node_crypto_1=require("node:crypto"),node_path_1=require("node:path"),http_exchange_1=require("@lensmcp/core/http-exchange"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,mkdirAsync=nodeFs.promises.mkdir,writeFileAsync=nodeFs.promises.writeFile,renameAsync=nodeFs.promises.rename,readdirAsync=nodeFs.promises.readdir,readFileAsync=nodeFs.promises.readFile,unlinkAsync=nodeFs.promises.unlink,statAsync=nodeFs.promises.stat;function httpCaptureMode(e=process.env){const t=(e.LENSMCP_HTTP_CAPTURE??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="none"?"off":t==="headers"?"headers":"bodies"}c(httpCaptureMode,"httpCaptureMode"),r(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024,exports.MAX_AI_KEPT_BYTES=4*1024*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=r(()=>`hx_${Date.now().toString(36)}${(0,node_crypto_1.randomBytes)(5).toString("hex")}`,"newExchangeId");exports.newExchangeId=newExchangeId;const CREDENTIAL_HEADERS=/^(authorization|proxy-authorization|dpop|cookie|set-cookie|x-api-key|api-key|openai-organization|openai-project|x-internal-token|x-amz-security-token)$|-api-key$|-token$|-secret$|-proof$/i,PROOF_HEADER=/^dpop$|-proof$/i;function proofBoundHeaders(e){try{if(!e||typeof e!="object")return!1;if(typeof e.forEach=="function"&&typeof e.get=="function"){let t=!1;return e.forEach((n,o)=>{PROOF_HEADER.test(o)&&(t=!0)}),t}if(Array.isArray(e)){if(e.every(t=>Array.isArray(t)))return e.some(([t,n])=>PROOF_HEADER.test(String(t))&&n!==void 0);for(let t=0;t<e.length;t+=2)if(PROOF_HEADER.test(String(e[t]))&&e[t+1]!==void 0)return!0;return!1}return Object.entries(e).some(([t,n])=>PROOF_HEADER.test(t)&&n!==void 0)}catch{return!0}}c(proofBoundHeaders,"proofBoundHeaders"),r(proofBoundHeaders,"proofBoundHeaders");const CREDENTIAL_FIELD=/pass(word|wd)?|secret|token|api[-_]?key|authorization|credential|cookie|signature/i;function jwtClaims(e){const t=e.split(".");if(t.length===3)try{const n=JSON.parse(Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return`JWT \xB7 ${["iss","aud","sub","exp"].filter(o=>n[o]!==void 0).map(o=>`${o}=${o==="exp"&&typeof n[o]=="number"?new Date(n[o]*1e3).toISOString():String(n[o]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}c(jwtClaims,"jwtClaims"),r(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],n=[];for(const[o,p]of e){const s=o.toLowerCase();if(CREDENTIAL_HEADERS.test(s)||(0,redact_1.isSecretParam)(s)){n.push(s);const i=/^bearer\s+(\S+)$/i.exec(p.trim()),f=i?jwtClaims(i[1]):void 0,u=/^(\w+)\s+\S/.exec(p.trim())?.[1];t.push([s,f?`Bearer ${f}`:u&&s.endsWith("authorization")?`${u} ${exports.REMOVED}`:exports.REMOVED])}else t.push([s,(0,ai_store_1.redactAiText)(p).slice(0,2048)])}return{headers:t,redacted:n}}c(redactHeaders,"redactHeaders"),r(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[n,o]of new URLSearchParams(e))t.push([n,(0,redact_1.isSecretParam)(n)||CREDENTIAL_FIELD.test(n)?exports.REMOVED:(0,ai_store_1.redactAiText)(o).slice(0,1024)])}catch{}return t.slice(0,100)}c(redactQuery,"redactQuery"),r(redactQuery,"redactQuery");function redactJson(e,t,n,o=0){if(o>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((s,i)=>redactJson(s,`${t}[${i}]`,n,o+1));const p={};for(const[s,i]of Object.entries(e)){const f=t?`${t}.${s}`:s,u=typeof i=="number"&&/tokens/i.test(s);CREDENTIAL_FIELD.test(s)&&i!==null&&typeof i!="object"&&!u?(p[s]=exports.REMOVED,n.length<50&&n.push(f)):p[s]=redactJson(i,f,n,o+1)}return p}c(redactJson,"redactJson"),r(redactJson,"redactJson");const textual=r(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,n,o,p,s=exports.MAX_KEPT_BYTES){const i=e.split(";")[0].trim().toLowerCase();if(!textual(i))return{contentType:i||"application/octet-stream",size:n,kept:0,truncated:!1,omitted:"binary",...p?{sha256:p}:{}};const f=t.byteLength>=n&&n<=Math.max(MAX_PARSE_BYTES,s),u=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let a;if(f&&/json/.test(i))try{a=JSON.stringify(redactJson(JSON.parse(u),"",o))}catch{a=(0,ai_store_1.redactAiText)(u)}else f&&/x-www-form-urlencoded/.test(i)?a=new URLSearchParams(redactQuery(u)).toString():a=(0,ai_store_1.redactAiText)(u);const l=Buffer.byteLength(a)>s?Buffer.from(a).subarray(0,s).toString("utf8"):a;return{contentType:i,size:n,kept:Buffer.byteLength(l),text:l,truncated:n>t.byteLength||l.length<a.length}}c(keepBody,"keepBody"),r(keepBody,"keepBody"),exports.DEFAULT_HTTP_MAX_FILES=1e4,exports.DEFAULT_HTTP_MAX_AGE_MS=1440*6e4,exports.PRUNE_EVERY_MS=3e4,exports.MAX_QUEUED=256;const MAX_QUEUED_BYTES=64*1024*1024,STALE_TMP_MS=10*6e4,CLAIM_PREFIX=".prune-",EXCHANGE_FILE=/^hx_[0-9a-z]+\.json$/,CLAIM_FILE=/^\.prune-([0-9a-z]+)$/,TMP_FILE=/^hx_[0-9a-z]+\.json\.(?:[0-9a-z.]+\.)?tmp$/,maxFiles=r(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:exports.DEFAULT_HTTP_MAX_FILES},"maxFiles"),maxAgeMs=r(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_AGE_MS);return Number.isFinite(e)&&e>=6e4?e:exports.DEFAULT_HTTP_MAX_AGE_MS},"maxAgeMs"),exchangeTime=r(e=>{const t=/^hx_([0-9a-z]{8})/.exec(e),n=t?parseInt(t[1],36):NaN;return Number.isFinite(n)?n:void 0},"exchangeTime");exports.exchangeTime=exchangeTime;const interval=r(e=>Math.floor(e/exports.PRUNE_EVERY_MS),"interval"),errno=r(e=>e?.code,"errno");async function pruneHttpExchanges(e,t=Date.now(),n=`${e}/ai`,o={}){let p=0,s;try{s=await readdirAsync(e)}catch{return 0}const i=(0,lens_time_1.lensTimed)(()=>s.filter(a=>EXCHANGE_FILE.test(a)).sort()),f=i.length-maxFiles(),u=t-maxAgeMs();for(let a=0;a<i.length;a+=1){const l=(0,exports.exchangeTime)(i[a]);if(a>=f&&(l===void 0||l>=u))break;const h=`${e}/${i[a]}`;try{if(!o.neverAi&&JSON.parse(await readFileAsync(h,"utf8"))?.ai){await mkdirAsync(n,{recursive:!0,mode:448}),await renameAsync(h,`${n}/${i[a]}`);continue}await unlinkAsync(h),p+=1}catch{}}for(const a of s){const l=CLAIM_FILE.exec(a);if(l?parseInt(l[1],36)<interval(t):TMP_FILE.test(a))try{if(!l&&t-(await statAsync((0,node_path_1.join)(e,a))).mtimeMs<STALE_TMP_MS)continue;await unlinkAsync((0,node_path_1.join)(e,a))}catch{}}return p}c(pruneHttpExchanges,"pruneHttpExchanges"),r(pruneHttpExchanges,"pruneHttpExchanges");async function claimPrune(e,t=Date.now()){try{return await writeFileAsync((0,node_path_1.join)(e,`${CLAIM_PREFIX}${interval(t).toString(36)}`),String(process.pid),{flag:"wx",mode:384}),!0}catch{return!1}}c(claimPrune,"claimPrune"),r(claimPrune,"claimPrune");let queue=[],queuedBytes=0,writing=[],armed=!1,draining;const dirty=new Set;let lastPruneAt=0,pruneTimer,pruning;const stats={written:0,failed:0,dropped:0,prunes:0};let root;const scope=r(()=>root??=new node_async_hooks_1.AsyncResource("lensmcp.http-store"),"scope");function primeHttpStore(){scope(),registerExitFlush()}c(primeHttpStore,"primeHttpStore"),r(primeHttpStore,"primeHttpStore");const approxBytes=r(e=>2048+(e.request.body?.kept??0)+(e.response.body?.kept??0)+(e.response.stream?.bytes??0),"approxBytes");function queueHttpExchange(e){try{const t=(0,http_exchange_1.exchangePlace)(e),n=(0,http_exchange_1.httpExchangeFile)(emit_1.EVENT_FILE,e.id,t),o=approxBytes(e);for(queue.push({x:e,place:t,file:n,bytes:o,state:"queued"}),queuedBytes+=o;queue.length>exports.MAX_QUEUED||queuedBytes>MAX_QUEUED_BYTES&&queue.length>1;){const p=queue.findIndex(i=>i.place!=="ai"),[s]=queue.splice(p<0?0:p,1);queuedBytes-=s.bytes,s.state="done",stats.dropped+=1}return registerExitFlush(),armFlush(),!0}catch{return!1}}c(queueHttpExchange,"queueHttpExchange"),r(queueHttpExchange,"queueHttpExchange");function armFlush(){armed||draining||(armed=!0,scope().runInAsyncScope(()=>setImmediate(startDrain).unref()))}c(armFlush,"armFlush"),r(armFlush,"armFlush");function startDrain(){armed=!1,!(draining||!queue.length)&&(draining=(async()=>{for(;queue.length;){const e=queue;queue=[],queuedBytes=0,writing=e;for(const t of e)t.state==="queued"&&await writeOne(t);writing=[]}})().catch(()=>{}).finally(()=>{draining=void 0,queue.length&&armFlush()}))}c(startDrain,"startDrain"),r(startDrain,"startDrain");async function writeOne(e){e.state="writing";const t=`${e.file}.tmp`;try{const n=(0,lens_time_1.lensTimed)(()=>JSON.stringify(e.x));try{await writeFileAsync(t,n,{mode:384})}catch(o){if(errno(o)!=="ENOENT")throw o;await mkdirAsync((0,node_path_1.dirname)(e.file),{recursive:!0,mode:448}),await writeFileAsync(t,n,{mode:384})}await renameAsync(t,e.file),e.state="done",stats.written+=1,e.place!=="ai"&&(dirty.add(e.place),armPrune())}catch{e.state="done",stats.failed+=1}}c(writeOne,"writeOne"),r(writeOne,"writeOne");function armPrune(){if(pruneTimer||pruning)return;const e=Math.max(0,lastPruneAt+exports.PRUNE_EVERY_MS-Date.now());pruneTimer=scope().runInAsyncScope(()=>setTimeout(runPrune,e)),pruneTimer.unref?.()}c(armPrune,"armPrune"),r(armPrune,"armPrune");function runPrune(){if(pruneTimer=void 0,pruning)return;const e=Date.now();lastPruneAt=e;const t=[...dirty];dirty.clear(),pruning=(async()=>{for(const n of t){const o=(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE,n);await claimPrune(o,e)&&(stats.prunes+=1,await pruneHttpExchanges(o,e,(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE,"ai"),{neverAi:n==="in"}))}})().catch(()=>{}).finally(()=>{pruning=void 0,dirty.size&&armPrune()})}c(runPrune,"runPrune"),r(runPrune,"runPrune");function flushHttpExchangesSync(){let e=0;for(const t of[...writing,...queue]){if(t.state==="done")continue;t.state="done";const n=`${t.file}.${process.pid.toString(36)}.exit.tmp`;try{const o=JSON.stringify(t.x);try{writeFileSync(n,o,{mode:384})}catch(p){if(errno(p)!=="ENOENT")throw p;mkdirSync((0,node_path_1.dirname)(t.file),{recursive:!0,mode:448}),writeFileSync(n,o,{mode:384})}renameSync(n,t.file),stats.written+=1,e+=1}catch{stats.failed+=1}}return queue=[],queuedBytes=0,e}c(flushHttpExchangesSync,"flushHttpExchangesSync"),r(flushHttpExchangesSync,"flushHttpExchangesSync");const EXIT_HOOK=Symbol.for("lensmcp.httpStore.exitFlush");let exitRegistered=!1;function registerExitFlush(){if(exitRegistered)return;exitRegistered=!0;const e=globalThis;let t=e[EXIT_HOOK];if(!t){const n=new Set;t=Object.assign(()=>{for(const o of n)try{o()}catch{}},{flushers:n}),e[EXIT_HOOK]=t,process.once("exit",t),process.on("beforeExit",t)}t.flushers.add(flushHttpExchangesSync)}c(registerExitFlush,"registerExitFlush"),r(registerExitFlush,"registerExitFlush");async function flushHttpExchanges(){for(let e=0;e<100&&(queue.length||draining||pruning);e+=1)queue.length&&!draining&&scope().runInAsyncScope(startDrain),await draining,await pruning}c(flushHttpExchanges,"flushHttpExchanges"),r(flushHttpExchanges,"flushHttpExchanges");function httpExchangeStats(){return{waiting:queue.length,...stats}}c(httpExchangeStats,"httpExchangeStats"),r(httpExchangeStats,"httpExchangeStats");
1
+ "use strict";var x=Object.defineProperty;var c=(e,t)=>x(e,"name",{value:t,configurable:!0});var d=Object.defineProperty,r=c((e,t)=>d(e,"name",{value:t,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.exchangeTime=exports.MAX_QUEUED=exports.PRUNE_EVERY_MS=exports.DEFAULT_HTTP_MAX_AGE_MS=exports.DEFAULT_HTTP_MAX_FILES=exports.newExchangeId=exports.MAX_AI_KEPT_BYTES=exports.MAX_KEPT_BYTES=exports.REMOVED=void 0,exports.httpCaptureMode=httpCaptureMode,exports.proofBoundHeaders=proofBoundHeaders,exports.redactHeaders=redactHeaders,exports.redactQuery=redactQuery,exports.keepBody=keepBody,exports.pruneHttpExchanges=pruneHttpExchanges,exports.claimPrune=claimPrune,exports.primeHttpStore=primeHttpStore,exports.queueHttpExchange=queueHttpExchange,exports.flushHttpExchangesSync=flushHttpExchangesSync,exports.flushHttpExchanges=flushHttpExchanges,exports.httpExchangeStats=httpExchangeStats;const tslib_1=require("tslib"),node_async_hooks_1=require("node:async_hooks"),nodeFs=tslib_1.__importStar(require("node:fs")),node_crypto_1=require("node:crypto"),node_path_1=require("node:path"),http_exchange_1=require("@lensmcp/core/http-exchange"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),mkdirSync=nodeFs.mkdirSync,writeFileSync=nodeFs.writeFileSync,renameSync=nodeFs.renameSync,mkdirAsync=nodeFs.promises.mkdir,writeFileAsync=nodeFs.promises.writeFile,renameAsync=nodeFs.promises.rename,readdirAsync=nodeFs.promises.readdir,readFileAsync=nodeFs.promises.readFile,unlinkAsync=nodeFs.promises.unlink,statAsync=nodeFs.promises.stat;function httpCaptureMode(e=process.env){const t=(e.LENSMCP_HTTP_CAPTURE??"").trim().toLowerCase();return t==="off"||t==="0"||t==="false"||t==="none"?"off":t==="headers"?"headers":"bodies"}c(httpCaptureMode,"httpCaptureMode"),r(httpCaptureMode,"httpCaptureMode"),exports.REMOVED="\u2022\u2022\u2022\u2022 redacted",exports.MAX_KEPT_BYTES=64*1024,exports.MAX_AI_KEPT_BYTES=4*1024*1024;const MAX_PARSE_BYTES=2*1024*1024,newExchangeId=r(()=>`hx_${Date.now().toString(36)}${(0,node_crypto_1.randomBytes)(5).toString("hex")}`,"newExchangeId");exports.newExchangeId=newExchangeId;const CREDENTIAL_HEADERS=/^(authorization|proxy-authorization|dpop|cookie|set-cookie|x-api-key|api-key|openai-organization|openai-project|x-internal-token|x-amz-security-token)$|-api-key$|-token$|-secret$|-proof$/i,PROOF_HEADER=/^dpop$|-proof$/i;function proofBoundHeaders(e){try{if(!e||typeof e!="object")return!1;if(typeof e.forEach=="function"&&typeof e.get=="function"){let t=!1;return e.forEach((n,o)=>{PROOF_HEADER.test(o)&&(t=!0)}),t}if(Array.isArray(e)){if(e.every(t=>Array.isArray(t)))return e.some(([t,n])=>PROOF_HEADER.test(String(t))&&n!==void 0);for(let t=0;t<e.length;t+=2)if(PROOF_HEADER.test(String(e[t]))&&e[t+1]!==void 0)return!0;return!1}return Object.entries(e).some(([t,n])=>PROOF_HEADER.test(t)&&n!==void 0)}catch{return!0}}c(proofBoundHeaders,"proofBoundHeaders"),r(proofBoundHeaders,"proofBoundHeaders");const CREDENTIAL_FIELD=/pass(word|wd)?|secret|token|api[-_]?key|authorization|credential|cookie|signature/i;function jwtClaims(e){const t=e.split(".");if(t.length===3)try{const n=JSON.parse(Buffer.from(t[1].replace(/-/g,"+").replace(/_/g,"/"),"base64").toString("utf8"));return`JWT \xB7 ${["iss","aud","sub","exp"].filter(o=>n[o]!==void 0).map(o=>`${o}=${o==="exp"&&typeof n[o]=="number"?new Date(n[o]*1e3).toISOString():String(n[o]).slice(0,80)}`).join(" \xB7 ")||"no claims"} \xB7 ${exports.REMOVED.split(" ")[0]} signature`}catch{return}}c(jwtClaims,"jwtClaims"),r(jwtClaims,"jwtClaims");function redactHeaders(e){const t=[],n=[];for(const[o,p]of e){const s=o.toLowerCase();if(CREDENTIAL_HEADERS.test(s)||(0,redact_1.isSecretParam)(s)){n.push(s);const i=/^bearer\s+(\S+)$/i.exec(p.trim()),f=i?jwtClaims(i[1]):void 0,u=/^(\w+)\s+\S/.exec(p.trim())?.[1];t.push([s,f?`Bearer ${f}`:u&&s.endsWith("authorization")?`${u} ${exports.REMOVED}`:exports.REMOVED])}else t.push([s,(0,ai_store_1.redactAiText)(p).slice(0,2048)])}return{headers:t,redacted:n}}c(redactHeaders,"redactHeaders"),r(redactHeaders,"redactHeaders");function redactQuery(e){const t=[];try{for(const[n,o]of new URLSearchParams(e))t.push([n,(0,redact_1.isSecretParam)(n)||CREDENTIAL_FIELD.test(n)?exports.REMOVED:(0,ai_store_1.redactAiText)(o).slice(0,1024)])}catch{}return t.slice(0,100)}c(redactQuery,"redactQuery"),r(redactQuery,"redactQuery");function redactJson(e,t,n,o=0){if(o>32||e===null||typeof e!="object")return typeof e=="string"?(0,ai_store_1.redactAiText)(e):e;if(Array.isArray(e))return e.map((s,i)=>redactJson(s,`${t}[${i}]`,n,o+1));const p={};for(const[s,i]of Object.entries(e)){const f=t?`${t}.${s}`:s,u=typeof i=="number"&&/tokens/i.test(s);CREDENTIAL_FIELD.test(s)&&i!==null&&typeof i!="object"&&!u?(p[s]=exports.REMOVED,n.length<50&&n.push(f)):p[s]=redactJson(i,f,n,o+1)}return p}c(redactJson,"redactJson"),r(redactJson,"redactJson");const textual=r(e=>/json|^text\/|x-www-form-urlencoded|xml|javascript|graphql|event-stream/i.test(e)||e==="","textual");function keepBody(e,t,n,o,p,s=exports.MAX_KEPT_BYTES){const i=e.split(";")[0].trim().toLowerCase();if(!textual(i))return{contentType:i||"application/octet-stream",size:n,kept:0,truncated:!1,omitted:"binary",...p?{sha256:p}:{}};const f=t.byteLength>=n&&n<=Math.max(MAX_PARSE_BYTES,s),u=Buffer.from(t.buffer,t.byteOffset,t.byteLength).toString("utf8");let a;if(f&&/json/.test(i))try{a=JSON.stringify(redactJson(JSON.parse(u),"",o))}catch{a=(0,ai_store_1.redactAiText)(u)}else f&&/x-www-form-urlencoded/.test(i)?a=new URLSearchParams(redactQuery(u)).toString():a=(0,ai_store_1.redactAiText)(u);const l=Buffer.byteLength(a)>s?Buffer.from(a).subarray(0,s).toString("utf8"):a;return{contentType:i,size:n,kept:Buffer.byteLength(l),text:l,truncated:n>t.byteLength||l.length<a.length}}c(keepBody,"keepBody"),r(keepBody,"keepBody"),exports.DEFAULT_HTTP_MAX_FILES=1e4,exports.DEFAULT_HTTP_MAX_AGE_MS=1440*6e4,exports.PRUNE_EVERY_MS=3e4,exports.MAX_QUEUED=256;const MAX_QUEUED_BYTES=64*1024*1024,STALE_TMP_MS=10*6e4,CLAIM_PREFIX=".prune-",EXCHANGE_FILE=/^hx_[0-9a-z]+\.json$/,CLAIM_FILE=/^\.prune-([0-9a-z]+)$/,TMP_FILE=/^hx_[0-9a-z]+\.json\.(?:[0-9a-z.]+\.)?tmp$/,maxFiles=r(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_FILES);return Number.isInteger(e)&&e>=10?e:exports.DEFAULT_HTTP_MAX_FILES},"maxFiles"),maxAgeMs=r(()=>{const e=Number(process.env.LENSMCP_HTTP_MAX_AGE_MS);return Number.isFinite(e)&&e>=6e4?e:exports.DEFAULT_HTTP_MAX_AGE_MS},"maxAgeMs"),exchangeTime=r(e=>{const t=/^hx_([0-9a-z]{8})/.exec(e),n=t?parseInt(t[1],36):NaN;return Number.isFinite(n)?n:void 0},"exchangeTime");exports.exchangeTime=exchangeTime;const interval=r(e=>Math.floor(e/exports.PRUNE_EVERY_MS),"interval"),errno=r(e=>e?.code,"errno");async function pruneHttpExchanges(e,t=Date.now(),n=`${e}/ai`,o={}){let p=0,s;try{s=await readdirAsync(e)}catch{return 0}const i=(0,lens_time_1.lensTimed)(()=>s.filter(a=>EXCHANGE_FILE.test(a)).sort(),"cleanup"),f=i.length-maxFiles(),u=t-maxAgeMs();for(let a=0;a<i.length;a+=1){const l=(0,exports.exchangeTime)(i[a]);if(a>=f&&(l===void 0||l>=u))break;const h=`${e}/${i[a]}`;try{if(!o.neverAi&&JSON.parse(await readFileAsync(h,"utf8"))?.ai){await mkdirAsync(n,{recursive:!0,mode:448}),await renameAsync(h,`${n}/${i[a]}`);continue}await unlinkAsync(h),p+=1}catch{}}for(const a of s){const l=CLAIM_FILE.exec(a);if(l?parseInt(l[1],36)<interval(t):TMP_FILE.test(a))try{if(!l&&t-(await statAsync((0,node_path_1.join)(e,a))).mtimeMs<STALE_TMP_MS)continue;await unlinkAsync((0,node_path_1.join)(e,a))}catch{}}return p}c(pruneHttpExchanges,"pruneHttpExchanges"),r(pruneHttpExchanges,"pruneHttpExchanges");async function claimPrune(e,t=Date.now()){try{return await writeFileAsync((0,node_path_1.join)(e,`${CLAIM_PREFIX}${interval(t).toString(36)}`),String(process.pid),{flag:"wx",mode:384}),!0}catch{return!1}}c(claimPrune,"claimPrune"),r(claimPrune,"claimPrune");let queue=[],queuedBytes=0,writing=[],armed=!1,draining;const dirty=new Set;let lastPruneAt=0,pruneTimer,pruning;const stats={written:0,failed:0,dropped:0,prunes:0};let root;const scope=r(()=>root??=new node_async_hooks_1.AsyncResource("lensmcp.http-store"),"scope");function primeHttpStore(){scope(),registerExitFlush()}c(primeHttpStore,"primeHttpStore"),r(primeHttpStore,"primeHttpStore");const approxBytes=r(e=>2048+(e.request.body?.kept??0)+(e.response.body?.kept??0)+(e.response.stream?.bytes??0),"approxBytes");function queueHttpExchange(e){try{const t=(0,http_exchange_1.exchangePlace)(e),n=(0,http_exchange_1.httpExchangeFile)(emit_1.EVENT_FILE,e.id,t),o=approxBytes(e);for(queue.push({x:e,place:t,file:n,bytes:o,state:"queued"}),queuedBytes+=o;queue.length>exports.MAX_QUEUED||queuedBytes>MAX_QUEUED_BYTES&&queue.length>1;){const p=queue.findIndex(i=>i.place!=="ai"),[s]=queue.splice(p<0?0:p,1);queuedBytes-=s.bytes,s.state="done",stats.dropped+=1}return registerExitFlush(),armFlush(),!0}catch{return!1}}c(queueHttpExchange,"queueHttpExchange"),r(queueHttpExchange,"queueHttpExchange");function armFlush(){armed||draining||(armed=!0,scope().runInAsyncScope(()=>setImmediate(startDrain).unref()))}c(armFlush,"armFlush"),r(armFlush,"armFlush");function startDrain(){armed=!1,!(draining||!queue.length)&&(draining=(async()=>{for(;queue.length;){const e=queue;queue=[],queuedBytes=0,writing=e;for(const t of e)t.state==="queued"&&await writeOne(t);writing=[]}})().catch(()=>{}).finally(()=>{draining=void 0,queue.length&&armFlush()}))}c(startDrain,"startDrain"),r(startDrain,"startDrain");async function writeOne(e){e.state="writing";const t=`${e.file}.tmp`;try{const n=(0,lens_time_1.lensTimed)(()=>JSON.stringify(e.x),"capture");try{await writeFileAsync(t,n,{mode:384})}catch(o){if(errno(o)!=="ENOENT")throw o;await mkdirAsync((0,node_path_1.dirname)(e.file),{recursive:!0,mode:448}),await writeFileAsync(t,n,{mode:384})}await renameAsync(t,e.file),e.state="done",stats.written+=1,e.place!=="ai"&&(dirty.add(e.place),armPrune())}catch{e.state="done",stats.failed+=1}}c(writeOne,"writeOne"),r(writeOne,"writeOne");function armPrune(){if(pruneTimer||pruning)return;const e=Math.max(0,lastPruneAt+exports.PRUNE_EVERY_MS-Date.now());pruneTimer=scope().runInAsyncScope(()=>setTimeout(runPrune,e)),pruneTimer.unref?.()}c(armPrune,"armPrune"),r(armPrune,"armPrune");function runPrune(){if(pruneTimer=void 0,pruning)return;const e=Date.now();lastPruneAt=e;const t=[...dirty];dirty.clear(),pruning=(async()=>{for(const n of t){const o=(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE,n);await claimPrune(o,e)&&(stats.prunes+=1,await pruneHttpExchanges(o,e,(0,http_exchange_1.httpExchangeDir)(emit_1.EVENT_FILE,"ai"),{neverAi:n==="in"}))}})().catch(()=>{}).finally(()=>{pruning=void 0,dirty.size&&armPrune()})}c(runPrune,"runPrune"),r(runPrune,"runPrune");function flushHttpExchangesSync(){let e=0;for(const t of[...writing,...queue]){if(t.state==="done")continue;t.state="done";const n=`${t.file}.${process.pid.toString(36)}.exit.tmp`;try{const o=JSON.stringify(t.x);try{writeFileSync(n,o,{mode:384})}catch(p){if(errno(p)!=="ENOENT")throw p;mkdirSync((0,node_path_1.dirname)(t.file),{recursive:!0,mode:448}),writeFileSync(n,o,{mode:384})}renameSync(n,t.file),stats.written+=1,e+=1}catch{stats.failed+=1}}return queue=[],queuedBytes=0,e}c(flushHttpExchangesSync,"flushHttpExchangesSync"),r(flushHttpExchangesSync,"flushHttpExchangesSync");const EXIT_HOOK=Symbol.for("lensmcp.httpStore.exitFlush");let exitRegistered=!1;function registerExitFlush(){if(exitRegistered)return;exitRegistered=!0;const e=globalThis;let t=e[EXIT_HOOK];if(!t){const n=new Set;t=Object.assign(()=>{for(const o of n)try{o()}catch{}},{flushers:n}),e[EXIT_HOOK]=t,process.once("exit",t),process.on("beforeExit",t)}t.flushers.add(flushHttpExchangesSync)}c(registerExitFlush,"registerExitFlush"),r(registerExitFlush,"registerExitFlush");async function flushHttpExchanges(){for(let e=0;e<100&&(queue.length||draining||pruning);e+=1)queue.length&&!draining&&scope().runInAsyncScope(startDrain),await draining,await pruning}c(flushHttpExchanges,"flushHttpExchanges"),r(flushHttpExchanges,"flushHttpExchanges");function httpExchangeStats(){return{waiting:queue.length,...stats}}c(httpExchangeStats,"httpExchangeStats"),r(httpExchangeStats,"httpExchangeStats");
package/lib/install.d.ts CHANGED
@@ -1 +1,12 @@
1
+ /**
2
+ * Node's module-hooks thread (`module.register`): a `--require` preload runs again there, on Node without
3
+ * `registerHooks` (`lensmcp run` passes `--require register --import loader`). It is no thread of the app's — Node's
4
+ * own `isInternalThread` says so where it exists; else it is the one worker with no `parentPort`, which an app's
5
+ * `Worker` always has.
6
+ */
7
+ export declare function inModuleHooksThread(wt?: {
8
+ isMainThread: boolean;
9
+ parentPort: unknown;
10
+ isInternalThread?: boolean;
11
+ }): boolean;
1
12
  export declare function installLensmcpNodeInstrumentation(): void;
package/lib/install.js CHANGED
@@ -1 +1 @@
1
- "use strict";var p=Object.defineProperty;var a=(t,r)=>p(t,"name",{value:r,configurable:!0});var s=Object.defineProperty,e=a((t,r)=>s(t,"name",{value:r,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installLensmcpNodeInstrumentation=installLensmcpNodeInstrumentation;const require_hook_1=require("./require-hook"),flow_context_1=require("./flow-context"),emit_custom_1=require("./emit-custom"),tap_egress_1=require("./tap-egress"),tap_ai_1=require("./tap-ai"),tap_fs_1=require("./tap-fs"),tap_exec_1=require("./tap-exec"),tap_pg_1=require("./tap-pg"),tap_redis_1=require("./tap-redis"),active_work_1=require("./active-work"),tap_bullmq_1=require("./tap-bullmq"),tap_nest_1=require("./tap-nest"),tap_nest_logger_1=require("./tap-nest-logger"),tap_event_loop_1=require("./tap-event-loop"),tap_ingress_1=require("./tap-ingress"),tap_stdout_1=require("./tap-stdout");function installLensmcpNodeInstrumentation(){const t=globalThis;if(!t.__lensmcpNodeInstrumented&&(t.__lensmcpNodeInstrumented=!0,process.env.LENSMCP_AUTO!=="0")){try{(0,active_work_1.installActiveWorkProbe)()}catch{}try{(0,flow_context_1.primeFlowContext)()}catch{}try{(0,emit_custom_1.installCustomEmit)()}catch{}try{(0,tap_egress_1.tapEgress)()}catch{}try{(0,tap_ingress_1.tapIngress)()}catch{}try{(0,tap_ai_1.tapAi)()}catch{}try{(0,tap_fs_1.tapFs)()}catch{}try{(0,tap_exec_1.tapExec)()}catch{}try{(0,tap_stdout_1.tapStdout)()}catch{}try{(0,tap_event_loop_1.tapEventLoop)()}catch{}try{(0,require_hook_1.installRequireHook)({pg:tap_pg_1.pgTap,ioredis:tap_redis_1.redisTap,bullmq:tap_bullmq_1.bullmqTap,"@nestjs/core":tap_nest_1.nestTap,"@nestjs/common":tap_nest_logger_1.nestLoggerTap})}catch{}try{(0,tap_nest_1.installChildAppBridge)()}catch{}}}a(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation"),e(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation");
1
+ "use strict";var i=Object.defineProperty;var r=(t,a)=>i(t,"name",{value:a,configurable:!0});var s=Object.defineProperty,e=r((t,a)=>s(t,"name",{value:a,configurable:!0}),"e");Object.defineProperty(exports,"__esModule",{value:!0}),exports.inModuleHooksThread=inModuleHooksThread,exports.installLensmcpNodeInstrumentation=installLensmcpNodeInstrumentation;const require_hook_1=require("./require-hook"),lens_peers_1=require("./lens-peers"),flow_context_1=require("./flow-context"),emit_custom_1=require("./emit-custom"),tap_egress_1=require("./tap-egress"),tap_ai_1=require("./tap-ai"),tap_fs_1=require("./tap-fs"),tap_exec_1=require("./tap-exec"),tap_pg_1=require("./tap-pg"),tap_redis_1=require("./tap-redis"),active_work_1=require("./active-work"),tap_bullmq_1=require("./tap-bullmq"),tap_mysql_1=require("./tap-mysql"),tap_kafka_1=require("./tap-kafka"),tap_nest_1=require("./tap-nest"),tap_nest_logger_1=require("./tap-nest-logger"),tap_event_loop_1=require("./tap-event-loop"),tap_ingress_1=require("./tap-ingress"),tap_stdout_1=require("./tap-stdout");function inModuleHooksThread(t=require("node:worker_threads")){return t.isInternalThread===!0?!0:!t.isMainThread&&t.parentPort===null}r(inModuleHooksThread,"inModuleHooksThread"),e(inModuleHooksThread,"inModuleHooksThread");function installLensmcpNodeInstrumentation(){const t=globalThis;if(!t.__lensmcpNodeInstrumented&&(t.__lensmcpNodeInstrumented=!0,process.env.LENSMCP_AUTO!=="0")){try{if(inModuleHooksThread())return}catch{}try{(0,lens_peers_1.installPeerRedirect)()}catch{}try{(0,active_work_1.installActiveWorkProbe)()}catch{}try{(0,flow_context_1.primeFlowContext)()}catch{}try{(0,emit_custom_1.installCustomEmit)()}catch{}try{(0,tap_egress_1.tapEgress)()}catch{}try{(0,tap_ingress_1.tapIngress)()}catch{}try{(0,tap_ai_1.tapAi)()}catch{}try{(0,tap_fs_1.tapFs)()}catch{}try{(0,tap_exec_1.tapExec)()}catch{}try{(0,tap_stdout_1.tapStdout)()}catch{}try{(0,tap_event_loop_1.tapEventLoop)()}catch{}try{(0,require_hook_1.installRequireHook)({pg:tap_pg_1.pgTap,ioredis:tap_redis_1.redisTap,bullmq:tap_bullmq_1.bullmqTap,mysql2:tap_mysql_1.mysqlTap,"mysql2/promise":tap_mysql_1.mysqlPromiseTap,kafkajs:tap_kafka_1.kafkaTap,"@nestjs/core":tap_nest_1.nestTap,"@nestjs/common":tap_nest_logger_1.nestLoggerTap})}catch{}try{(0,tap_nest_1.installChildAppBridge)()}catch{}try{require("node:module").syncBuiltinESMExports()}catch{}}}r(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation"),e(installLensmcpNodeInstrumentation,"installLensmcpNodeInstrumentation");
@@ -0,0 +1,30 @@
1
+ export declare const LENS_PEER: RegExp;
2
+ /** The `node_modules` folder that holds this `@lensmcp/*` package, or undefined when it is not installed as one. */
3
+ export declare function lensInstallOf(dir?: string): string | undefined;
4
+ export declare function appRootOf(env?: NodeJS.ProcessEnv): string;
5
+ /** The install is not the app's own: the folder that owns it is not the app's root nor above it. */
6
+ export declare function foreignInstall(install: string, appRoot: string): boolean;
7
+ type ResolveContext = {
8
+ conditions: string[];
9
+ parentURL: string | undefined;
10
+ };
11
+ type Resolved = {
12
+ url: string;
13
+ };
14
+ type Next<R> = (specifier: string, context?: Partial<ResolveContext>) => R;
15
+ type PeerHook = <R extends Resolved | Promise<Resolved>>(specifier: string, context: ResolveContext, next: Next<R>) => R;
16
+ /** What the ESM resolve hook needs: where the lens is installed, and the app it runs for. */
17
+ export interface PeerHookData {
18
+ roots: string[];
19
+ appURL: string;
20
+ }
21
+ /** The ESM form: a lens file's `import` of a peer resolves from the app; `next` sync (in-thread) or async (off-thread). */
22
+ export declare function peerResolveHook(data: PeerHookData): PeerHook;
23
+ /** Off-thread hooks (`module.register`, Node without `registerHooks`). */
24
+ export declare function initialize(data: PeerHookData): void;
25
+ export declare function resolve(specifier: string, context: ResolveContext, next: Next<Promise<Resolved>>): Promise<Resolved>;
26
+ /** Resolve the lens's peers from the app when this instrumentation runs from an install that is not the app's. */
27
+ export declare function installPeerRedirect(env?: NodeJS.ProcessEnv, install?: string | undefined): boolean;
28
+ /** Without `registerHooks` the ESM half runs off-thread: from the loader only, as a `--require` preload reruns in that thread. */
29
+ export declare function installPeerRedirectOffThread(): boolean;
30
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";var h=Object.defineProperty;var s=(r,e)=>h(r,"name",{value:e,configurable:!0});var m=Object.defineProperty,n=s((r,e)=>m(r,"name",{value:e,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_PEER=void 0,exports.lensInstallOf=lensInstallOf,exports.appRootOf=appRootOf,exports.foreignInstall=foreignInstall,exports.peerResolveHook=peerResolveHook,exports.initialize=initialize,exports.resolve=resolve,exports.installPeerRedirect=installPeerRedirect,exports.installPeerRedirectOffThread=installPeerRedirectOffThread;const tslib_1=require("tslib"),fs=tslib_1.__importStar(require("node:fs")),path=tslib_1.__importStar(require("node:path")),node_url_1=require("node:url");exports.LENS_PEER=/^(?:@nestjs\/[^/]+|reflect-metadata|rxjs)(?:\/|$)/;function lensInstallOf(r=__dirname){for(let e=r;path.dirname(e)!==e;e=path.dirname(e)){const t=path.dirname(e);if(path.basename(t)==="@lensmcp"&&path.basename(path.dirname(t))==="node_modules")return path.dirname(t)}}s(lensInstallOf,"lensInstallOf"),n(lensInstallOf,"lensInstallOf");function appRootOf(r=process.env){return path.resolve(r.LENSMCP_APP_ROOT||process.cwd())}s(appRootOf,"appRootOf"),n(appRootOf,"appRootOf");const realOr=n(r=>{try{return fs.realpathSync(r)}catch{return r}},"realOr");function foreignInstall(r,e){const t=realOr(path.dirname(r)),o=realOr(e);return o!==t&&!o.startsWith(t+path.sep)}s(foreignInstall,"foreignInstall"),n(foreignInstall,"foreignInstall");function peerResolveHook(r){return(e,t,o)=>{const i=t.parentURL?.startsWith("file:")?(0,node_url_1.fileURLToPath)(t.parentURL):void 0;if(!exports.LENS_PEER.test(e)||!i||!r.roots.some(a=>i.startsWith(a)))return o(e,t);const c=n(()=>o(e,t),"fallback");try{const a=o(e,{...t,parentURL:r.appURL});return a instanceof Promise?a.catch(c):a}catch{return c()}}}s(peerResolveHook,"peerResolveHook"),n(peerResolveHook,"peerResolveHook");let offThread;function initialize(r){offThread=peerResolveHook(r)}s(initialize,"initialize"),n(initialize,"initialize");async function resolve(r,e,t){return offThread?offThread(r,e,t):t(r,e)}s(resolve,"resolve"),n(resolve,"resolve");const INSTALLED=Symbol.for("lensmcp.peerRedirect"),OFF_THREAD=Symbol.for("lensmcp.peerRedirect.offThread");function installPeerRedirect(r=process.env,e=lensInstallOf()){const t=globalThis;if(t[INSTALLED]||!e)return!1;const o=appRootOf(r);if(!foreignInstall(e,o))return!1;t[INSTALLED]=!0;const i=require("node:module"),c=[...new Set([e,realOr(e)])].map(l=>l+path.sep),a=n(l=>!!l&&c.some(f=>l.startsWith(f)),"fromLens"),R={id:path.join(o,"index.js"),filename:path.join(o,"index.js"),paths:i._nodeModulePaths(o)},p=i._resolveFilename;i._resolveFilename=function(l,f,...u){if(exports.LENS_PEER.test(l)&&a(f?.filename))try{return p.call(this,l,R,...u)}catch{}return p.call(this,l,f,...u)};const d={roots:c,appURL:(0,node_url_1.pathToFileURL)(path.join(o,"package.json")).href};return typeof i.registerHooks=="function"?i.registerHooks({resolve:peerResolveHook(d)}):t[OFF_THREAD]=d,!0}s(installPeerRedirect,"installPeerRedirect"),n(installPeerRedirect,"installPeerRedirect");function installPeerRedirectOffThread(){const r=globalThis,e=r[OFF_THREAD],t=require("node:module");return!e||typeof t.register!="function"?!1:(delete r[OFF_THREAD],t.register((0,node_url_1.pathToFileURL)(__filename).href,{data:e}),!0)}s(installPeerRedirectOffThread,"installPeerRedirectOffThread"),n(installPeerRedirectOffThread,"installPeerRedirectOffThread");
@@ -1,9 +1,13 @@
1
1
  export declare const LENS_SELF_MS: unique symbol;
2
+ /** The same total by what the lens was doing; `@lensmcp/nest-instrumentation`'s event sink adds to both (event-sink.ts). */
3
+ export declare const LENS_SELF_BY: unique symbol;
4
+ export type LensWork = 'write' | 'cleanup' | 'capture';
2
5
  /** The lens's own time so far in this process, ms. */
3
6
  export declare function lensSelfMs(): number;
7
+ export declare function lensSelfBy(): Partial<Record<LensWork, number>>;
4
8
  /** A lens section begins: returns its start, for {@link lensLeave}. */
5
9
  export declare function lensEnter(): number;
6
10
  /** …and ends. */
7
- export declare function lensLeave(startedAt: number): void;
11
+ export declare function lensLeave(startedAt: number, work?: LensWork): void;
8
12
  /** Run `fn` as a lens section. */
9
- export declare function lensTimed<T>(fn: () => T): T;
13
+ export declare function lensTimed<T>(fn: () => T, work?: LensWork): T;
package/lib/lens-time.js CHANGED
@@ -1 +1 @@
1
- "use strict";var t=Object.defineProperty;var r=(e,s)=>t(e,"name",{value:s,configurable:!0});var o=Object.defineProperty,n=r((e,s)=>o(e,"name",{value:s,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_SELF_MS=void 0,exports.lensSelfMs=lensSelfMs,exports.lensEnter=lensEnter,exports.lensLeave=lensLeave,exports.lensTimed=lensTimed;const node_perf_hooks_1=require("node:perf_hooks");exports.LENS_SELF_MS=Symbol.for("lensmcp.lensSelfMs");const total=globalThis;let depth=0;function lensSelfMs(){return total[exports.LENS_SELF_MS]??0}r(lensSelfMs,"lensSelfMs"),n(lensSelfMs,"lensSelfMs");function lensEnter(){return depth+=1,node_perf_hooks_1.performance.now()}r(lensEnter,"lensEnter"),n(lensEnter,"lensEnter");function lensLeave(e){depth=Math.max(0,depth-1),depth===0&&(total[exports.LENS_SELF_MS]=lensSelfMs()+Math.max(0,node_perf_hooks_1.performance.now()-e))}r(lensLeave,"lensLeave"),n(lensLeave,"lensLeave");function lensTimed(e){const s=lensEnter();try{return e()}finally{lensLeave(s)}}r(lensTimed,"lensTimed"),n(lensTimed,"lensTimed");
1
+ "use strict";var S=Object.defineProperty;var s=(n,e)=>S(n,"name",{value:e,configurable:!0});var r=Object.defineProperty,t=s((n,e)=>r(n,"name",{value:e,configurable:!0}),"t");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_SELF_BY=exports.LENS_SELF_MS=void 0,exports.lensSelfMs=lensSelfMs,exports.lensSelfBy=lensSelfBy,exports.lensEnter=lensEnter,exports.lensLeave=lensLeave,exports.lensTimed=lensTimed;const node_perf_hooks_1=require("node:perf_hooks");exports.LENS_SELF_MS=Symbol.for("lensmcp.lensSelfMs"),exports.LENS_SELF_BY=Symbol.for("lensmcp.lensSelfBy");const total=globalThis;let depth=0;function lensSelfMs(){return total[exports.LENS_SELF_MS]??0}s(lensSelfMs,"lensSelfMs"),t(lensSelfMs,"lensSelfMs");function lensSelfBy(){return total[exports.LENS_SELF_BY]??={}}s(lensSelfBy,"lensSelfBy"),t(lensSelfBy,"lensSelfBy");function lensEnter(){return depth+=1,node_perf_hooks_1.performance.now()}s(lensEnter,"lensEnter"),t(lensEnter,"lensEnter");function lensLeave(n,e="write"){if(depth=Math.max(0,depth-1),depth!==0)return;const o=Math.max(0,node_perf_hooks_1.performance.now()-n);total[exports.LENS_SELF_MS]=lensSelfMs()+o;const l=lensSelfBy();l[e]=(l[e]??0)+o}s(lensLeave,"lensLeave"),t(lensLeave,"lensLeave");function lensTimed(n,e="write"){const o=lensEnter();try{return n()}finally{lensLeave(o,e)}}s(lensTimed,"lensTimed"),t(lensTimed,"lensTimed");
@@ -1,12 +1,3 @@
1
- /**
2
- * CJS require hook: the cluster's dev webpack config externalizes every real
3
- * node_modules package (`commonjs <request>`), so at pod runtime `pg`,
4
- * `ioredis`, `bullmq` and `@nestjs/core` arrive through `Module._load`. We
5
- * intercept the EXACT package names and mutate their exports IN PLACE
6
- * (prototype/static patches, never proxies) — ESM `import` of the same CJS
7
- * package yields the same exports object, so both module systems observe the
8
- * patched behavior.
9
- */
10
1
  /**
11
2
  * A tap returns `true` once it actually patched its target, `false` when the
12
3
  * exports it needs aren't there YET. The distinction matters because of
@@ -1 +1 @@
1
- "use strict";var l=Object.defineProperty;var s=(e,n)=>l(e,"name",{value:n,configurable:!0});var a=Object.defineProperty,r=s((e,n)=>a(e,"name",{value:n,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installRequireHook=installRequireHook;const tapped=new Set;function runTap(e,n,u){try{n(u)!==!1&&tapped.add(e)}catch{tapped.add(e)}}s(runTap,"runTap"),r(runTap,"runTap");function installRequireHook(e){const n=require("node:module"),u=n._load;n._load=function(t,...c){const i=u.call(this,t,...c),o=e[t];return o&&!tapped.has(t)&&runTap(t,o,i),i};for(const t of Object.keys(e)){if(tapped.has(t))continue;const c=e[t];if(c)try{const i=require.resolve(t),o=require.cache[i];o&&runTap(t,c,o.exports)}catch{}}}s(installRequireHook,"installRequireHook"),r(installRequireHook,"installRequireHook");
1
+ "use strict";var d=Object.defineProperty;var s=(e,o)=>d(e,"name",{value:o,configurable:!0});var r=Object.defineProperty,i=s((e,o)=>r(e,"name",{value:o,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.installRequireHook=installRequireHook;const tapped_packages_1=require("./tapped-packages"),tapped=new Set;function runTap(e,o,u){try{o(u)!==!1&&tapped.add(e)}catch{tapped.add(e)}}s(runTap,"runTap"),i(runTap,"runTap");function installRequireHook(e){const o=require("node:module"),u=o._load;(0,tapped_packages_1.addTappedPackages)(Object.keys(e)),o._load=function(a,...c){const n=u.call(this,a,...c),t=e[a];return t&&!tapped.has(a)&&runTap(a,t,n),n};for(const a of Object.keys(e)){if(tapped.has(a))continue;const c=e[a];if(c)try{const n=require.resolve(a),t=require.cache[n];t&&runTap(a,c,t.exports)}catch{}}}s(installRequireHook,"installRequireHook"),i(installRequireHook,"installRequireHook");
@@ -14,6 +14,8 @@ export declare const SQL_DROPS_EVERY_MS = 1000;
14
14
  /** One statement's dropped runs since the last record. */
15
15
  export interface DroppedStatement {
16
16
  sqlId: string;
17
+ /** The tap's name for its engine, as on its `db-query` events: `postgres` | `mysql`. */
18
+ name?: string;
17
19
  op: string;
18
20
  table?: string;
19
21
  sqlName?: string;
@@ -31,6 +33,7 @@ export interface DroppedStatement {
31
33
  /** One dropped run, as the tap knows it when its bucket refuses the event. */
32
34
  export interface DroppedRun {
33
35
  sqlId: string;
36
+ name?: string;
34
37
  op: string;
35
38
  table?: string;
36
39
  sqlName?: string;
package/lib/sql-drops.js CHANGED
@@ -1 +1 @@
1
- "use strict";var n=Object.defineProperty;var u=(e,o)=>n(e,"name",{value:o,configurable:!0});var a=Object.defineProperty,d=u((e,o)=>a(e,"name",{value:o,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_DROPS_EVERY_MS=exports.SLOW_QUERY_MS=exports.SQL_DROPS_KIND=void 0,exports.noteDroppedRun=noteDroppedRun,exports.flushSqlDrops=flushSqlDrops;const flood_guard_1=require("./flood-guard"),emit_1=require("./emit");exports.SQL_DROPS_KIND="db-dropped",exports.SLOW_QUERY_MS=100,exports.SQL_DROPS_EVERY_MS=1e3;const MAX_SHAPES=200,guard=(0,flood_guard_1.createEventFloodGuard)({burst:10,perSec:2}),pending=new Map;let overflow,timer,exitHooked=!1;function noteDroppedRun(e){const o=e.durationMs>=exports.SLOW_QUERY_MS?1:0,t=e.failed?1:0;let s=pending.get(e.sqlId);!s&&pending.size>=MAX_SHAPES?(overflow??={runs:0,slow:0,failed:0,maxMs:0},overflow.runs+=1,overflow.slow+=o,overflow.failed+=t,overflow.maxMs=Math.max(overflow.maxMs,e.durationMs)):(s||(s={sqlId:e.sqlId,op:e.op,...e.table?{table:e.table}:{},...e.sqlName?{sqlName:e.sqlName}:{},runs:0,slow:0,failed:0,workMs:0,maxMs:0,firstAt:e.at,lastAt:e.at},pending.set(e.sqlId,s)),e.query&&!s.query&&(s.query=e.query),s.runs+=1,s.slow+=o,s.failed+=t,s.workMs+=e.durationMs,s.maxMs=Math.max(s.maxMs,e.durationMs),s.lastAt=Math.max(s.lastAt,e.at)),exitHooked||(exitHooked=!0,process.once("exit",()=>flushSqlDrops())),timer||(timer=setTimeout(()=>{timer=void 0,flushSqlDrops()},exports.SQL_DROPS_EVERY_MS),timer.unref?.())}u(noteDroppedRun,"noteDroppedRun"),d(noteDroppedRun,"noteDroppedRun");function flushSqlDrops(){if(timer&&(clearTimeout(timer),timer=void 0),pending.size===0&&!overflow)return;const e=[...pending.values()],o=e.reduce((r,l)=>r+l.runs,overflow?.runs??0),t=e.reduce((r,l)=>r+l.slow,overflow?.slow??0),s=e.reduce((r,l)=>r+l.failed,overflow?.failed??0);if((0,emit_1.lensEmitOutcome)("lens",s?"error":"info",`SQL: ${o} run${o===1?"":"s"} of ${e.length} statement${e.length===1?"":"s"} not on the bus (flood guard${t?`; ${t} slow`:""}${s?`; ${s} failed`:""})`,{kind:exports.SQL_DROPS_KIND,slowMs:exports.SLOW_QUERY_MS,runs:o,slow:t,failed:s,shapes:e,...overflow?{overflow}:{}},`lens:sql-drops:${emit_1.PROJECT}`,void 0,"db",guard)==="suppressed"){timer||(timer=setTimeout(()=>{timer=void 0,flushSqlDrops()},exports.SQL_DROPS_EVERY_MS),timer.unref?.());return}pending.clear(),overflow=void 0}u(flushSqlDrops,"flushSqlDrops"),d(flushSqlDrops,"flushSqlDrops");
1
+ "use strict";var u=Object.defineProperty;var n=(e,o)=>u(e,"name",{value:o,configurable:!0});var r=Object.defineProperty,d=n((e,o)=>r(e,"name",{value:o,configurable:!0}),"d");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_DROPS_EVERY_MS=exports.SLOW_QUERY_MS=exports.SQL_DROPS_KIND=void 0,exports.noteDroppedRun=noteDroppedRun,exports.flushSqlDrops=flushSqlDrops;const flood_guard_1=require("./flood-guard"),emit_1=require("./emit");exports.SQL_DROPS_KIND="db-dropped",exports.SLOW_QUERY_MS=100,exports.SQL_DROPS_EVERY_MS=1e3;const MAX_SHAPES=200,guard=(0,flood_guard_1.createEventFloodGuard)({burst:10,perSec:2}),pending=new Map;let overflow,timer,exitHooked=!1;function noteDroppedRun(e){const o=e.durationMs>=exports.SLOW_QUERY_MS?1:0,t=e.failed?1:0;let s=pending.get(e.sqlId);!s&&pending.size>=MAX_SHAPES?(overflow??={runs:0,slow:0,failed:0,maxMs:0},overflow.runs+=1,overflow.slow+=o,overflow.failed+=t,overflow.maxMs=Math.max(overflow.maxMs,e.durationMs)):(s||(s={sqlId:e.sqlId,...e.name?{name:e.name}:{},op:e.op,...e.table?{table:e.table}:{},...e.sqlName?{sqlName:e.sqlName}:{},runs:0,slow:0,failed:0,workMs:0,maxMs:0,firstAt:e.at,lastAt:e.at},pending.set(e.sqlId,s)),e.query&&!s.query&&(s.query=e.query),s.runs+=1,s.slow+=o,s.failed+=t,s.workMs+=e.durationMs,s.maxMs=Math.max(s.maxMs,e.durationMs),s.lastAt=Math.max(s.lastAt,e.at)),exitHooked||(exitHooked=!0,process.once("exit",()=>flushSqlDrops())),timer||(timer=setTimeout(()=>{timer=void 0,flushSqlDrops()},exports.SQL_DROPS_EVERY_MS),timer.unref?.())}n(noteDroppedRun,"noteDroppedRun"),d(noteDroppedRun,"noteDroppedRun");function flushSqlDrops(){if(timer&&(clearTimeout(timer),timer=void 0),pending.size===0&&!overflow)return;const e=[...pending.values()],o=e.reduce((a,l)=>a+l.runs,overflow?.runs??0),t=e.reduce((a,l)=>a+l.slow,overflow?.slow??0),s=e.reduce((a,l)=>a+l.failed,overflow?.failed??0);if((0,emit_1.lensEmitOutcome)("lens",s?"error":"info",`SQL: ${o} run${o===1?"":"s"} of ${e.length} statement${e.length===1?"":"s"} not on the bus (flood guard${t?`; ${t} slow`:""}${s?`; ${s} failed`:""})`,{kind:exports.SQL_DROPS_KIND,slowMs:exports.SLOW_QUERY_MS,runs:o,slow:t,failed:s,shapes:e,...overflow?{overflow}:{}},`lens:sql-drops:${emit_1.PROJECT}`,void 0,"db",guard)==="suppressed"){timer||(timer=setTimeout(()=>{timer=void 0,flushSqlDrops()},exports.SQL_DROPS_EVERY_MS),timer.unref?.());return}pending.clear(),overflow=void 0}n(flushSqlDrops,"flushSqlDrops"),d(flushSqlDrops,"flushSqlDrops");
@@ -0,0 +1,40 @@
1
+ import { type SiteHolder } from './callsite';
2
+ /** Transaction and session plumbing: with pools it is pure noise that says nothing about what the service does. */
3
+ export declare const SQL_SKIP_OPS: Set<string>;
4
+ /** The first word, past any leading comments — enough to skip session plumbing before parsing anything. */
5
+ export declare const firstWord: (text: string) => string;
6
+ export declare function parseSql(text: string): {
7
+ op: string;
8
+ table?: string;
9
+ sqlId: string;
10
+ tables: string[];
11
+ name?: string;
12
+ };
13
+ export declare const clip: (s: string, n: number) => string;
14
+ export interface SqlRunResult {
15
+ rows: number;
16
+ returned?: unknown[];
17
+ extra?: Record<string, unknown>;
18
+ }
19
+ export interface SqlRunStart {
20
+ text: string;
21
+ shapeText?: string;
22
+ values?: unknown[];
23
+ where: {
24
+ database?: string;
25
+ server?: string;
26
+ };
27
+ checkout?: SiteHolder;
28
+ }
29
+ export interface SqlRun {
30
+ done(err: unknown, result?: SqlRunResult): void;
31
+ abandon(): void;
32
+ }
33
+ export interface SqlRunRecorderOptions {
34
+ name: string;
35
+ bucketPrefix?: string;
36
+ fields?: Record<string, unknown>;
37
+ }
38
+ /** A statement's id for its engine: Postgres keeps the shape's id; another engine's same shape gets its own. */
39
+ export declare const engineSqlId: (engine: string, shapeId: string) => string;
40
+ export declare function createSqlRunRecorder(opts: SqlRunRecorderOptions): (start: SqlRunStart) => SqlRun | undefined;
package/lib/sql-run.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var j=Object.defineProperty;var u=(r,e)=>j(r,"name",{value:e,configurable:!0});var H=Object.defineProperty,n=u((r,e)=>H(r,"name",{value:e,configurable:!0}),"n");Object.defineProperty(exports,"__esModule",{value:!0}),exports.engineSqlId=exports.clip=exports.firstWord=exports.SQL_SKIP_OPS=void 0,exports.parseSql=parseSql,exports.createSqlRunRecorder=createSqlRunRecorder;const node_crypto_1=require("node:crypto"),redact_1=require("@lensmcp/core/redact"),sql_shape_1=require("@lensmcp/core/sql-shape"),emit_1=require("./emit"),flood_guard_1=require("./flood-guard"),flow_context_1=require("./flow-context"),sql_accounting_1=require("./sql-accounting"),callsite_1=require("./callsite"),sql_values_1=require("./sql-values"),sql_drops_1=require("./sql-drops");exports.SQL_SKIP_OPS=new Set(["BEGIN","START","COMMIT","END","ROLLBACK","SAVEPOINT","RELEASE","SET","RESET","SHOW","DEALLOCATE","DISCARD","LISTEN","UNLISTEN"]);const STATEMENT_EVERY_MS=10*6e4,STATEMENT_MAX=64*1024,SLOW_SITE_MS=250,MAX_SHAPES_REMEMBERED=2e3,firstWord=n(r=>(/^\s*(?:(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)\s*)*(\w+)/.exec(r)?.[1]??"query").toUpperCase(),"firstWord");exports.firstWord=firstWord;function parseSql(r){const e=(0,sql_shape_1.sqlShape)(r),d=(e.target??e.tables[0])?.split(".").pop();return{op:e.verb,...d?{table:d}:{},sqlId:e.id,tables:e.tables,...e.name?{name:e.name}:{}}}u(parseSql,"parseSql"),n(parseSql,"parseSql");const oneLine=n(r=>r.replace(/\s+/g," ").trim(),"oneLine"),clip=n((r,e)=>r.length>e?r.slice(0,e-1)+"\u2026":r,"clip");exports.clip=clip;function paramPreview(r){if(!(!Array.isArray(r)||r.length===0))return r.slice(0,10).map(e=>{if(e==null)return String(e);const d=typeof e=="string"?e:(()=>{try{return JSON.stringify(e)}catch{return String(e)}})();return(0,exports.clip)(d,80)})}u(paramPreview,"paramPreview"),n(paramPreview,"paramPreview");function resultPreview(r){if(!(!Array.isArray(r)||r.length===0))try{return(0,exports.clip)(JSON.stringify((0,redact_1.redactDeep)(r.slice(0,2))),240)}catch{return}}u(resultPreview,"resultPreview"),n(resultPreview,"resultPreview");const engineSqlId=n((r,e)=>r==="postgres"?e:(0,node_crypto_1.createHash)("sha256").update(`${r}:${e}`).digest("hex").slice(0,e.length||12),"engineSqlId");exports.engineSqlId=engineSqlId;function createSqlRunRecorder(r){const e=r.name,d=r.bucketPrefix??"",M=r.fields??{},W=new callsite_1.SiteSampler,V=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),R={admit:n(c=>({ok:V.admit(c).ok,suppressed:0}),"admit")},i=new Map;function T(c){const{text:E,values:O,where:K}=c,f=c.shapeText??E;if(exports.SQL_SKIP_OPS.has((0,exports.firstWord)(f)))return;const{op:Q,table:t,sqlId:B,tables:P,name:b}=parseSql(f),o=(0,exports.engineSqlId)(e,B),p=Q.toLowerCase(),y=`${d}${p}:${t??"query"}`,s=Date.now(),h=(0,flow_context_1.flowContext)(),G=(0,callsite_1.captureSite)(),L=c.checkout,S=(0,flow_context_1.liveFlowContext)(),w=paramPreview(O);S&&(S.dbCallCount=(S.dbCallCount??0)+1,(0,flow_context_1.countDbSecond)(S,s),(0,flow_context_1.noteDbShape)(S,o,(0,flow_context_1.hashDbValues)(w)));const $=(0,sql_accounting_1.beginSqlStatement)(S,h,s),I=(0,exports.clip)(oneLine(E),500),_=w&&(0,redact_1.redactSqlParams)(f,w);let g=!1;const U=n((a,q)=>{if(g)return;g=!0;const l=Date.now()-s,v=s-(i.get(o)??-1/0)>=STATEMENT_EVERY_MS;let A;try{A=W.site(o,G,{force:!!a||v||l>=SLOW_SITE_MS,...L?{fallback:L}:{}})}catch{}const C={sqlId:o,...P.length?{tables:P}:{},...b?{sqlName:b}:{},...K,...A?{site:A}:{},...v?{statement:(0,exports.clip)(E.trim(),STATEMENT_MAX)}:{}},x=(0,sql_values_1.newSqlValuesId)(s),D=x?{valuesId:x}:{};let m;if(a)m=(0,emit_1.lensEmitOutcome)("db","error",`${p}${t?" "+t:""} failed (${l}ms)`,{name:e,...M,kind:"db-query",op:p,...t?{table:t}:{},...C,query:I,..._?{params:_}:{},...D,startedAt:s,error:String(a?.message??a),durationMs:l},`db:error:${y}`,h,"cluster",R);else{const N=q?.rows??0,k=resultPreview(q?.returned);m=(0,emit_1.lensEmitOutcome)("db","info",`${p} ${t??"query"} (${N} rows, ${l}ms)`,{name:e,...M,kind:"db-query",op:p,...t?{table:t}:{},...C,query:I,..._?{params:_}:{},...k?{result:k}:{},...D,startedAt:s,rows:N,...q?.extra,durationMs:l},l>=sql_drops_1.SLOW_QUERY_MS?`db:slow:${y}`:`db:${y}`,h,"cluster",R)}m==="suppressed"&&(0,sql_drops_1.noteDroppedRun)({sqlId:o,name:e,op:p,...t?{table:t}:{},...b?{sqlName:b}:{},...i.has(o)?{}:{query:I},durationMs:l,failed:!!a,at:s}),x&&m==="written"&&(0,sql_values_1.keepSqlValues)(x,s,f,O,a?void 0:q?.returned),v&&m==="written"&&(i.delete(o),i.set(o,s),i.size>MAX_SHAPES_REMEMBERED&&i.delete(i.keys().next().value)),(0,sql_accounting_1.endSqlStatement)($,{durationMs:l,failed:!!a,emitted:m})},"done");return{done:n((a,q)=>{try{U(a,q)}catch{}},"done"),abandon:n(()=>{g||(g=!0,(0,sql_accounting_1.abandonSqlStatement)($))},"abandon")}}return u(T,"v"),n(T,"beginRun"),n(function(c){try{return T(c)}catch{return}},"begin")}u(createSqlRunRecorder,"createSqlRunRecorder"),n(createSqlRunRecorder,"createSqlRunRecorder");
@@ -15,7 +15,17 @@ export declare function keepSqlValues(id: string, at: number, sql: string, value
15
15
  * half the budget, then the reply in what is left.
16
16
  */
17
17
  export declare function keepCacheValues(id: string, at: number, op: string, key: string, args: readonly unknown[] | undefined, reply?: unknown): void;
18
- /** A day at most and 200 MB in all, oldest first. Returns how many files went. */
19
- export declare function pruneSqlValues(at: string, now?: number): number;
18
+ /** Takes the folder's prune for this process unless another claimed it within `freshMs`: an exclusive marker, its age the freshness. */
19
+ export declare function claimPrune(at: string, now: number, freshMs: number): Promise<boolean>;
20
+ export interface PruneOptions {
21
+ /** Prune only when no process claimed the folder this recently; absent: prune whoever asks (tests, one process). */
22
+ claimMs?: number;
23
+ maxAgeMs?: number;
24
+ maxBytes?: number;
25
+ }
26
+ /** A day at most and 200 MB in all, oldest first, off the loop: fs in batches, a file dated by its name and sized once. Returns how many went. */
27
+ export declare function pruneSqlValues(at: string, now?: number, opts?: PruneOptions): Promise<number>;
20
28
  /** Tests: write what is buffered now — under `at` as the lens dir when given. */
21
29
  export declare function flushSqlValuesForTests(at?: string): void;
30
+ /** Tests: the flush a timer runs (asynchronous, with its prune) — resolves once that prune has finished. */
31
+ export declare function flushAndPruneForTests(at: string): Promise<number>;
package/lib/sql-values.js CHANGED
@@ -1,3 +1,3 @@
1
- "use strict";var g=Object.defineProperty;var a=(t,l)=>g(t,"name",{value:l,configurable:!0});var y=Object.defineProperty,c=a((t,l)=>y(t,"name",{value:l,configurable:!0}),"c");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_VALUES_RUN_MAX_CHARS=void 0,exports.newSqlValuesId=newSqlValuesId,exports.newCacheValuesId=newCacheValuesId,exports.keepSqlValues=keepSqlValues,exports.keepCacheValues=keepCacheValues,exports.pruneSqlValues=pruneSqlValues,exports.flushSqlValuesForTests=flushSqlValuesForTests;const tslib_1=require("tslib"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),sql_values_1=require("@lensmcp/core/sql-values"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),capture_file_1=require("./capture-file"),emit_1=require("./emit"),appendFile=nodeFs.appendFile,appendFileSync=nodeFs.appendFileSync,mkdirSync=nodeFs.mkdirSync,readdirSync=nodeFs.readdirSync,statSync=nodeFs.statSync,unlinkSync=nodeFs.unlinkSync;exports.SQL_VALUES_RUN_MAX_CHARS=64*1024;const MAX_AGE_MS=1440*6e4,MAX_TOTAL_BYTES=200*1024*1024,FLUSH_MS=1e3,PRUNE_EVERY_MS=10*6e4,PRUNE_EVERY_BYTES=20*1024*1024;let seq=0,pending=[],timer,lastPrune=0,appended=0;const made=new Set;let lensDir=c(()=>(0,node_path_1.dirname)(emit_1.EVENT_FILE),"lensDir");function newSqlValuesId(t){if((0,capture_file_1.sqlValuesAsked)(t))return seq=(seq+1)%2147483647,(0,sql_values_1.sqlValuesId)(t,process.pid,seq)}a(newSqlValuesId,"newSqlValuesId"),c(newSqlValuesId,"newSqlValuesId");function newCacheValuesId(t){if((0,capture_file_1.sqlValuesAsked)(t))return seq=(seq+1)%2147483647,(0,sql_values_1.cacheValuesId)(t,process.pid,seq)}a(newCacheValuesId,"newCacheValuesId"),c(newCacheValuesId,"newCacheValuesId");const MIN_VALUE_CHARS=256;function keptParam(t,l){let s;if(t==null)s=String(t);else if(typeof t=="string")s=t;else if(t instanceof Date)s=t.toISOString();else if(t instanceof Uint8Array)s=`<${t.byteLength} bytes>`;else if(typeof t=="bigint")s=t.toString();else try{s=JSON.stringify(typeof t=="object"?(0,redact_1.redactDeep)(t):t)??String(t)}catch{s=String(t)}const n=s.length>l,r=(0,ai_store_1.redactAiText)(n?s.slice(0,l+4096):s);return r.length>l?{text:`${r.slice(0,l-1)}\u2026`,cut:!0}:{text:r,cut:n}}a(keptParam,"keptParam"),c(keptParam,"keptParam");function cells(t,l=0){if(typeof t=="string")return(0,ai_store_1.redactAiText)(t);if(typeof t=="bigint")return t.toString();if(t instanceof Date)return Number.isNaN(t.getTime())?null:t.toISOString();if(t instanceof Uint8Array)return`<${t.byteLength} bytes>`;if(l>8||t===null||typeof t!="object")return t;if(Array.isArray(t))return t.map(n=>cells(n,l+1));const s={};for(const[n,r]of Object.entries(t))s[n]=cells(r,l+1);return s}a(cells,"cells"),c(cells,"cells");function json(t){try{return JSON.stringify(t,function(l,s){const n=this[l];return n instanceof Uint8Array?`<${n.byteLength} bytes>`:typeof s=="bigint"?s.toString():s})??""}catch{return""}}a(json,"json"),c(json,"json");function keepSqlValues(t,l,s,n,r){try{const e={id:t,at:l};let i=exports.SQL_VALUES_RUN_MAX_CHARS-256;if(n?.length){const o=(0,redact_1.redactSqlParams)(s,n),u=Math.max(MIN_VALUE_CHARS,Math.floor(i/o.length)-8),f=[];for(const p of o){const S=keptParam(p,u),h=json(S.text).length+1;if(h>i){e.cut=!0;break}S.cut&&(e.cut=!0),f.push(S.text),i-=h}e.params=f,f.length<o.length&&(e.paramCount=o.length)}if(r?.length){const o=[];for(const u of r){if(json(u).length+1>i){e.cut=!0;break}const f=(0,redact_1.redactDeep)(cells(u)),p=json(f).length+1;if(p>i){e.cut=!0;break}o.push(f),i-=p}o.length&&(e.rows=o),e.rowCount=r.length}pending.push(e),timer??=setTimeout(flush,FLUSH_MS),timer.unref?.()}catch{}}a(keepSqlValues,"keepSqlValues"),c(keepSqlValues,"keepSqlValues");function keptReply(t,l){if(t==null)return;if(t instanceof Uint8Array)return{reply:`<${t.byteLength} bytes>`,size:24,cut:!1};if(typeof t=="number"||typeof t=="boolean")return{reply:t,size:16,cut:!1};if(typeof t=="string"){const n=t.trimStart();if((n.startsWith("{")||n.startsWith("["))&&t.length<=l)try{const e=(0,redact_1.redactDeep)(cells(JSON.parse(t))),i=json(e).length;if(i<=l)return{reply:e,size:i,cut:!1}}catch{}const r=keptParam(t,Math.max(MIN_VALUE_CHARS,l-8));return{reply:r.text,size:json(r.text).length,cut:r.cut}}if(Array.isArray(t)){const n=[];let r=2;for(const e of t){if(json(e).length+1>l-r)return{reply:n,size:r,cut:!0};const i=(0,redact_1.redactDeep)(cells(e));r+=json(i).length+1,n.push(i)}return{reply:n,size:r,cut:!1}}if(json(t).length>l){const n=keptParam(t,Math.max(MIN_VALUE_CHARS,l-8));return{reply:n.text,size:json(n.text).length,cut:!0}}const s=(0,redact_1.redactDeep)(cells(t));return{reply:s,size:json(s).length,cut:!1}}a(keptReply,"keptReply"),c(keptReply,"keptReply");function keepCacheValues(t,l,s,n,r,e){try{const i={id:t,at:l,op:s,key:(0,ai_store_1.redactAiText)(n.slice(0,1024))};let o=exports.SQL_VALUES_RUN_MAX_CHARS-256-i.key.length;if(r?.length){const f=Math.max(MIN_VALUE_CHARS,Math.floor(o/2/r.length)-8),p=[];for(const S of r){const h=keptParam(S,f),d=json(h.text).length+1;if(d>o){i.cut=!0;break}h.cut&&(i.cut=!0),p.push(h.text),o-=d}i.args=p,p.length<r.length&&(i.argCount=r.length)}const u=keptReply(e,o);u&&(i.reply=u.reply,u.cut&&(i.cut=!0)),pending.push(i),timer??=setTimeout(flush,FLUSH_MS),timer.unref?.()}catch{}}a(keepCacheValues,"keepCacheValues"),c(keepCacheValues,"keepCacheValues");function flush(t=!1){if(timer=void 0,!pending.length)return;const l=pending;pending=[];const s=new Map;for(const n of l){const r=(0,sql_values_1.keptValuesFile)(lensDir(),n.id);if(!r)continue;const e=s.get(r)??[];e.push(JSON.stringify(n)),s.set(r,e)}try{for(const[n,r]of s){const e=(0,node_path_1.dirname)(n);made.has(e)||(mkdirSync(e,{recursive:!0,mode:448}),made.add(e));const i=`${r.join(`
1
+ "use strict";var w=Object.defineProperty;var p=(e,t)=>w(e,"name",{value:t,configurable:!0});var x=Object.defineProperty,u=p((e,t)=>x(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.SQL_VALUES_RUN_MAX_CHARS=void 0,exports.newSqlValuesId=newSqlValuesId,exports.newCacheValuesId=newCacheValuesId,exports.keepSqlValues=keepSqlValues,exports.keepCacheValues=keepCacheValues,exports.claimPrune=claimPrune,exports.pruneSqlValues=pruneSqlValues,exports.flushSqlValuesForTests=flushSqlValuesForTests,exports.flushAndPruneForTests=flushAndPruneForTests;const tslib_1=require("tslib"),node_async_hooks_1=require("node:async_hooks"),nodeFs=tslib_1.__importStar(require("node:fs")),node_path_1=require("node:path"),sql_values_1=require("@lensmcp/core/sql-values"),redact_1=require("@lensmcp/core/redact"),ai_store_1=require("./ai-store"),capture_file_1=require("./capture-file"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),appendFile=nodeFs.appendFile,appendFileSync=nodeFs.appendFileSync,mkdirSync=nodeFs.mkdirSync,{readdir,stat,unlink,open}=nodeFs.promises,own=new node_async_hooks_1.AsyncResource("lensmcp.sql-values");exports.SQL_VALUES_RUN_MAX_CHARS=64*1024;const MAX_AGE_MS=1440*6e4,MAX_TOTAL_BYTES=200*1024*1024,FLUSH_MS=1e3,PRUNE_EVERY_MS=10*6e4,PRUNE_EVERY_BYTES=20*1024*1024,PRUNE_CLAIM=".prune",PRUNE_CLAIM_MS=PRUNE_EVERY_MS-3e4,PRUNE_CLAIM_BYTES_MS=3e4,PRUNE_BATCH=32;let seq=0,pending=[],timer,lastPrune=0,appended=0;const made=new Set;let lensDir=u(()=>(0,node_path_1.dirname)(emit_1.EVENT_FILE),"lensDir");function newSqlValuesId(e){if((0,capture_file_1.sqlValuesAsked)(e))return seq=(seq+1)%2147483647,(0,sql_values_1.sqlValuesId)(e,process.pid,seq)}p(newSqlValuesId,"newSqlValuesId"),u(newSqlValuesId,"newSqlValuesId");function newCacheValuesId(e){if((0,capture_file_1.sqlValuesAsked)(e))return seq=(seq+1)%2147483647,(0,sql_values_1.cacheValuesId)(e,process.pid,seq)}p(newCacheValuesId,"newCacheValuesId"),u(newCacheValuesId,"newCacheValuesId");const MIN_VALUE_CHARS=256;function keptParam(e,t){let n;if(e==null)n=String(e);else if(typeof e=="string")n=e;else if(e instanceof Date)n=e.toISOString();else if(e instanceof Uint8Array)n=`<${e.byteLength} bytes>`;else if(typeof e=="bigint")n=e.toString();else try{n=JSON.stringify(typeof e=="object"?(0,redact_1.redactDeep)(e):e)??String(e)}catch{n=String(e)}const r=n.length>t,s=(0,ai_store_1.redactAiText)(r?n.slice(0,t+4096):n);return s.length>t?{text:`${s.slice(0,t-1)}\u2026`,cut:!0}:{text:s,cut:r}}p(keptParam,"keptParam"),u(keptParam,"keptParam");function cells(e,t=0){if(typeof e=="string")return(0,ai_store_1.redactAiText)(e);if(typeof e=="bigint")return e.toString();if(e instanceof Date)return Number.isNaN(e.getTime())?null:e.toISOString();if(e instanceof Uint8Array)return`<${e.byteLength} bytes>`;if(t>8||e===null||typeof e!="object")return e;if(Array.isArray(e))return e.map(r=>cells(r,t+1));const n={};for(const[r,s]of Object.entries(e))n[r]=cells(s,t+1);return n}p(cells,"cells"),u(cells,"cells");function json(e){try{return JSON.stringify(e,function(t,n){const r=this[t];return r instanceof Uint8Array?`<${r.byteLength} bytes>`:typeof n=="bigint"?n.toString():n})??""}catch{return""}}p(json,"json"),u(json,"json");function keepSqlValues(e,t,n,r,s){(0,lens_time_1.lensTimed)(()=>keepSqlValuesNow(e,t,n,r,s),"capture")}p(keepSqlValues,"keepSqlValues"),u(keepSqlValues,"keepSqlValues");function keepSqlValuesNow(e,t,n,r,s){try{const o={id:e,at:t};let i=exports.SQL_VALUES_RUN_MAX_CHARS-256;if(r?.length){const c=(0,redact_1.redactSqlParams)(n,r),f=Math.max(MIN_VALUE_CHARS,Math.floor(i/c.length)-8),h=[];for(const d of c){const y=keptParam(d,f),m=json(y.text).length+1;if(m>i){o.cut=!0;break}y.cut&&(o.cut=!0),h.push(y.text),i-=m}o.params=h,h.length<c.length&&(o.paramCount=c.length)}if(s?.length){const c=[];for(const f of s){if(json(f).length+1>i){o.cut=!0;break}const h=(0,redact_1.redactDeep)(cells(f)),d=json(h).length+1;if(d>i){o.cut=!0;break}c.push(h),i-=d}c.length&&(o.rows=c),o.rowCount=s.length}pending.push(o),timer??=own.runInAsyncScope(()=>setTimeout(flush,FLUSH_MS)),timer.unref?.()}catch{}}p(keepSqlValuesNow,"keepSqlValuesNow"),u(keepSqlValuesNow,"keepSqlValuesNow");function keptReply(e,t){if(e==null)return;if(e instanceof Uint8Array)return{reply:`<${e.byteLength} bytes>`,size:24,cut:!1};if(typeof e=="number"||typeof e=="boolean")return{reply:e,size:16,cut:!1};if(typeof e=="string"){const r=e.trimStart();if((r.startsWith("{")||r.startsWith("["))&&e.length<=t)try{const o=(0,redact_1.redactDeep)(cells(JSON.parse(e))),i=json(o).length;if(i<=t)return{reply:o,size:i,cut:!1}}catch{}const s=keptParam(e,Math.max(MIN_VALUE_CHARS,t-8));return{reply:s.text,size:json(s.text).length,cut:s.cut}}if(Array.isArray(e)){const r=[];let s=2;for(const o of e){if(json(o).length+1>t-s)return{reply:r,size:s,cut:!0};const i=(0,redact_1.redactDeep)(cells(o));s+=json(i).length+1,r.push(i)}return{reply:r,size:s,cut:!1}}if(json(e).length>t){const r=keptParam(e,Math.max(MIN_VALUE_CHARS,t-8));return{reply:r.text,size:json(r.text).length,cut:!0}}const n=(0,redact_1.redactDeep)(cells(e));return{reply:n,size:json(n).length,cut:!1}}p(keptReply,"keptReply"),u(keptReply,"keptReply");function keepCacheValues(e,t,n,r,s,o){(0,lens_time_1.lensTimed)(()=>keepCacheValuesNow(e,t,n,r,s,o),"capture")}p(keepCacheValues,"keepCacheValues"),u(keepCacheValues,"keepCacheValues");function keepCacheValuesNow(e,t,n,r,s,o){try{const i={id:e,at:t,op:n,key:(0,ai_store_1.redactAiText)(r.slice(0,1024))};let c=exports.SQL_VALUES_RUN_MAX_CHARS-256-i.key.length;if(s?.length){const h=Math.max(MIN_VALUE_CHARS,Math.floor(c/2/s.length)-8),d=[];for(const y of s){const m=keptParam(y,h),g=json(m.text).length+1;if(g>c){i.cut=!0;break}m.cut&&(i.cut=!0),d.push(m.text),c-=g}i.args=d,d.length<s.length&&(i.argCount=s.length)}const f=keptReply(o,c);f&&(i.reply=f.reply,f.cut&&(i.cut=!0)),pending.push(i),timer??=own.runInAsyncScope(()=>setTimeout(flush,FLUSH_MS)),timer.unref?.()}catch{}}p(keepCacheValuesNow,"keepCacheValuesNow"),u(keepCacheValuesNow,"keepCacheValuesNow");function flush(e=!1){if(timer=void 0,!pending.length)return;const t=pending;pending=[],(0,lens_time_1.lensTimed)(()=>{const o=new Map;for(const i of t){const c=(0,sql_values_1.keptValuesFile)(lensDir(),i.id);if(!c)continue;const f=o.get(c)??[];f.push(JSON.stringify(i)),o.set(c,f)}try{for(const[i,c]of o){const f=(0,node_path_1.dirname)(i);made.has(f)||(mkdirSync(f,{recursive:!0,mode:448}),made.add(f));const h=`${c.join(`
2
2
  `)}
3
- `;appended+=i.length,t?appendFileSync(n,i,{mode:384}):appendFile(n,i,{mode:384},()=>{})}}catch{}(Date.now()-lastPrune>=PRUNE_EVERY_MS||appended>=PRUNE_EVERY_BYTES)&&(lastPrune=Date.now(),appended=0,pruneSqlValues((0,node_path_1.join)(lensDir(),sql_values_1.SQL_VALUES_DIR)),pruneSqlValues((0,node_path_1.join)(lensDir(),sql_values_1.CACHE_VALUES_DIR)))}a(flush,"flush"),c(flush,"flush");function pruneSqlValues(t,l=Date.now()){let s;try{s=readdirSync(t).filter(e=>e.endsWith(".jsonl")).map(e=>{const i=statSync((0,node_path_1.join)(t,e));return{file:(0,node_path_1.join)(t,e),mtime:i.mtimeMs,size:i.size}}).sort((e,i)=>e.mtime-i.mtime)}catch{return 0}let n=s.reduce((e,i)=>e+i.size,0),r=0;for(const e of s){if(l-e.mtime<=MAX_AGE_MS&&n<=MAX_TOTAL_BYTES)break;try{unlinkSync(e.file),n-=e.size,r+=1}catch{}}return r}a(pruneSqlValues,"pruneSqlValues"),c(pruneSqlValues,"pruneSqlValues"),process.once("exit",()=>flush(!0));function flushSqlValuesForTests(t){t&&(lensDir=c(()=>t,"lensDir"),made.clear()),timer&&clearTimeout(timer),flush(!0)}a(flushSqlValuesForTests,"flushSqlValuesForTests"),c(flushSqlValuesForTests,"flushSqlValuesForTests");
3
+ `;appended+=h.length,e?appendFileSync(i,h,{mode:384}):appendFile(i,h,{mode:384},()=>{})}}catch{}},"capture");const n=appended>=PRUNE_EVERY_BYTES;if(e||!(n||Date.now()-lastPrune>=PRUNE_EVERY_MS))return;lastPrune=Date.now(),appended=0;const r=lensDir(),s=n?PRUNE_CLAIM_BYTES_MS:PRUNE_CLAIM_MS;own.runInAsyncScope(()=>{pruning=pruneSqlValues((0,node_path_1.join)(r,sql_values_1.SQL_VALUES_DIR),Date.now(),{claimMs:s}).then(()=>pruneSqlValues((0,node_path_1.join)(r,sql_values_1.CACHE_VALUES_DIR),Date.now(),{claimMs:s})).catch(()=>0)})}p(flush,"flush"),u(flush,"flush");let pruning;const sizes=new Map;function minuteEnd(e){const t=/-(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\.jsonl$/.exec(e);if(!t)return;const n=Date.UTC(Number(t[1]),Number(t[2])-1,Number(t[3]),Number(t[4]),Number(t[5]));return Number.isFinite(n)?n+6e4:void 0}p(minuteEnd,"minuteEnd"),u(minuteEnd,"minuteEnd");async function claimPrune(e,t,n){const r=(0,node_path_1.join)(e,PRUNE_CLAIM);for(let s=0;s<2;s+=1){try{return await(await open(r,"wx",384)).close(),!0}catch(o){if(o.code!=="EEXIST")return!1}try{if(t-(await stat(r)).mtimeMs<n)return!1;await unlink(r)}catch{}}return!1}p(claimPrune,"claimPrune"),u(claimPrune,"claimPrune");async function pruneSqlValues(e,t=Date.now(),n={}){if(n.claimMs!==void 0&&!await claimPrune(e,t,n.claimMs))return 0;let r;try{r=await readdir(e)}catch{return 0}const s=n.maxAgeMs??MAX_AGE_MS,o=n.maxBytes??MAX_TOTAL_BYTES,i=(0,lens_time_1.lensTimed)(()=>r.filter(l=>l.endsWith(".jsonl")).map(l=>({file:(0,node_path_1.join)(e,l),end:minuteEnd(l),size:0})),"cleanup");for(const l of i.filter(a=>a.end===void 0))l.end=await stat(l.file).then(a=>a.mtimeMs,()=>t);i.sort((l,a)=>l.end-a.end);const c=u(async l=>{let a=0;for(let S=0;S<l.length;S+=PRUNE_BATCH){const A=await Promise.all(l.slice(S,S+PRUNE_BATCH).map(_=>unlink(_.file).then(()=>(sizes.delete(_.file),1),()=>0)));a+=A.reduce((_,V)=>_+V,0)}return a},"drop"),f=i.findIndex(l=>t-l.end<=s),h=f===-1?i:i.slice(0,f);let d=await c(h);const y=i.slice(h.length);let m=0;for(let l=0;l<y.length;l+=PRUNE_BATCH){await Promise.all(y.slice(l,l+PRUNE_BATCH).map(async a=>{const S=sizes.get(a.file);if(S!==void 0){a.size=S;return}try{a.size=(await stat(a.file)).size,t-a.end>12e4&&sizes.set(a.file,a.size)}catch{a.size=0}}));for(const a of y.slice(l,l+PRUNE_BATCH))m+=a.size}sizes.size>y.length+4096&&sizes.clear();const g=[];for(const l of y){if(m<=o)break;g.push(l),m-=l.size}return d+=await c(g),d}p(pruneSqlValues,"pruneSqlValues"),u(pruneSqlValues,"pruneSqlValues"),process.once("exit",()=>flush(!0));function flushSqlValuesForTests(e){e&&(lensDir=u(()=>e,"lensDir"),made.clear()),timer&&clearTimeout(timer),flush(!0)}p(flushSqlValuesForTests,"flushSqlValuesForTests"),u(flushSqlValuesForTests,"flushSqlValuesForTests");function flushAndPruneForTests(e){return lensDir=u(()=>e,"lensDir"),made.clear(),sizes.clear(),lastPrune=0,pruning=void 0,timer&&clearTimeout(timer),flush(),pruning??Promise.resolve(0)}p(flushAndPruneForTests,"flushAndPruneForTests"),u(flushAndPruneForTests,"flushAndPruneForTests");
package/lib/tap-bullmq.js CHANGED
@@ -1 +1 @@
1
- "use strict";var b=Object.defineProperty;var a=(t,e)=>b(t,"name",{value:e,configurable:!0});var g=Object.defineProperty,i=a((t,e)=>g(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),emit_1=require("./emit"),flow_context_1=require("./flow-context");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}a(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}a(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}a(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}a(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}a(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const f=Reflect.construct(r,n,s);return stampWorker(f),f}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}a(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}a(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}a(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}a(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const f=n.pause;if(typeof f!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(f.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}a(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}a(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}a(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}a(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(f),p=beginIntake(this,f),c=i(()=>{u(),p()},"endWork"),l=String(this?.name??n?.queueName??"queue"),m=flowOfJob(l,n);if(!m)return o.call(this,n,...s).finally(c);const w=jobLegId(l,n),d=Date.now(),h={flowId:m.flowId,requestId:w};if(m.own){const k=`job:${l}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${l}`,{queue:l,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:k},`queue-origin:${l}`,{...h,originType:"job",originNodeId:k})}return(0,flow_context_1.runInFlowContext)(h,async()=>{try{const k=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"ok"},`queue:${l}`,h),k}catch(k){throw(0,emit_1.lensEmit)("queue","error",`process ${n?.name}#${n?.id} failed (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"error",error:String(k?.message??k)},`queue:${l}`,h),k}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}a(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const f=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const p=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),l=s[0];let m;try{const d=JSON.stringify(l);m=d&&d!=="undefined"?d.length>300?d.slice(0,299)+"\u2026":d:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${p?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:p?.id,...m?{data:m}:{},startedAt:f,durationMs:Date.now()-f},`queue:${c}`,u);const w=sourceFor(c);w.app?.deref()!==this&&(w.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return p},"wrapped");r.__lensmcp=!0,e.add=r}a(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}a(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),f=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,f);else if(e==="completed"){let u;try{const p=n?.returnvalue??o[1],c=JSON.stringify(p);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,f)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,f)}if(!currentQueue(r))try{const u=t.opts,p=ownConnection(u?.connection);if(p){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:p}))}}catch{}ensureStatePublisher(r)}a(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}a(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const p of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([p],0,7)){const l=c?.data?.to;s.push({id:String(c.id),name:c.name,state:p,timestamp:c.timestamp??0,...typeof l=="string"?{to:l}:{}})}s.sort((p,c)=>Number(c.timestamp)-Number(p.timestamp));const f=s.slice(0,8),u=JSON.stringify([n,f.map(p=>`${p.id}${p.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:f},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}a(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}a(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}a(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
1
+ "use strict";var b=Object.defineProperty;var f=(t,e)=>b(t,"name",{value:e,configurable:!0});var h=Object.defineProperty,i=f((t,e)=>h(t,"name",{value:e,configurable:!0}),"i");Object.defineProperty(exports,"__esModule",{value:!0}),exports.bullmqTap=bullmqTap,exports.stopWorkIntake=stopWorkIntake,exports.workIntakeReport=workIntakeReport,exports.resetQueueStatePublishersForTests=resetQueueStatePublishersForTests,exports.resetWorkIntakeForTests=resetWorkIntakeForTests;const active_work_1=require("./active-work"),workerGeneration=new WeakMap,headless_flow_1=require("@lensmcp/core/headless-flow"),queue_signals_1=require("@lensmcp/core/queue-signals"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),delayedUntil=new WeakMap;function attemptOf(t){const e=t?.attemptsMade;if(typeof e!="number"||!Number.isFinite(e)||e<0)return;const o=t?.opts?.attempts;return{n:e+1,...typeof o=="number"&&Number.isFinite(o)&&o>1?{of:o}:{}}}f(attemptOf,"attemptOf"),i(attemptOf,"attemptOf");function jobFlow(t){const e=t?.opts?.__lensmcpFlow;return e&&typeof e=="object"?e:void 0}f(jobFlow,"jobFlow"),i(jobFlow,"jobFlow");const jobLegId=i((t,e)=>`job:${t}#${e?.id??"?"}`,"jobLegId");function flowOfJob(t,e){const o=jobFlow(e)?.flowId;if(o)return{flowId:o,own:!1};if((0,headless_flow_1.headlessFlowsEnabled)())return{flowId:(0,headless_flow_1.headlessJobFlowId)(t,e?.id),own:!0}}f(flowOfJob,"flowOfJob"),i(flowOfJob,"flowOfJob");const publishers=new Map,sources=new Map,sourceFor=i(t=>{let e=sources.get(t);return e||sources.set(t,e={}),e},"sourceFor"),usable=i(t=>!!t&&t.closing===void 0,"usable"),currentQueue=i(t=>{const e=sources.get(t),o=e?.app?.deref();return usable(o)?o:e?.own},"currentQueue");function ownConnection(t){if(!t||typeof t!="object")return;const e=t;if(typeof e.duplicate=="function")try{return e.duplicate()}catch{return}return Object.fromEntries(Object.entries(e).filter(([,o])=>typeof o!="function"))}f(ownConnection,"ownConnection"),i(ownConnection,"ownConnection");function bullmqTap(t){const e=t;if(typeof e?.Queue!="function"||typeof e?.Worker!="function")return!1;tappedQueue=e.Queue;try{tapQueueAdd(e)}catch{}try{tapWorkerEmit(e)}catch{}try{tapWorkerProcess(e)}catch{}try{tapJobDelay(e)}catch{}try{tapWorkerStamp(e)}catch{}try{tapWorkerIntake(e)}catch{}try{tapWorkerConstruct(e)}catch{}try{installWorkIntakeControl()}catch{}return!0}f(bullmqTap,"bullmqTap"),i(bullmqTap,"bullmqTap");function stampWorker(t){try{if(workerGeneration.has(t))return;workerGeneration.set(t,(0,active_work_1.activeWorkGeneration)()),knownWorkers.add(new WeakRef(t))}catch{}}f(stampWorker,"stampWorker"),i(stampWorker,"stampWorker");function tapWorkerConstruct(t){const e=t.Worker;if(typeof e!="function"||e.__lensmcpGen)return;const o=new Proxy(e,{construct(r,n,s){const p=Reflect.construct(r,n,s);return stampWorker(p),p}});Object.defineProperty(e,"__lensmcpGen",{value:!0,enumerable:!1}),t.Worker=o}f(tapWorkerConstruct,"tapWorkerConstruct"),i(tapWorkerConstruct,"tapWorkerConstruct");function tapWorkerStamp(t){const e=t.Worker?.prototype;if(e)for(const o of["createLockManager","run"]){const r=e[o];if(typeof r!="function"||r.__lensmcpStamp)continue;const n=i(function(...s){return stampWorker(this),r.apply(this,s)},"wrapped");n.__lensmcpStamp=!0,e[o]=n}}f(tapWorkerStamp,"tapWorkerStamp"),i(tapWorkerStamp,"tapWorkerStamp");const knownWorkers=new Set,stoppedWorkers=new WeakSet,intake=new Map,INTAKE_GENERATIONS_KEPT=64;function intakeOf(t){let e=intake.get(t);if(!e){intake.set(t,e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0});for(const o of intake.keys()){if(intake.size<=INTAKE_GENERATIONS_KEPT)break;intake.delete(o)}}return e}f(intakeOf,"intakeOf"),i(intakeOf,"intakeOf");function beginIntake(t,e){if(e===void 0)return()=>{};const o=intakeOf(e);return o.running+=1,stoppedWorkers.has(t)&&(o.takenAfterStop+=1),()=>{o.running-=1,o.stoppedAt!==void 0&&(o.finishedAfterStop+=1)}}f(beginIntake,"beginIntake"),i(beginIntake,"beginIntake");function stopWorkIntake(t){const e={workers:0,running:0,runningAtStop:0,takenAfterStop:0,finishedAfterStop:0},o=Date.now();for(const r of knownWorkers){const n=r.deref();if(!n){knownWorkers.delete(r);continue}const s=workerGeneration.get(n);if(s===void 0||s>=t||stoppedWorkers.has(n))continue;const p=n.pause;if(typeof p!="function")continue;stoppedWorkers.add(n),knownWorkers.delete(r);try{Promise.resolve(p.call(n,!0)).catch(()=>{})}catch{}const u=intakeOf(s);u.stoppedAt===void 0&&(u.stoppedAt=o,u.runningAtStop=u.running,e.running+=u.running,e.runningAtStop+=u.running),u.workers+=1,e.workers+=1}return e}f(stopWorkIntake,"stopWorkIntake"),i(stopWorkIntake,"stopWorkIntake");function workIntakeReport(t){const e=intake.get(t);if(!(!e||e.stoppedAt===void 0))return{workers:e.workers,running:e.running,runningAtStop:e.runningAtStop,takenAfterStop:e.takenAfterStop,finishedAfterStop:e.finishedAfterStop}}f(workIntakeReport,"workIntakeReport"),i(workIntakeReport,"workIntakeReport");function tapWorkerIntake(t){const e=t.Worker?.prototype;if(!e)return;const o=e.moveToActive;if(typeof o=="function"&&!o.__lensmcpIntake){const n=i(function(...s){return stoppedWorkers.has(this)?Promise.resolve(void 0):o.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.moveToActive=n}const r=e.resume;if(typeof r=="function"&&!r.__lensmcpIntake){const n=i(function(...s){if(!stoppedWorkers.has(this))return r.apply(this,s)},"wrapped");n.__lensmcpIntake=!0,e.resume=n}}f(tapWorkerIntake,"tapWorkerIntake"),i(tapWorkerIntake,"tapWorkerIntake");function installWorkIntakeControl(){const t=globalThis;t.__lensmcpStopWorkIntake=stopWorkIntake,t.__lensmcpWorkIntakeReport=workIntakeReport}f(installWorkIntakeControl,"installWorkIntakeControl"),i(installWorkIntakeControl,"installWorkIntakeControl");function tapWorkerProcess(t){const e=t.Worker?.prototype,o=e?.callProcessJob;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=workerGeneration.get(this),u=(0,active_work_1.beginActiveWork)(p),a=beginIntake(this,p),c=i(()=>{u(),a()},"endWork"),l=String(this?.name??n?.queueName??"queue"),m=flowOfJob(l,n);if(!m)return o.call(this,n,...s).finally(c);const w=jobLegId(l,n),d=Date.now(),y={flowId:m.flowId,requestId:w};if(m.own){const k=`job:${l}/${n?.name??"job"}`;(0,emit_1.lensEmit)("queue","info",`job ${n?.name??""}#${n?.id??"?"} \xB7 ${l}`,{queue:l,kind:"flow-origin",job:n?.name,jobId:n?.id,originNodeId:k},`queue-origin:${l}`,{...y,originType:"job",originNodeId:k})}return(0,flow_context_1.runInFlowContext)(y,async()=>{try{const k=await o.call(this,n,...s);return(0,emit_1.lensEmit)("queue","info",`process ${n?.name}#${n?.id} (${Date.now()-d}ms)`,{queue:l,kind:"queue-process",job:n?.name,jobId:n?.id,startedAt:d,durationMs:Date.now()-d,status:"ok"},`queue:${l}`,y),k}catch(k){try{reportProcessThrow(k,n,l,d,y)}catch{}throw k}finally{c()}})},"wrapped");r.__lensmcp=!0,e.callProcessJob=r}f(tapWorkerProcess,"tapWorkerProcess"),i(tapWorkerProcess,"tapWorkerProcess");function reportProcessThrow(t,e,o,r,n){const s=Date.now()-r,p={queue:o,kind:"queue-process",job:e?.name,jobId:e?.id,startedAt:r,durationMs:s},u=(0,queue_signals_1.isControlFlowThrow)(t);if(u){const c=u==="delayed"&&e&&typeof e=="object"?delayedUntil.get(e):void 0;(0,emit_1.lensEmit)("queue","info",`process ${e?.name}#${e?.id} ${(0,queue_signals_1.queueSignalTitle)(u)} (${s}ms)`,{...p,status:u,...c!==void 0?{delayMs:Math.max(0,c-Date.now()),delayedUntil:c}:{}},`queue:${o}`,n);return}const a=attemptOf(e);(0,emit_1.lensEmit)("queue","error",`process ${e?.name}#${e?.id} failed${a?.of?`, attempt ${a.n} of ${a.of}`:""} (${s}ms)`,{...p,status:"error",error:String(t?.message??t),...a?{attempt:a.n,...a.of?{attempts:a.of}:{}}:{}},`queue:${o}`,n)}f(reportProcessThrow,"reportProcessThrow"),i(reportProcessThrow,"reportProcessThrow");function tapJobDelay(t){const e=t.Job?.prototype,o=e?.moveToDelayed;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(...n){try{typeof n[0]=="number"&&Number.isFinite(n[0])&&delayedUntil.set(this,n[0])}catch{}return o.apply(this,n)},"wrapped");r.__lensmcp=!0,e.moveToDelayed=r}f(tapJobDelay,"tapJobDelay"),i(tapJobDelay,"tapJobDelay");function tapQueueAdd(t){const e=t.Queue?.prototype,o=e?.add;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(async function(n,...s){const p=Date.now(),u=(0,flow_context_1.flowContext)();if(u?.flowId){const c=s[1]??{};s[1]={...c,__lensmcpFlow:{flowId:u.flowId,...u.requestId?{originRequestId:u.requestId}:{}}}}const a=await o.call(this,n,...s);try{const c=String(this?.name??"queue"),l=s[0];let m;try{const d=JSON.stringify(l);m=d&&d!=="undefined"?d.length>300?d.slice(0,299)+"\u2026":d:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`enqueued ${n}#${a?.id} \u2192 ${c}`,{queue:c,kind:"queue-enqueued",job:n,jobId:a?.id,...m?{data:m}:{},startedAt:p,durationMs:Date.now()-p},`queue:${c}`,u);const w=sourceFor(c);w.app?.deref()!==this&&(w.app=new WeakRef(this)),ensureStatePublisher(c)}catch{}return a},"wrapped");r.__lensmcp=!0,e.add=r}f(tapQueueAdd,"tapQueueAdd"),i(tapQueueAdd,"tapQueueAdd");function tapWorkerEmit(t){const e=t.Worker?.prototype,o=e?.emit;if(!e||typeof o!="function"||o.__lensmcp)return;const r=i(function(n,...s){try{observeWorkerEvent(this,String(n),s)}catch{}return o.call(this,n,...s)},"wrapped");r.__lensmcp=!0,e.emit=r}f(tapWorkerEmit,"tapWorkerEmit"),i(tapWorkerEmit,"tapWorkerEmit");function observeWorkerEvent(t,e,o){if(e!=="active"&&e!=="completed"&&e!=="failed")return;const r=String(t.name??"queue"),n=o[0],s=flowOfJob(r,n),p=s?{flowId:s.flowId,requestId:jobLegId(r,n)}:void 0;if(e==="active")(0,emit_1.lensEmit)("queue","info",`processing ${n?.name}#${n?.id}`,{queue:r,kind:"queue-active",jobId:n?.id},`queue:${r}`,p);else if(e==="completed"){let u;try{const a=n?.returnvalue??o[1],c=JSON.stringify(a);u=c&&c!=="undefined"?c.length>160?c.slice(0,159)+"\u2026":c:void 0}catch{}(0,emit_1.lensEmit)("queue","info",`completed ${n?.name}#${n?.id}`,{queue:r,kind:"queue-completed",jobId:n?.id,...u?{returned:u}:{}},`queue:${r}`,p)}else{const u=o[1];(0,emit_1.lensEmit)("queue","error",`job ${n?.id} failed: ${u?.message}`,{queue:r,kind:"queue-failed",jobId:n?.id,error:String(u?.message??u)},`queue:${r}`,p)}if(!currentQueue(r))try{const u=t.opts,a=ownConnection(u?.connection);if(a){const c=snapshotQueueClass();c&&(sourceFor(r).own=new c(r,{connection:a}))}}catch{}ensureStatePublisher(r)}f(observeWorkerEvent,"observeWorkerEvent"),i(observeWorkerEvent,"observeWorkerEvent");let tappedQueue;function snapshotQueueClass(){if(tappedQueue)return tappedQueue;try{return require("bullmq").Queue}catch{return}}f(snapshotQueueClass,"snapshotQueueClass"),i(snapshotQueueClass,"snapshotQueueClass");function ensureStatePublisher(t){if(publishers.has(t))return;let e="";const o=setInterval(()=>{(async()=>{try{const r=currentQueue(t);if(!r)return;const n=await r.getJobCounts(),s=[];for(const a of["active","waiting","failed","completed","delayed"])for(const c of await r.getJobs([a],0,7)){const l=c?.data?.to;s.push({id:String(c.id),name:c.name,state:a,timestamp:c.timestamp??0,...typeof l=="string"?{to:l}:{}})}s.sort((a,c)=>Number(c.timestamp)-Number(a.timestamp));const p=s.slice(0,8),u=JSON.stringify([n,p.map(a=>`${a.id}${a.state}`)]);if(u===e)return;e=u,(0,emit_1.lensEmit)("queue","info",`queue state: ${n.active??0} active \xB7 ${n.waiting??0} waiting \xB7 ${n.failed??0} failed`,{queue:t,kind:"queue-state",counts:n,recent:p},`queue:${t}`)}catch{}})()},2e3);o.unref?.(),publishers.set(t,o)}f(ensureStatePublisher,"ensureStatePublisher"),i(ensureStatePublisher,"ensureStatePublisher");function resetQueueStatePublishersForTests(){for(const t of publishers.values())clearInterval(t);publishers.clear(),sources.clear()}f(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests"),i(resetQueueStatePublishersForTests,"resetQueueStatePublishersForTests");function resetWorkIntakeForTests(){knownWorkers.clear(),intake.clear()}f(resetWorkIntakeForTests,"resetWorkIntakeForTests"),i(resetWorkIntakeForTests,"resetWorkIntakeForTests");
@@ -1 +1 @@
1
- "use strict";var q=Object.defineProperty;var u=(r,t)=>q(r,"name",{value:t,configurable:!0});var z=Object.defineProperty,o=u((r,t)=>z(r,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EXCHANGE_ID=void 0,exports.tapIngress=tapIngress,exports.resetIngressTapForTests=resetIngressTapForTests;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),zlib=tslib_1.__importStar(require("node:zlib")),headless_flow_1=require("@lensmcp/core/headless-flow"),http_exchange_1=require("@lensmcp/core/http-exchange"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),http_store_1=require("./http-store");exports.EXCHANGE_ID=Symbol.for("lensmcp.exchangeId");const MAX_READ=2*1024*1024,MAX_PATH_CHARS=256;let originalEmit;function tapIngress(){if(originalEmit)return;const r=(0,http_store_1.httpCaptureMode)();if(r==="off")return;(0,http_store_1.primeHttpStore)();const t=http.Server.prototype,s=t.emit;originalEmit=s,t.emit=function(e,...n){if(e==="request")try{watch(n[0],n[1],r)}catch{}return s.call(this,e,...n)}}u(tapIngress,"tapIngress"),o(tapIngress,"tapIngress");function resetIngressTapForTests(){originalEmit&&(http.Server.prototype.emit=originalEmit),originalEmit=void 0}u(resetIngressTapForTests,"resetIngressTapForTests"),o(resetIngressTapForTests,"resetIngressTapForTests");const one=o(r=>r===void 0?void 0:Array.isArray(r)?r.join(", "):String(r),"one"),pairs=o(r=>Object.entries(r).flatMap(([t,s])=>s===void 0?[]:[[t,one(s)]]),"pairs");class Tee{static{u(this,"Tee")}static{o(this,"Tee")}constructor(t=!0){this.keep=t,this.chunks=[],this.read=0,this.size=0,this.tail=Buffer.alloc(0)}take(t,s){if(t==null||typeof t=="function")return;if(!this.keep&&typeof t=="string"){this.size+=Buffer.byteLength(t,typeof s=="string"?s:"utf8"),this.tail=Buffer.alloc(0);return}const e=Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):typeof t=="string"?Buffer.from(t,typeof s=="string"?s:"utf8"):void 0;e&&(this.size+=e.length,this.tail=Buffer.from(e.length>=4?e.subarray(e.length-4):Buffer.concat([this.tail,e]).subarray(-4)),this.keep&&this.read<MAX_READ&&(this.chunks.push(e),this.read+=e.length))}bytes(){return Buffer.concat(this.chunks)}}function watch(r,t,s){if(!r||!t||r[exports.EXCHANGE_ID])return;const e=r.url??"/",n=e.indexOf("?"),m=n<0?e:e.slice(0,n);if((0,headless_flow_1.isProbePath)(m))return;const g=(0,http_store_1.newExchangeId)();r[exports.EXCHANGE_ID]=g;const _=Date.now(),y=s==="bodies"&&!(0,http_store_1.proofBoundHeaders)(r.headers),w=new Tee,h=new Tee(y);if(y){const l=r.emit;r.emit=function(d,...i){return d==="data"&&w.take(i[0]),l.call(this,d,...i)}}{const l=t.write,d=t.end;t.write=function(i,...c){return h.take(i,c[0]),l.call(this,i,...c)},t.end=function(i,...c){return h.take(i,c[0]),d.call(this,i,...c)}}let p=!1;const a=o(()=>{if(!p){p=!0;try{(0,lens_time_1.lensTimed)(()=>(0,http_store_1.queueHttpExchange)(exchangeOf(g,r,t,{url:e,q:n,path:m,startedAt:_,bodies:y,sent:w,answered:h})))}catch{}}},"finish");t.once("finish",a),t.once("close",a)}u(watch,"watch"),o(watch,"watch");function unpacked(r,t){try{if(r==="gzip"||r==="x-gzip")return zlib.gunzipSync(t,{maxOutputLength:MAX_READ});if(r==="br")return zlib.brotliDecompressSync(t,{maxOutputLength:MAX_READ});if(r==="deflate")return zlib.inflateSync(t,{maxOutputLength:MAX_READ})}catch{return}}u(unpacked,"unpacked"),o(unpacked,"unpacked");function exchangeOf(r,t,s,e){const n=[],m=[],g=[],_=(0,http_store_1.redactHeaders)(pairs(t.headers));n.push(..._.redacted);const y=(0,http_store_1.redactHeaders)(pairs(s.getHeaders()));n.push(...y.redacted);const w=e.bodies&&e.q>=0?(0,http_store_1.redactQuery)(e.url.slice(e.q)):[];let h;e.bodies&&e.sent.size&&(h=(0,http_store_1.keepBody)(one(t.headers["content-type"])??"",e.sent.bytes(),e.sent.size,m));let p;const a=(one(s.getHeader("content-encoding"))??"").trim().toLowerCase();let l=!a||a==="identity"?e.answered.size:(a==="gzip"||a==="x-gzip")&&e.answered.size>=18&&e.answered.tail.length===4?e.answered.tail.readUInt32LE(0):void 0;if(e.bodies&&e.answered.size){const f=one(s.getHeader("content-type"))??"";if(!a||a==="identity")p=(0,http_store_1.keepBody)(f,e.answered.bytes(),e.answered.size,g);else{const b=e.answered.size<=MAX_READ?unpacked(a,e.answered.bytes()):void 0;b&&(l=b.length),p=b?(0,http_store_1.keepBody)(f,b,b.length,g):{contentType:f.split(";")[0].trim().toLowerCase(),size:e.answered.size,kept:0,truncated:!1,omitted:"encoded"}}}const d=one(t.headers.host)??"localhost",i=e.path.length>MAX_PATH_CHARS?`${e.path.slice(0,MAX_PATH_CHARS)}\u2026`:e.path,c=one(t.headers["x-lensmcp-flow-id"]),x=one(t.headers[http_exchange_1.LENS_REQUEST_ID_HEADER])||one(t.headers["x-request-id"]),E=!s.writableFinished;return{schemaVersion:1,id:r,capturedAt:Date.now(),side:"ingress",service:emit_1.PROJECT,...c?{flowId:c}:{},...x?{requestId:x}:{},method:(t.method??"GET").toUpperCase(),url:`http://${d}${i}`,host:d.split(":")[0]??d,path:i,status:s.statusCode,...s.statusMessage?{statusText:s.statusMessage}:{},...E?{error:"the client went away before the answer ended"}:{},startedAt:e.startedAt,durationMs:Date.now()-e.startedAt,capture:e.bodies?"bodies":"headers",request:{headers:_.headers,...w.length?{query:w}:{},...h?{body:h}:{}},response:{headers:y.headers,bytes:{wire:e.answered.size,...l!==void 0?{decoded:l}:{}},...p?{body:p}:{}},redacted:{headers:[...new Set(n)],bodyFields:[...m.map(f=>`request.${f}`),...g.map(f=>`response.${f}`)]}}}u(exchangeOf,"exchangeOf"),o(exchangeOf,"exchangeOf");
1
+ "use strict";var q=Object.defineProperty;var u=(r,t)=>q(r,"name",{value:t,configurable:!0});var z=Object.defineProperty,o=u((r,t)=>z(r,"name",{value:t,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.EXCHANGE_ID=void 0,exports.tapIngress=tapIngress,exports.resetIngressTapForTests=resetIngressTapForTests;const tslib_1=require("tslib"),http=tslib_1.__importStar(require("node:http")),zlib=tslib_1.__importStar(require("node:zlib")),headless_flow_1=require("@lensmcp/core/headless-flow"),http_exchange_1=require("@lensmcp/core/http-exchange"),emit_1=require("./emit"),lens_time_1=require("./lens-time"),http_store_1=require("./http-store");exports.EXCHANGE_ID=Symbol.for("lensmcp.exchangeId");const MAX_READ=2*1024*1024,MAX_PATH_CHARS=256;let originalEmit;function tapIngress(){if(originalEmit)return;const r=(0,http_store_1.httpCaptureMode)();if(r==="off")return;(0,http_store_1.primeHttpStore)();const t=http.Server.prototype,s=t.emit;originalEmit=s,t.emit=function(e,...n){if(e==="request")try{watch(n[0],n[1],r)}catch{}return s.call(this,e,...n)}}u(tapIngress,"tapIngress"),o(tapIngress,"tapIngress");function resetIngressTapForTests(){originalEmit&&(http.Server.prototype.emit=originalEmit),originalEmit=void 0}u(resetIngressTapForTests,"resetIngressTapForTests"),o(resetIngressTapForTests,"resetIngressTapForTests");const one=o(r=>r===void 0?void 0:Array.isArray(r)?r.join(", "):String(r),"one"),pairs=o(r=>Object.entries(r).flatMap(([t,s])=>s===void 0?[]:[[t,one(s)]]),"pairs");class Tee{static{u(this,"Tee")}static{o(this,"Tee")}constructor(t=!0){this.keep=t,this.chunks=[],this.read=0,this.size=0,this.tail=Buffer.alloc(0)}take(t,s){if(t==null||typeof t=="function")return;if(!this.keep&&typeof t=="string"){this.size+=Buffer.byteLength(t,typeof s=="string"?s:"utf8"),this.tail=Buffer.alloc(0);return}const e=Buffer.isBuffer(t)?t:t instanceof Uint8Array?Buffer.from(t):typeof t=="string"?Buffer.from(t,typeof s=="string"?s:"utf8"):void 0;e&&(this.size+=e.length,this.tail=Buffer.from(e.length>=4?e.subarray(e.length-4):Buffer.concat([this.tail,e]).subarray(-4)),this.keep&&this.read<MAX_READ&&(this.chunks.push(e),this.read+=e.length))}bytes(){return Buffer.concat(this.chunks)}}function watch(r,t,s){if(!r||!t||r[exports.EXCHANGE_ID])return;const e=r.url??"/",n=e.indexOf("?"),m=n<0?e:e.slice(0,n);if((0,headless_flow_1.isProbePath)(m))return;const g=(0,http_store_1.newExchangeId)();r[exports.EXCHANGE_ID]=g;const _=Date.now(),y=s==="bodies"&&!(0,http_store_1.proofBoundHeaders)(r.headers),w=new Tee,h=new Tee(y);if(y){const l=r.emit;r.emit=function(d,...i){return d==="data"&&w.take(i[0]),l.call(this,d,...i)}}{const l=t.write,d=t.end;t.write=function(i,...c){return h.take(i,c[0]),l.call(this,i,...c)},t.end=function(i,...c){return h.take(i,c[0]),d.call(this,i,...c)}}let p=!1;const a=o(()=>{if(!p){p=!0;try{(0,lens_time_1.lensTimed)(()=>(0,http_store_1.queueHttpExchange)(exchangeOf(g,r,t,{url:e,q:n,path:m,startedAt:_,bodies:y,sent:w,answered:h})),"capture")}catch{}}},"finish");t.once("finish",a),t.once("close",a)}u(watch,"watch"),o(watch,"watch");function unpacked(r,t){try{if(r==="gzip"||r==="x-gzip")return zlib.gunzipSync(t,{maxOutputLength:MAX_READ});if(r==="br")return zlib.brotliDecompressSync(t,{maxOutputLength:MAX_READ});if(r==="deflate")return zlib.inflateSync(t,{maxOutputLength:MAX_READ})}catch{return}}u(unpacked,"unpacked"),o(unpacked,"unpacked");function exchangeOf(r,t,s,e){const n=[],m=[],g=[],_=(0,http_store_1.redactHeaders)(pairs(t.headers));n.push(..._.redacted);const y=(0,http_store_1.redactHeaders)(pairs(s.getHeaders()));n.push(...y.redacted);const w=e.bodies&&e.q>=0?(0,http_store_1.redactQuery)(e.url.slice(e.q)):[];let h;e.bodies&&e.sent.size&&(h=(0,http_store_1.keepBody)(one(t.headers["content-type"])??"",e.sent.bytes(),e.sent.size,m));let p;const a=(one(s.getHeader("content-encoding"))??"").trim().toLowerCase();let l=!a||a==="identity"?e.answered.size:(a==="gzip"||a==="x-gzip")&&e.answered.size>=18&&e.answered.tail.length===4?e.answered.tail.readUInt32LE(0):void 0;if(e.bodies&&e.answered.size){const f=one(s.getHeader("content-type"))??"";if(!a||a==="identity")p=(0,http_store_1.keepBody)(f,e.answered.bytes(),e.answered.size,g);else{const b=e.answered.size<=MAX_READ?unpacked(a,e.answered.bytes()):void 0;b&&(l=b.length),p=b?(0,http_store_1.keepBody)(f,b,b.length,g):{contentType:f.split(";")[0].trim().toLowerCase(),size:e.answered.size,kept:0,truncated:!1,omitted:"encoded"}}}const d=one(t.headers.host)??"localhost",i=e.path.length>MAX_PATH_CHARS?`${e.path.slice(0,MAX_PATH_CHARS)}\u2026`:e.path,c=one(t.headers["x-lensmcp-flow-id"]),x=one(t.headers[http_exchange_1.LENS_REQUEST_ID_HEADER])||one(t.headers["x-request-id"]),E=!s.writableFinished;return{schemaVersion:1,id:r,capturedAt:Date.now(),side:"ingress",service:emit_1.PROJECT,...c?{flowId:c}:{},...x?{requestId:x}:{},method:(t.method??"GET").toUpperCase(),url:`http://${d}${i}`,host:d.split(":")[0]??d,path:i,status:s.statusCode,...s.statusMessage?{statusText:s.statusMessage}:{},...E?{error:"the client went away before the answer ended"}:{},startedAt:e.startedAt,durationMs:Date.now()-e.startedAt,capture:e.bodies?"bodies":"headers",request:{headers:_.headers,...w.length?{query:w}:{},...h?{body:h}:{}},response:{headers:y.headers,bytes:{wire:e.answered.size,...l!==void 0?{decoded:l}:{}},...p?{body:p}:{}},redacted:{headers:[...new Set(n)],bodyFields:[...m.map(f=>`request.${f}`),...g.map(f=>`response.${f}`)]}}}u(exchangeOf,"exchangeOf"),o(exchangeOf,"exchangeOf");
@@ -0,0 +1,12 @@
1
+ export declare const KAFKA_FLOW_HEADER = "x-lensmcp-flow-id";
2
+ export declare const KAFKA_PARENT_HEADER = "x-lensmcp-parent-request-id";
3
+ export declare const KAFKA_ORIGIN_HEADER = "x-lensmcp-origin-node-id";
4
+ export declare const KAFKA_LEG_HEADER = "x-lensmcp-request-id";
5
+ type Headers = Record<string, unknown>;
6
+ export declare function kafkaStamp(headers: Headers | undefined): {
7
+ flowId: string;
8
+ leg?: string;
9
+ parent?: string;
10
+ } | undefined;
11
+ export declare function kafkaTap(exportsObject: unknown): boolean;
12
+ export {};
@@ -0,0 +1 @@
1
+ "use strict";var m=Object.defineProperty;var l=(e,t)=>m(e,"name",{value:t,configurable:!0});var h=Object.defineProperty,u=l((e,t)=>h(e,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.KAFKA_LEG_HEADER=exports.KAFKA_ORIGIN_HEADER=exports.KAFKA_PARENT_HEADER=exports.KAFKA_FLOW_HEADER=void 0,exports.kafkaStamp=kafkaStamp,exports.kafkaTap=kafkaTap;const headless_flow_1=require("@lensmcp/core/headless-flow"),http_exchange_1=require("@lensmcp/core/http-exchange"),active_work_1=require("./active-work"),emit_1=require("./emit"),flow_context_1=require("./flow-context");exports.KAFKA_FLOW_HEADER="x-lensmcp-flow-id",exports.KAFKA_PARENT_HEADER="x-lensmcp-parent-request-id",exports.KAFKA_ORIGIN_HEADER="x-lensmcp-origin-node-id",exports.KAFKA_LEG_HEADER=http_exchange_1.LENS_REQUEST_ID_HEADER;const LENS_HEADERS=[exports.KAFKA_FLOW_HEADER,exports.KAFKA_PARENT_HEADER,exports.KAFKA_ORIGIN_HEADER,exports.KAFKA_LEG_HEADER];let sendSeq=0;const newSendId=u(e=>`${process.pid.toString(36)}${e.toString(36)}${(sendSeq=(sendSeq+1)%16777215).toString(36)}`,"newSendId"),sizeOf=u(e=>typeof e=="string"?Buffer.byteLength(e):e instanceof Uint8Array?e.byteLength:0,"sizeOf"),headerText=u(e=>{const t=Array.isArray(e)?e[0]:e;if(typeof t=="string")return t||void 0;if(t instanceof Uint8Array)return Buffer.from(t).toString("utf8")||void 0},"headerText"),hasLensHeader=u(e=>!!e&&Object.keys(e).some(t=>LENS_HEADERS.includes(t.toLowerCase())),"hasLensHeader"),headerOf=u((e,t)=>{if(!e)return;if(t in e)return headerText(e[t]);const r=Object.keys(e).find(s=>s.toLowerCase()===t);return r?headerText(e[r]):void 0},"headerOf");function kafkaStamp(e){const t=headerOf(e,exports.KAFKA_FLOW_HEADER);if(!t)return;const r=headerOf(e,exports.KAFKA_LEG_HEADER),s=headerOf(e,exports.KAFKA_PARENT_HEADER);return{flowId:t,...r?{leg:r}:{},...s?{parent:s}:{}}}l(kafkaStamp,"kafkaStamp"),u(kafkaStamp,"kafkaStamp");function stampTopic(e,t,r){const s=String(e.topic??""),n=Array.isArray(e.messages)?e.messages:void 0;if(!r?.flowId||!n||!s)return e;const a={[exports.KAFKA_FLOW_HEADER]:r.flowId,[exports.KAFKA_LEG_HEADER]:`job:${s}#${t}`,...r.requestId?{[exports.KAFKA_PARENT_HEADER]:r.requestId}:{},...r.originNodeId?{[exports.KAFKA_ORIGIN_HEADER]:r.originNodeId}:{}};return{...e,messages:n.map(o=>!isPlainObject(o)||hasLensHeader(o.headers)?o:{...o,headers:{...o.headers??{},...a}})}}l(stampTopic,"stampTopic"),u(stampTopic,"stampTopic");const isPlainObject=u(e=>{if(!e||typeof e!="object")return!1;const t=Object.getPrototypeOf(e);return t===Object.prototype||t===null},"isPlainObject");function reportSend(e,t,r,s,n,a){const o=Array.isArray(a)?a:[],i=Date.now()-r;for(const f of e){const c=String(f.topic??"");if(!c)continue;const d=Array.isArray(f.messages)?f.messages:[];let p=0,y=0;for(const g of d)p+=sizeOf(g?.value),g?.key!==void 0&&g?.key!==null&&(y+=1);const E=[...new Set(o.filter(g=>g.topicName===c&&typeof g.partition=="number").map(g=>g.partition))],_=d.length,A={queue:c,broker:"kafka",kind:"queue-enqueued",jobId:t,messages:_,keyed:y,bytes:p,...E.length?{partitions:E}:{},startedAt:r,durationMs:i};n?(0,emit_1.lensEmit)("queue","error",`send of ${_} message${_===1?"":"s"} \u2192 ${c} failed (${i}ms)`,{...A,status:"error",error:String(n?.message??n)},`queue:kafka:error:${c}`,s):(0,emit_1.lensEmit)("queue","info",`sent ${_} message${_===1?"":"s"} \u2192 ${c} (${i}ms)`,A,`queue:kafka:${c}`,s)}}l(reportSend,"reportSend"),u(reportSend,"reportSend");function wrapSend(e,t){if(e.__lensmcp)return e;const r=u(function(...s){const n=s[0];let a,o="",i=0,f;try{if(n&&typeof n=="object")if(i=Date.now(),o=newSendId(i),f=(0,flow_context_1.flowContext)(),t)Array.isArray(n.topicMessages)&&(a=n.topicMessages.map(d=>stampTopic(d,o,f)),s[0]={...n,topicMessages:a});else{const d=stampTopic(n,o,f);a=[d],s[0]=d}}catch{a=void 0}const c=e.apply(this,s);if(a&&c&&typeof c.then=="function"){const d=a;c.then(p=>{try{reportSend(d,o,i,f,void 0,p)}catch{}},p=>{try{reportSend(d,o,i,f,p??new Error("send failed"),void 0)}catch{}})}return c},"wrapped");return r.__lensmcp=!0,r}l(wrapSend,"wrapSend"),u(wrapSend,"wrapSend");function wrapSenders(e){typeof e.send=="function"&&(e.send=wrapSend(e.send,!1)),typeof e.sendBatch=="function"&&(e.sendBatch=wrapSend(e.sendBatch,!0))}l(wrapSenders,"wrapSenders"),u(wrapSenders,"wrapSenders");function tapProducer(e){if(!e||typeof e!="object")return;const t=e;wrapSenders(t);const r=t.transaction;if(typeof r=="function"&&!r.__lensmcp){const s=u(function(...n){const a=r.apply(this,n);return a&&typeof a.then=="function"?a.then(o=>{try{o&&typeof o=="object"&&wrapSenders(o)}catch{}return o}):a},"wrapped");s.__lensmcp=!0,t.transaction=s}}l(tapProducer,"tapProducer"),u(tapProducer,"tapProducer");function legOf(e,t,r){if(t){const n=t.leg?.startsWith("job:")?t.leg:`job:${e}#${r}`,a=n.indexOf("#");return{flowId:t.flowId,legId:n,jobId:a>=0?n.slice(a+1):r,own:!1}}if(!(0,headless_flow_1.headlessFlowsEnabled)())return;const s=(0,headless_flow_1.headlessJobFlowId)(e,r);return{flowId:s,legId:s,jobId:r,own:!0}}l(legOf,"legOf"),u(legOf,"legOf");async function consume(e,t,r,s,n,a){const o=(0,active_work_1.beginActiveWork)(e.gen),i=Date.now(),f={queue:t,broker:"kafka",...e.group?{group:e.group,job:e.group}:{},...s},c=r?{flowId:r.flowId,requestId:r.legId}:void 0;try{if(r?.own&&c){const p=`job:${t}/${e.group??"consumer"}`;(0,emit_1.lensEmit)("queue","info",`${n} \xB7 ${t}`,{...f,kind:"flow-origin",jobId:r.jobId,originNodeId:p},`queue-origin:${t}`,{...c,originType:"job",originNodeId:p})}const d=u(async()=>a(),"run");try{const p=await(c?(0,flow_context_1.runInFlowContext)(c,d):d());return(0,emit_1.lensEmit)("queue","info",`process ${n} \xB7 ${t} (${Date.now()-i}ms)`,{...f,kind:"queue-process",...r?{jobId:r.jobId}:{},startedAt:i,durationMs:Date.now()-i,status:"ok"},`queue:kafka:${t}`,c),p}catch(p){const y=String(p?.message??p);throw(0,emit_1.lensEmit)("queue","error",`process ${n} \xB7 ${t} failed (${Date.now()-i}ms)`,{...f,kind:"queue-process",...r?{jobId:r.jobId}:{},startedAt:i,durationMs:Date.now()-i,status:"error",error:y},`queue:kafka:error:${t}`,c),(0,emit_1.lensEmit)("queue","error",`${n} on ${t} failed: ${y}`,{...f,kind:"queue-failed",...r?{jobId:r.jobId}:{},error:y},`queue:kafka:failed:${t}`,c),p}}finally{o()}}l(consume,"consume"),u(consume,"consume");function wrapEachMessage(e,t){return function(r,...s){let n,a,o;try{n=String(r?.topic??"topic");const i=r?.message,f=`${r?.partition??"?"}:${i?.offset??"?"}`;a=legOf(n,kafkaStamp(i?.headers),f),o={partition:r?.partition,offset:i?.offset,keyed:i?.key!==void 0&&i?.key!==null,bytes:sizeOf(i?.value)}}catch{return t.call(this,r,...s)}return consume(e,n,a,o,`message ${o.partition}:${o.offset}`,()=>t.call(this,r,...s))}}l(wrapEachMessage,"wrapEachMessage"),u(wrapEachMessage,"wrapEachMessage");function wrapEachBatch(e,t){return function(r,...s){let n,a,o;try{const i=r?.batch;n=String(i?.topic??"topic");const f=Array.isArray(i?.messages)?i.messages:[],c=f[0]?.offset,d=f[f.length-1]?.offset,p=f.map(A=>kafkaStamp(A?.headers)).filter(A=>!!A),y=new Set(p.map(A=>A.flowId)).size;a=legOf(n,p[0],`${i?.partition??"?"}:${c??"?"}`);let E=0,_=0;for(const A of f)E+=sizeOf(A?.value),A?.key!==void 0&&A?.key!==null&&(_+=1);o={partition:i?.partition,messages:f.length,...c!==void 0?{firstOffset:c,lastOffset:d}:{},keyed:_,bytes:E,...y>1?{flows:y}:{}}}catch{return t.call(this,r,...s)}return consume(e,n,a,o,`batch of ${o.messages} @${o.partition}`,()=>t.call(this,r,...s))}}l(wrapEachBatch,"wrapEachBatch"),u(wrapEachBatch,"wrapEachBatch");function tapConsumer(e,t){if(!e||typeof e!="object")return;const r=e,s=r.run;if(typeof s!="function"||s.__lensmcp)return;const n=u(function(...a){try{const o=a[0];if(o&&typeof o=="object"){const i={...o};typeof o.eachMessage=="function"?i.eachMessage=wrapEachMessage(t,o.eachMessage):typeof o.eachBatch=="function"&&(i.eachBatch=wrapEachBatch(t,o.eachBatch)),a[0]=i}}catch{}return s.apply(this,a)},"wrapped");n.__lensmcp=!0,r.run=n}l(tapConsumer,"tapConsumer"),u(tapConsumer,"tapConsumer");function kafkaTap(e){const t=e?.Kafka?.prototype;if(!t||typeof t.producer!="function"||typeof t.consumer!="function")return!1;const r=t.producer;if(!r.__lensmcp){const n=u(function(...a){const o=r.apply(this,a);try{tapProducer(o)}catch{}return o},"wrapped");n.__lensmcp=!0,t.producer=n}const s=t.consumer;if(!s.__lensmcp){const n=u(function(...a){const o=s.apply(this,a);try{const i=a[0]?.groupId;tapConsumer(o,{...typeof i=="string"&&i?{group:i}:{},gen:(0,active_work_1.activeWorkGeneration)()})}catch{}return o},"wrapped");n.__lensmcp=!0,t.consumer=n}return!0}l(kafkaTap,"kafkaTap"),u(kafkaTap,"kafkaTap");
@@ -11,6 +11,7 @@ export interface LensGcMark {
11
11
  at?: number;
12
12
  trigger?: string;
13
13
  gcMs?: number;
14
+ deferredMs?: number;
14
15
  }
15
16
  /** Measures callback execution, not the time a promise/request spent awaiting I/O. No per-callback stack capture. */
16
17
  export declare function tapLoopCallbacks(minMs?: number): () => void;
@@ -1 +1 @@
1
- "use strict";var M=Object.defineProperty;var i=(l,t)=>M(l,"name",{value:t,configurable:!0});var h=Object.defineProperty,u=i((l,t)=>h(l,"name",{value:t,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_GC_MARK=void 0,exports.tapLoopCallbacks=tapLoopCallbacks;const node_async_hooks_1=require("node:async_hooks"),node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),lens_time_1=require("./lens-time"),loop_identity_1=require("./loop-identity");exports.LENS_GC_MARK=Symbol.for("lensmcp.lensGc");function lensGcWithin(l,t){const n=globalThis[exports.LENS_GC_MARK];if(!n||typeof n.startedAt!="number")return;const r=typeof n.endedAt=="number"?n.endedAt:t;return n.startedAt<=t&&r>=l?n:void 0}i(lensGcWithin,"lensGcWithin"),u(lensGcWithin,"lensGcWithin");function tapLoopCallbacks(l=50){const t=new Map,n=new Map;let r=!1,f=!1,d=!1,c=0;const a=[],g=(0,node_async_hooks_1.createHook)({init(o,s){r||(t.set(o,s),t.size>2e4&&t.delete(t.keys().next().value))},before(o){if(!(r||!t.has(o)))try{n.set(o,{start:node_perf_hooks_1.performance.now(),at:Date.now(),type:t.get(o)??"unknown",lens:(0,lens_time_1.lensSelfMs)()})}catch{}},after(o){const s=n.get(o);if(n.delete(o),!s||r)return;const _=node_perf_hooks_1.performance.now(),p=_-s.start;if(p<l)return;if(a.length>=50){c++;return}const m=(0,lens_time_1.lensSelfMs)()-s.lens,y=lensGcWithin(s.start,_);y?a.push({...s,duration:p,lensMs:m,id:o,gc:{...y}}):a.push({...s,duration:p,lensMs:m,id:o,context:(0,flow_context_1.flowContext)()}),!d&&(d=!0,r=!0,setImmediate(()=>{if(d=!1,!f){r=!0;try{for(const e of a.splice(0)){const b=e.duration.toFixed(1);(0,emit_1.lensEmit)("perf",e.gc?"info":e.duration>=1e3?"error":"warning",e.gc?`Event loop paused ${b}ms by the lens's own full GC${e.gc.trigger?` (${e.gc.trigger})`:""} \u2014 not the app's`:`Event loop callback blocked for ${b}ms (${e.type})`,{kind:"event-loop-stall",incidentId:`${loop_identity_1.NODE_LOOP.id}:callback:${e.id}:${e.start}`,loop:loop_identity_1.NODE_LOOP,startedAt:e.at,durationMs:Math.round(e.duration*100)/100,state:"recovered",mechanism:"callback",callbackType:e.type,...e.lensMs>=.05?{lensMs:Math.round(e.lensMs*100)/100}:{},...e.gc?{cause:"lensmcp-gc",...e.gc.trigger?{trigger:e.gc.trigger}:{},...typeof e.gc.gcMs=="number"?{gcMs:e.gc.gcMs}:{}}:{},...c?{droppedIncidents:c}:{}},"perf:event-loop-stall",e.context,"performance")}c=0}finally{r=!1}}}),r=!1)},destroy(o){t.delete(o),n.delete(o)}});return g.enable(),()=>{f=!0,g.disable(),t.clear(),n.clear(),a.length=0}}i(tapLoopCallbacks,"tapLoopCallbacks"),u(tapLoopCallbacks,"tapLoopCallbacks");
1
+ "use strict";var x=Object.defineProperty;var g=(i,r)=>x(i,"name",{value:r,configurable:!0});var b=Object.defineProperty,h=g((i,r)=>b(i,"name",{value:r,configurable:!0}),"h");Object.defineProperty(exports,"__esModule",{value:!0}),exports.LENS_GC_MARK=void 0,exports.tapLoopCallbacks=tapLoopCallbacks;const node_async_hooks_1=require("node:async_hooks"),node_perf_hooks_1=require("node:perf_hooks"),emit_1=require("./emit"),flow_context_1=require("./flow-context"),lens_time_1=require("./lens-time"),loop_identity_1=require("./loop-identity");exports.LENS_GC_MARK=Symbol.for("lensmcp.lensGc");function lensGcWithin(i,r){const t=globalThis[exports.LENS_GC_MARK];if(!t||typeof t.startedAt!="number")return;const s=typeof t.endedAt=="number"?t.endedAt:r;return t.startedAt<=r&&s>=i?t:void 0}g(lensGcWithin,"lensGcWithin"),h(lensGcWithin,"lensGcWithin");const LENS_WORK={write:"writing events",cleanup:"cleanup",capture:"capturing values"};function tapLoopCallbacks(i=50){const r=new Map,t=[];let s=!1,m=!1,w=!1,d=0;const p=[],y=(0,node_async_hooks_1.createHook)({init(l,o){s||(r.set(l,o),r.size>2e4&&r.delete(r.keys().next().value))},before(l){if(!(s||!r.has(l)))try{const o=node_perf_hooks_1.performance.now();t.length&&(t.length>64||o-t[0].start>3e5)&&(t.length=0);const n=(0,lens_time_1.lensSelfBy)();t.push({id:l,start:o,at:Date.now(),type:r.get(l)??"unknown",lens:(0,lens_time_1.lensSelfMs)(),write:n.write??0,cleanup:n.cleanup??0,capture:n.capture??0})}catch{}},after(l){let o=t.length-1;for(;o>=0&&t[o].id!==l;)o--;if(o<0)return;const n=t[o];if(t.length=o,s)return;const k=node_perf_hooks_1.performance.now(),c=k-n.start;if(c<i)return;const _=t[o-1];if(_){const e=(0,flow_context_1.flowContext)();e?.flowId&&c>(_.inner?.duration??0)&&(_.inner={duration:c,context:e});return}if(p.length>=50){d++;return}const f=(0,lens_time_1.lensSelfMs)()-n.lens,M=lensGcWithin(n.start,k);if(M)p.push({...n,duration:c,lensMs:f,gc:{...M}});else if(f>=c/2){const e=(0,lens_time_1.lensSelfBy)(),a=[["write",(e.write??0)-n.write],["cleanup",(e.cleanup??0)-n.cleanup],["capture",(e.capture??0)-n.capture]];p.push({...n,duration:c,lensMs:f,work:a.reduce((u,v)=>v[1]>u[1]?v:u)[0]})}else{const e=(0,flow_context_1.flowContext)(),a=e?.flowId||!n.inner||n.inner.duration<c/2?e:n.inner.context;p.push({...n,duration:c,lensMs:f,...a?{context:a}:{}})}w||(w=!0,s=!0,setImmediate(()=>{if(w=!1,!m){s=!0;try{for(const e of p.splice(0)){const a=e.duration.toFixed(1),u=e.gc?"lensmcp-gc":e.work?`lensmcp-${e.work}`:void 0;(0,emit_1.lensEmit)("perf",u?"info":e.duration>=1e3?"error":"warning",e.gc?`Event loop paused ${a}ms by the lens's own full GC${e.gc.trigger?` (${e.gc.trigger})`:""} \u2014 not the app's`:e.work?`Event loop paused ${a}ms by LensMCP's own work (${LENS_WORK[e.work]}) \u2014 not the app's`:`Event loop callback blocked for ${a}ms (${e.type})`,{kind:"event-loop-stall",incidentId:`${loop_identity_1.NODE_LOOP.id}:callback:${e.id}:${e.start}`,loop:loop_identity_1.NODE_LOOP,startedAt:e.at,durationMs:Math.round(e.duration*100)/100,state:"recovered",mechanism:"callback",callbackType:e.type,...e.lensMs>=.05?{lensMs:Math.round(e.lensMs*100)/100}:{},...u?{cause:u}:{},...e.gc?{...e.gc.trigger?{trigger:e.gc.trigger}:{},...typeof e.gc.gcMs=="number"?{gcMs:e.gc.gcMs}:{},...typeof e.gc.deferredMs=="number"&&e.gc.deferredMs>0?{deferredMs:e.gc.deferredMs}:{}}:{},...d?{droppedIncidents:d}:{}},"perf:event-loop-stall",e.context,"performance")}d=0}finally{s=!1}}}),s=!1)},destroy(l){r.delete(l)}});return y.enable(),()=>{m=!0,y.disable(),r.clear(),t.length=0,p.length=0}}g(tapLoopCallbacks,"tapLoopCallbacks"),h(tapLoopCallbacks,"tapLoopCallbacks");
@@ -0,0 +1,5 @@
1
+ /** `?`/`??` → `$n`, backticks → double quotes, literals → `''`, `#` → `--`: the spelling sqlShape and the column map read. */
2
+ export declare function mysqlShapeText(sql: string): string;
3
+ export declare function mysqlTap(exportsObject: unknown): boolean;
4
+ /** Taps the callback API behind it: the sibling `mysql2` module, else lazily from the first promise connection or pool. */
5
+ export declare function mysqlPromiseTap(exportsObject: unknown): boolean;
@@ -0,0 +1,2 @@
1
+ "use strict";var m=Object.defineProperty;var l=(t,o)=>m(t,"name",{value:o,configurable:!0});var y=Object.defineProperty,u=l((t,o)=>y(t,"name",{value:o,configurable:!0}),"u");Object.defineProperty(exports,"__esModule",{value:!0}),exports.mysqlShapeText=mysqlShapeText,exports.mysqlTap=mysqlTap,exports.mysqlPromiseTap=mysqlPromiseTap;const node_async_hooks_1=require("node:async_hooks"),redact_1=require("@lensmcp/core/redact"),callsite_1=require("./callsite"),sql_run_1=require("./sql-run"),recordRun=(0,sql_run_1.createSqlRunRecorder)({name:"mysql",bucketPrefix:"mysql:",fields:{driver:"mysql2"}}),MYSQL_SKIP_OPS=new Set(["USE","XA","LOCK","UNLOCK"]);function mysqlShapeText(t){let o="",c=0;const r=t.length;for(let n=0;n<r;n++){const s=t.charAt(n);if(s==="'"||s==='"'){let e=n+1;for(;e<r;){if(t[e]==="\\"){e+=2;continue}if(t[e]===s){if(t[e+1]===s){e+=2;continue}break}e++}o+="''",n=e}else if(s==="`"){let e=n+1,i="";for(;e<r;){if(t[e]==="`"){if(t[e+1]==="`"){i+="`",e+=2;continue}break}i+=t[e],e++}o+=`"${i.replace(/"/g,'""')}"`,n=e}else if(s==="#"||s==="-"&&t[n+1]==="-"){const e=t.indexOf(`
2
+ `,n),i=e<0?r:e;o+=`--${t.slice(s==="#"?n+1:n+2,i)}`,n=i-1}else if(s==="/"&&t[n+1]==="*"){const e=t.indexOf("*/",n+2),i=e<0?r:e+2;o+=t.slice(n,i),n=i-1}else s==="?"?(t[n+1]==="?"&&n++,o+=`$${++c}`):o+=s}return o}l(mysqlShapeText,"mysqlShapeText"),u(mysqlShapeText,"mysqlShapeText");function whereOf(t){const o=t?.config,c=typeof o?.database=="string"&&o.database?o.database:void 0,r=typeof o?.socketPath=="string"&&o.socketPath?o.socketPath:`${typeof o?.host=="string"&&o.host?o.host:"localhost"}:${typeof o?.port=="number"||typeof o?.port=="string"?o.port:3306}`;return{...c?{database:c}:{},server:r}}l(whereOf,"whereOf"),u(whereOf,"whereOf");const isPlainObject=u(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&!(t instanceof Date)&&!(t instanceof Uint8Array),"isPlainObject");function statementOf(t,o,c,r){let n=o,s;if(isPlainObject(c)&&(r??t.config?.namedPlaceholders)&&typeof t._resolveNamedPlaceholders=="function")try{const e={sql:o,values:c,namedPlaceholders:r??t.config?.namedPlaceholders};t._resolveNamedPlaceholders.call(t,e),n=e.sql,s=Array.isArray(e.values)?e.values:void 0}catch{s=void 0}else Array.isArray(c)?s=c:c!=null&&typeof c!="function"&&(s=[c]);return{text:o,shapeText:mysqlShapeText(n),...s?.length?{values:s.map(e=>isPlainObject(e)?(0,redact_1.redactDeep)(e):e)}:{}}}l(statementOf,"statementOf"),u(statementOf,"statementOf");const isHeader=u(t=>!!t&&typeof t=="object"&&!Array.isArray(t)&&typeof t.affectedRows=="number","isHeader");function resultOf(t){return isHeader(t)?{rows:t.affectedRows,extra:{affectedRows:t.affectedRows}}:Array.isArray(t)?{rows:t.length,returned:t}:{rows:0}}l(resultOf,"resultOf"),u(resultOf,"resultOf");const checkoutSites=new node_async_hooks_1.AsyncLocalStorage;function begin(t,o,c,r){if(typeof o!="string"||!o)return;const n=statementOf(t,o,c,r);if(!MYSQL_SKIP_OPS.has((0,sql_run_1.firstWord)(n.shapeText)))return recordRun({...n,where:whereOf(t),...checkoutSites.getStore()?{checkout:checkoutSites.getStore()}:{}})}l(begin,"begin"),u(begin,"begin");function reporting(t,o){return node_async_hooks_1.AsyncResource.bind(function(c,r,n){return t.done(c,c?void 0:resultOf(r)),o.call(this,c,r,n)})}l(reporting,"reporting"),u(reporting,"reporting");const STREAM_ROWS_KEPT=50;function watchEvents(t,o){const c=o,r=c?.emit;if(!c||typeof r!="function"){t.abandon();return}const n=[];let s=0,e;c.emit=function(i,...f){try{if(i==="result"){const a=f[0];isHeader(a)?e=(e??0)+a.affectedRows:++s<=STREAM_ROWS_KEPT&&n.push(a)}else i==="error"?t.done(f[0]):i==="end"&&t.done(void 0,e!==void 0&&!s?{rows:e,extra:{affectedRows:e}}:{rows:s,returned:n})}catch{}return r.call(this,i,...f)}}l(watchEvents,"watchEvents"),u(watchEvents,"watchEvents");function tapQuery(t){const o=t.query;if(typeof o!="function"||o.__lensmcp)return;const c=u(function(r,n,s){let e;const i=!!r&&typeof r=="object"&&(r.constructor?.name==="Query"||typeof r.on=="function");try{if(i){const a=r;e=begin(this,a.sql,a.values,a.namedPlaceholders),e&&typeof a.onResult=="function"&&(a.onResult=reporting(e,a.onResult))}else{const a=r&&typeof r=="object"?r:void 0,p=a?a.sql:r,d=n===void 0||typeof n=="function"?void 0:n,h=a?d??a.values:d;e=begin(this,p,h,a?.namedPlaceholders),e&&typeof n=="function"?n=reporting(e,n):e&&typeof s=="function"&&(s=reporting(e,s))}}catch{e=void 0}let f;try{f=o.call(this,r,n,s)}catch(a){throw e?.abandon(),a}if(e&&!(i?typeof r.onResult=="function":typeof n=="function"||typeof s=="function"))try{watchEvents(e,f)}catch{e.abandon()}return f},"wrapped");c.__lensmcp=!0,t.query=c}l(tapQuery,"tapQuery"),u(tapQuery,"tapQuery");function tapExecute(t){const o=t.execute;if(typeof o!="function"||o.__lensmcp)return;const c=u(function(r,n,s){let e;try{const f=r&&typeof r=="object"?r:void 0,a=f?f.sql:r,p=typeof n=="function"?f?.values:f?.values??n;e=begin(this,a,p,f?.namedPlaceholders),e&&typeof n=="function"?n=reporting(e,n):e&&typeof s=="function"&&(s=reporting(e,s))}catch{e=void 0}let i;try{i=o.call(this,r,n,s)}catch(f){throw e?.abandon(),f}if(e&&typeof n!="function"&&typeof s!="function")try{watchEvents(e,i)}catch{e.abandon()}return i},"wrapped");c.__lensmcp=!0,t.execute=c}l(tapExecute,"tapExecute"),u(tapExecute,"tapExecute");function tapStatement(t){const o=t&&typeof t=="object"?Object.getPrototypeOf(t):null,c=o?.execute;if(!o||typeof c!="function"||c.__lensmcp)return;const r=u(function(n,s){let e;try{const f=this._connection??{};e=begin(f,this.query,typeof n=="function"?void 0:n,void 0),e&&typeof n=="function"?n=reporting(e,n):e&&typeof s=="function"&&(s=reporting(e,s))}catch{e=void 0}let i;try{i=c.call(this,n,s)}catch(f){throw e?.abandon(),f}if(e&&typeof n!="function"&&typeof s!="function")try{watchEvents(e,i)}catch{e.abandon()}return i},"wrapped");r.__lensmcp=!0,o.execute=r}l(tapStatement,"tapStatement"),u(tapStatement,"tapStatement");function tapPrepare(t){const o=t.prepare;if(typeof o!="function"||o.__lensmcp)return;const c=u(function(r,n){if(typeof n!="function")return o.call(this,r,n);const s=n;return o.call(this,r,function(e,i){if(!e)try{tapStatement(i)}catch{}return s.call(this,e,i)})},"wrapped");c.__lensmcp=!0,t.prepare=c}l(tapPrepare,"tapPrepare"),u(tapPrepare,"tapPrepare");const BOUND=Symbol.for("lensmcp.mysqlCheckout");function tapGetConnection(t){const o=t.getConnection;if(typeof o!="function"||o.__lensmcp)return;const c=u(function(r){if(typeof r!="function"||r[BOUND])return o.call(this,r);const n=r,s=(0,callsite_1.captureSite)(),e=node_async_hooks_1.AsyncResource.bind(function(...i){if(!i[0]&&i[1])try{tapConnection(i[1].constructor)}catch{}return s?checkoutSites.run(s,()=>n.apply(this,i)):n.apply(this,i)});return Object.defineProperty(e,BOUND,{value:!0}),o.call(this,e)},"wrapped");c.__lensmcp=!0,t.getConnection=c}l(tapGetConnection,"tapGetConnection"),u(tapGetConnection,"tapGetConnection");function ownerOf(t,o){let c=t?.prototype;for(;c&&!Object.prototype.hasOwnProperty.call(c,o);)c=Object.getPrototypeOf(c);return c??void 0}l(ownerOf,"ownerOf"),u(ownerOf,"ownerOf");const tappedClasses=new WeakSet;function tapConnection(t){if(typeof t!="function")return!1;if(tappedClasses.has(t))return!0;const o=ownerOf(t,"query");if(!o)return!1;try{tapQuery(o)}catch{}try{tapExecute(ownerOf(t,"execute")??o)}catch{}try{tapPrepare(ownerOf(t,"prepare")??o)}catch{}return tappedClasses.add(t),!0}l(tapConnection,"tapConnection"),u(tapConnection,"tapConnection");function tapPool(t){if(typeof t!="function"||tappedClasses.has(t))return;const o=ownerOf(t,"getConnection");o&&tapGetConnection(o),tappedClasses.add(t)}l(tapPool,"tapPool"),u(tapPool,"tapPool");function mysqlTap(t){const o=t;if(!tapConnection(o?.Connection))return!1;try{tapPool(o?.Pool)}catch{}return!0}l(mysqlTap,"mysqlTap"),u(mysqlTap,"mysqlTap");function mysqlPromiseTap(t){const o=t;if(!o||typeof o.PromiseConnection!="function")return!1;try{for(const n of Object.values(require.cache))if(n?.exports===t&&n&&mysqlTap(n.require("./index.js")))return!0}catch{}const c=u((n,s,e)=>{const i=n?.prototype;if(i)for(const f of s){const a=i[f];if(typeof a!="function"||a.__lensmcp)continue;const p=u(function(...d){try{e(this)}catch{}return a.apply(this,d)},"wrapped");p.__lensmcp=!0,i[f]=p}},"lazily"),r=u(n=>n&&typeof n=="object"?Object.getPrototypeOf(n).constructor:void 0,"classOf");return c(o.PromiseConnection,["query","execute","prepare"],n=>tapConnection(r(n.connection))),c(o.PromisePool,["query","execute","getConnection"],n=>tapPool(r(n.pool))),!0}l(mysqlPromiseTap,"mysqlPromiseTap"),u(mysqlPromiseTap,"mysqlPromiseTap");
package/lib/tap-pg.js CHANGED
@@ -1 +1 @@
1
- "use strict";var j=Object.defineProperty;var u=(t,e)=>j(t,"name",{value:e,configurable:!0});var U=Object.defineProperty,r=u((t,e)=>U(t,"name",{value:e,configurable:!0}),"r");Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedAppName=taggedAppName,exports.pgTap=pgTap;const redact_1=require("@lensmcp/core/redact"),sql_shape_1=require("@lensmcp/core/sql-shape"),emit_1=require("./emit"),flood_guard_1=require("./flood-guard"),flow_context_1=require("./flow-context"),sql_accounting_1=require("./sql-accounting"),tap_pg_pool_1=require("./tap-pg-pool"),callsite_1=require("./callsite"),active_work_1=require("./active-work"),emit_2=require("./emit"),sql_values_1=require("./sql-values"),sql_drops_1=require("./sql-drops"),SKIP_OPS=new Set(["BEGIN","START","COMMIT","END","ROLLBACK","SAVEPOINT","RELEASE","SET","RESET","SHOW","DEALLOCATE","DISCARD","LISTEN","UNLISTEN"]),STATEMENT_EVERY_MS=10*6e4,STATEMENT_MAX=64*1024,SLOW_SITE_MS=250,sites=new callsite_1.SiteSampler,buckets=(0,flood_guard_1.createEventFloodGuard)({burst:30,perSec:5}),statementGuard={admit:r(t=>({ok:buckets.admit(t).ok,suppressed:0}),"admit")},statementSentAt=new Map,MAX_SHAPES_REMEMBERED=2e3,firstWord=r(t=>(/^\s*(?:(?:\/\*[\s\S]*?\*\/|--[^\n]*\n?)\s*)*(\w+)/.exec(t)?.[1]??"query").toUpperCase(),"firstWord");function parseSql(t){const e=(0,sql_shape_1.sqlShape)(t),n=(e.target??e.tables[0])?.split(".").pop();return{op:e.verb,...n?{table:n}:{},sqlId:e.id,tables:e.tables,...e.name?{name:e.name}:{}}}u(parseSql,"parseSql"),r(parseSql,"parseSql");const oneLine=r(t=>t.replace(/\s+/g," ").trim(),"oneLine"),clip=r((t,e)=>t.length>e?t.slice(0,e-1)+"\u2026":t,"clip");function paramPreview(t){if(!(!Array.isArray(t)||t.length===0))return t.slice(0,10).map(e=>{if(e==null)return String(e);const n=typeof e=="string"?e:(()=>{try{return JSON.stringify(e)}catch{return String(e)}})();return clip(n,80)})}u(paramPreview,"paramPreview"),r(paramPreview,"paramPreview");const rowsOf=r(t=>t?.rowCount??t?.rows?.length??0,"rowsOf");function resultPreview(t){const e=t?.rows;if(!(!Array.isArray(e)||e.length===0))try{return clip(JSON.stringify((0,redact_1.redactDeep)(e.slice(0,2))),240)}catch{return}}u(resultPreview,"resultPreview"),r(resultPreview,"resultPreview");function connectionOf(t){const e=t,n=e?.connectionParameters,a=typeof e?.database=="string"?e.database:typeof n?.database=="string"?n.database:void 0,s=typeof e?.host=="string"?e.host:typeof n?.host=="string"?n.host:void 0,i=typeof e?.port=="number"||typeof e?.port=="string"?e.port:typeof n?.port=="number"||typeof n?.port=="string"?n.port:5432;return{...a?{database:a}:{},...s?{server:`${s}:${i}`}:{}}}u(connectionOf,"connectionOf"),r(connectionOf,"connectionOf");const APP_NAME_MAX=63;function taggedAppName(t,e,n,a){const s=` lens:${e.replace(/[^\x21-\x7e]/g,"?").replace(/:/g,"_")}${n>0?`:g${n}`:""}${a?`:p${a}`:""}`.slice(0,APP_NAME_MAX);return`${(t??"node").replace(/[^\x20-\x7e]/g,"?").replace(/ lens:\S+$/,"").slice(0,Math.max(0,APP_NAME_MAX-s.length))}${s}`}u(taggedAppName,"taggedAppName"),r(taggedAppName,"taggedAppName");function tagApplicationName(t){if(process.env.LENSMCP_PG_APP_NAME==="0")return;const e=t.getStartupConf;if(typeof e!="function"||e.__lensmcp)return;const n=r(function(){const a=e.call(this);try{a&&typeof a=="object"&&emit_2.PROJECT&&(a.application_name=taggedAppName(typeof a.application_name=="string"?a.application_name:void 0,emit_2.PROJECT,(0,active_work_1.activeWorkGeneration)(),process.pid))}catch{}return a},"wrapped");n.__lensmcp=!0,t.getStartupConf=n}u(tagApplicationName,"tagApplicationName"),r(tagApplicationName,"tagApplicationName");function pgTap(t){const e=t?.Client?.prototype,n=e?.query;if(!e||typeof n!="function")return!1;try{(0,tap_pg_pool_1.pgPoolTap)(t)}catch{}try{tagApplicationName(e)}catch{}if(n.__lensmcp)return!0;const a=r(function(s,i,b){const S=s,f=typeof S=="string"?S:S?.text;if(!f||S&&typeof S=="object"&&typeof S.submit=="function")return n.call(this,s,i,b);if(SKIP_OPS.has(firstWord(f)))return n.call(this,s,i,b);const{op:G,table:p,sqlId:m,tables:N,name:h}=parseSql(f),J=connectionOf(this),g=G.toLowerCase(),v=`${g}:${p??"query"}`,l=Date.now(),M=(0,flow_context_1.flowContext)(),V=(0,callsite_1.captureSite)(),O=(0,tap_pg_pool_1.checkoutSite)(),_=(0,flow_context_1.liveFlowContext)();_&&(_.dbCallCount=(_.dbCallCount??0)+1,(0,flow_context_1.countDbSecond)(_,l));const w=(0,sql_accounting_1.beginSqlStatement)(_,M,l),T=clip(oneLine(f),500),x=Array.isArray(i)?i:s?.values,I=paramPreview(x),E=I&&(0,redact_1.redactSqlParams)(f,I),$=r((o,d)=>{const c=Date.now()-l,P=l-(statementSentAt.get(m)??-1/0)>=STATEMENT_EVERY_MS;let C;try{C=sites.site(m,V,{force:!!o||P||c>=SLOW_SITE_MS,...O?{fallback:O}:{}})}catch{}const k={sqlId:m,...N.length?{tables:N}:{},...h?{sqlName:h}:{},...J,...C?{site:C}:{},...P?{statement:clip(f.trim(),STATEMENT_MAX)}:{}},A=(0,sql_values_1.newSqlValuesId)(l),R=A?{valuesId:A}:{};let y;if(o)y=(0,emit_1.lensEmitOutcome)("db","error",`${g}${p?" "+p:""} failed (${c}ms)`,{name:"postgres",kind:"db-query",op:g,...p?{table:p}:{},...k,query:T,...E?{params:E}:{},...R,startedAt:l,error:String(o?.message??o),durationMs:c},`db:error:${v}`,M,"cluster",statementGuard);else{const D=rowsOf(d),W=resultPreview(d);y=(0,emit_1.lensEmitOutcome)("db","info",`${g} ${p??"query"} (${D} rows, ${c}ms)`,{name:"postgres",kind:"db-query",op:g,...p?{table:p}:{},...k,query:T,...E?{params:E}:{},...W?{result:W}:{},...R,startedAt:l,rows:D,durationMs:c},c>=sql_drops_1.SLOW_QUERY_MS?`db:slow:${v}`:`db:${v}`,M,"cluster",statementGuard)}y==="suppressed"&&(0,sql_drops_1.noteDroppedRun)({sqlId:m,op:g,...p?{table:p}:{},...h?{sqlName:h}:{},...statementSentAt.has(m)?{}:{query:T},durationMs:c,failed:!!o,at:l}),A&&y==="written"&&(0,sql_values_1.keepSqlValues)(A,l,f,x,o?void 0:d?.rows),P&&y==="written"&&(statementSentAt.delete(m),statementSentAt.set(m,l),statementSentAt.size>MAX_SHAPES_REMEMBERED&&statementSentAt.delete(statementSentAt.keys().next().value)),(0,sql_accounting_1.endSqlStatement)(w,{durationMs:c,failed:!!o,emitted:y})},"done"),L=typeof b=="function"?b:typeof i=="function"?i:void 0;if(L){const o=r((d,c)=>{try{$(d,c)}catch{}L(d,c)},"wrappedCb");try{return typeof i=="function"?n.call(this,s,o):n.call(this,s,i,o)}catch(d){throw(0,sql_accounting_1.abandonSqlStatement)(w),d}}let q;try{q=n.call(this,s,i)}catch(o){throw(0,sql_accounting_1.abandonSqlStatement)(w),o}return q&&typeof q.then=="function"?q.then(o=>$(void 0,o),o=>$(o,void 0)):(0,sql_accounting_1.abandonSqlStatement)(w),q},"wrapped");return a.__lensmcp=!0,e.query=a,!0}u(pgTap,"pgTap"),r(pgTap,"pgTap");
1
+ "use strict";var v=Object.defineProperty;var u=(n,t)=>v(n,"name",{value:t,configurable:!0});var b=Object.defineProperty,p=u((n,t)=>b(n,"name",{value:t,configurable:!0}),"p");Object.defineProperty(exports,"__esModule",{value:!0}),exports.taggedAppName=taggedAppName,exports.pgTap=pgTap;const tap_pg_pool_1=require("./tap-pg-pool"),active_work_1=require("./active-work"),emit_1=require("./emit"),sql_run_1=require("./sql-run"),recordRun=(0,sql_run_1.createSqlRunRecorder)({name:"postgres"}),rowsOf=p(n=>n?.rowCount??n?.rows?.length??0,"rowsOf");function connectionOf(n){const t=n,e=t?.connectionParameters,o=typeof t?.database=="string"?t.database:typeof e?.database=="string"?e.database:void 0,r=typeof t?.host=="string"?t.host:typeof e?.host=="string"?e.host:void 0,a=typeof t?.port=="number"||typeof t?.port=="string"?t.port:typeof e?.port=="number"||typeof e?.port=="string"?e.port:5432;return{...o?{database:o}:{},...r?{server:`${r}:${a}`}:{}}}u(connectionOf,"connectionOf"),p(connectionOf,"connectionOf");const APP_NAME_MAX=63;function taggedAppName(n,t,e,o){const r=` lens:${t.replace(/[^\x21-\x7e]/g,"?").replace(/:/g,"_")}${e>0?`:g${e}`:""}${o?`:p${o}`:""}`.slice(0,APP_NAME_MAX);return`${(n??"node").replace(/[^\x20-\x7e]/g,"?").replace(/ lens:\S+$/,"").slice(0,Math.max(0,APP_NAME_MAX-r.length))}${r}`}u(taggedAppName,"taggedAppName"),p(taggedAppName,"taggedAppName");function tagApplicationName(n){if(process.env.LENSMCP_PG_APP_NAME==="0")return;const t=n.getStartupConf;if(typeof t!="function"||t.__lensmcp)return;const e=p(function(){const o=t.call(this);try{o&&typeof o=="object"&&emit_1.PROJECT&&(o.application_name=taggedAppName(typeof o.application_name=="string"?o.application_name:void 0,emit_1.PROJECT,(0,active_work_1.activeWorkGeneration)(),process.pid))}catch{}return o},"wrapped");e.__lensmcp=!0,n.getStartupConf=e}u(tagApplicationName,"tagApplicationName"),p(tagApplicationName,"tagApplicationName");function pgTap(n){const t=n?.Client?.prototype,e=t?.query;if(!t||typeof e!="function")return!1;try{(0,tap_pg_pool_1.pgPoolTap)(n)}catch{}try{tagApplicationName(t)}catch{}if(e.__lensmcp)return!0;const o=p(function(r,a,y){const s=r,g=typeof s=="string"?s:s?.text;if(!g||s&&typeof s=="object"&&typeof s.submit=="function")return e.call(this,r,a,y);const m=Array.isArray(a)?a:r?.values,f=recordRun({text:g,values:m,where:connectionOf(this),checkout:(0,tap_pg_pool_1.checkoutSite)()});if(!f)return e.call(this,r,a,y);const d=p((c,i)=>f.done(c,c?void 0:{rows:rowsOf(i),returned:i?.rows}),"done"),h=typeof y=="function"?y:typeof a=="function"?a:void 0;if(h){const c=p((i,_)=>{try{d(i,_)}catch{}h(i,_)},"wrappedCb");try{return typeof a=="function"?e.call(this,r,c):e.call(this,r,a,c)}catch(i){throw f.abandon(),i}}let l;try{l=e.call(this,r,a)}catch(c){throw f.abandon(),c}return l&&typeof l.then=="function"?l.then(c=>d(void 0,c),c=>d(c,void 0)):f.abandon(),l},"wrapped");return o.__lensmcp=!0,t.query=o,!0}u(pgTap,"pgTap"),p(pgTap,"pgTap");
@@ -0,0 +1,4 @@
1
+ export declare function tappedPackages(): Set<string>;
2
+ export declare function addTappedPackages(names: Iterable<string>): void;
3
+ /** The tapped package a specifier loads — itself, or the one a subpath (`pg/lib/client.js`) belongs to; the longest wins. */
4
+ export declare function tappedPackageOf(specifier: string, names?: ReadonlySet<string>): string | undefined;
@@ -0,0 +1 @@
1
+ "use strict";var c=Object.defineProperty;var p=(e,a)=>c(e,"name",{value:a,configurable:!0});var n=Object.defineProperty,o=p((e,a)=>n(e,"name",{value:a,configurable:!0}),"o");Object.defineProperty(exports,"__esModule",{value:!0}),exports.tappedPackages=tappedPackages,exports.addTappedPackages=addTappedPackages,exports.tappedPackageOf=tappedPackageOf;const KEY=Symbol.for("lensmcp.tappedPackages");function tappedPackages(){const e=globalThis;return e[KEY]??=new Set}p(tappedPackages,"tappedPackages"),o(tappedPackages,"tappedPackages");function addTappedPackages(e){const a=tappedPackages();for(const t of e)a.add(t)}p(addTappedPackages,"addTappedPackages"),o(addTappedPackages,"addTappedPackages");function tappedPackageOf(e,a=tappedPackages()){if(a.has(e))return e;let t;for(const s of a)e.startsWith(s+"/")&&(!t||s.length>t.length)&&(t=s);return t}p(tappedPackageOf,"tappedPackageOf"),o(tappedPackageOf,"tappedPackageOf");
package/loader.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=loader.d.mts.map
package/loader.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";import{createRequire as r}from"node:module";const e=r(import.meta.url);if(e("./register.js"),process.env.LENSMCP_AUTO!=="0"){e("./lib/lens-peers.js").installPeerRedirectOffThread();const s=e("./lib/esm-taps.js").installEsmTaps();s||process.stderr.write(`[lensmcp] Node ${process.version} has no module hooks: an ESM import of pg, ioredis, Nest\u2026 is not seen, nor a store install's Nest (Node 20.19+ / 22.15+ sees both)
2
+ `);const t=e("./lib/flow-context.js");if(s==="off-thread"&&t.flowContextStatus().state!=="ready"){const o="@lensmcp/nest-instrumentation";try{await import(o),t.primeFlowContext()}catch{}}}
package/loader.mjs ADDED
@@ -0,0 +1,23 @@
1
+ // `node --import <this>`: the require taps, plus the ESM hooks that route an `import` of a tapped package through them.
2
+ import { createRequire } from 'node:module';
3
+ const load = createRequire(import.meta.url);
4
+ load('./register.js');
5
+ if (process.env['LENSMCP_AUTO'] !== '0') {
6
+ load('./lib/lens-peers.js').installPeerRedirectOffThread();
7
+ const mode = load('./lib/esm-taps.js').installEsmTaps();
8
+ if (!mode) {
9
+ process.stderr.write(`[lensmcp] Node ${process.version} has no module hooks: an ESM import of pg, ioredis, Nest… is not seen, nor a store install's Nest (Node 20.19+ / 22.15+ sees both)\n`);
10
+ }
11
+ const flow = load('./lib/flow-context.js');
12
+ if (mode === 'off-thread' && flow.flowContextStatus().state !== 'ready') {
13
+ // Off-thread hooks miss a `require` of the ESM Nest instrumentation, so its peers did not resolve from the app: import it through them.
14
+ const nest = '@lensmcp/nest-instrumentation';
15
+ try {
16
+ await import(nest);
17
+ flow.primeFlowContext();
18
+ }
19
+ catch {
20
+ /* no Nest in the app: flow correlation stays off, as under CommonJS */
21
+ }
22
+ }
23
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lensmcp/node-instrumentation",
3
- "version": "1.25.79",
3
+ "version": "1.26.1",
4
4
  "main": "./index.js",
5
5
  "types": "./index.d.ts",
6
6
  "exports": {
@@ -12,12 +12,16 @@
12
12
  "./register": {
13
13
  "types": "./register.d.ts",
14
14
  "default": "./register.js"
15
+ },
16
+ "./loader": {
17
+ "types": "./loader.d.mts",
18
+ "default": "./loader.mjs"
15
19
  }
16
20
  },
17
21
  "dependencies": {
18
- "@lensmcp/core": "1.25.79",
19
- "@lensmcp/nest-instrumentation": "1.25.79",
20
- "@lensmcp/protocol-types": "1.25.79",
22
+ "@lensmcp/core": "1.26.1",
23
+ "@lensmcp/nest-instrumentation": "1.26.1",
24
+ "@lensmcp/protocol-types": "1.26.1",
21
25
  "tslib": "^2.3.0"
22
26
  },
23
27
  "optionalDependencies": {