@jini-ai/diagnostics 0.1.2 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +97 -0
  2. package/README.md +114 -0
  3. package/dist/agent-logs.d.ts +9 -4
  4. package/dist/agent-logs.js +14 -15
  5. package/dist/domain-dns/index.d.ts +136 -0
  6. package/dist/domain-dns/index.js +117 -0
  7. package/dist/index.d.ts +41 -3
  8. package/dist/index.js +38 -1
  9. package/dist/manifest.d.ts +22 -16
  10. package/dist/manifest.js +9 -19
  11. package/dist/node-ports.d.ts +6 -0
  12. package/dist/node-ports.js +57 -0
  13. package/dist/observability/config.d.ts +24 -0
  14. package/dist/observability/config.js +21 -0
  15. package/dist/observability/hooks.d.ts +19 -0
  16. package/dist/observability/hooks.js +32 -0
  17. package/dist/observability/index.d.ts +17 -0
  18. package/dist/observability/index.js +16 -0
  19. package/dist/observability/instrumentation.d.ts +61 -0
  20. package/dist/observability/instrumentation.js +139 -0
  21. package/dist/observability/node.d.ts +12 -0
  22. package/dist/observability/node.js +15 -0
  23. package/dist/observability/noop.d.ts +7 -0
  24. package/dist/observability/noop.js +22 -0
  25. package/dist/observability/otel.d.ts +28 -0
  26. package/dist/observability/otel.js +120 -0
  27. package/dist/observability/ports.d.ts +150 -0
  28. package/dist/observability/ports.js +2 -0
  29. package/dist/ports.d.ts +45 -0
  30. package/dist/ports.js +2 -0
  31. package/dist/redaction/secrets-only.d.ts +44 -0
  32. package/dist/redaction/secrets-only.js +179 -0
  33. package/dist/redaction.d.ts +12 -3
  34. package/dist/redaction.js +18 -8
  35. package/dist/sources.d.ts +22 -12
  36. package/dist/sources.js +22 -42
  37. package/dist/types.d.ts +24 -0
  38. package/dist/types.js +2 -0
  39. package/dist/web-evidence/browser-port.d.ts +166 -0
  40. package/dist/web-evidence/browser-port.js +6 -0
  41. package/dist/web-evidence/collect-page-evidence.d.ts +160 -0
  42. package/dist/web-evidence/collect-page-evidence.js +215 -0
  43. package/dist/web-evidence/index.d.ts +5 -0
  44. package/dist/web-evidence/index.js +5 -0
  45. package/dist/web-evidence/page-structure-script.d.ts +53 -0
  46. package/dist/web-evidence/page-structure-script.js +338 -0
  47. package/dist/web-evidence/page-work-budget.d.ts +27 -0
  48. package/dist/web-evidence/page-work-budget.js +53 -0
  49. package/dist/web-evidence/playwright-browser.d.ts +131 -0
  50. package/dist/web-evidence/playwright-browser.js +349 -0
  51. package/dist/web-evidence/same-origin.d.ts +126 -0
  52. package/dist/web-evidence/same-origin.js +141 -0
  53. package/dist/zip.d.ts +8 -3
  54. package/dist/zip.js +23 -16
  55. package/package.json +50 -5
  56. package/dist/agent-logs.d.ts.map +0 -1
  57. package/dist/agent-logs.js.map +0 -1
  58. package/dist/contract.d.ts.map +0 -1
  59. package/dist/contract.js.map +0 -1
  60. package/dist/index.d.ts.map +0 -1
  61. package/dist/index.js.map +0 -1
  62. package/dist/manifest.d.ts.map +0 -1
  63. package/dist/manifest.js.map +0 -1
  64. package/dist/redaction.d.ts.map +0 -1
  65. package/dist/redaction.js.map +0 -1
  66. package/dist/sources.d.ts.map +0 -1
  67. package/dist/sources.js.map +0 -1
  68. package/dist/zip.d.ts.map +0 -1
  69. package/dist/zip.js.map +0 -1
package/dist/index.js CHANGED
@@ -4,9 +4,45 @@
4
4
  * Diagnostics-bundle tooling shared by any host application's HTTP and desktop
5
5
  * export surfaces: endpoint constants, JSON/text secret redaction, log-source
6
6
  * collection (incl. macOS crash reports and coding-agent CLI logs), a manifest
7
- * builder, and a zip packager. See `source-map.md` for full provenance and
7
+ * builder, and a zip packager. See `archived provenance ledger` for full provenance and
8
8
  * scope-decision notes (this package is NOT yet in extraction-plan.md's
9
9
  * locked §3 package set — see that file for details).
10
+
11
+ * Archived provenance rationale:
12
+ * ## Design decision: `agent-logs.ts` carries real agent-CLI vocabulary, ported anyway
13
+ *
14
+ * `r2-packages.md`'s coupling grade for this package ("LOW... daemon-endpoint
15
+ * comments") was assessed at the whole-package level. Read in isolation,
16
+ * `agent-logs.ts` carries more domain content than the other six files: it
17
+ * hardcodes knowledge of four specific coding-agent CLIs — Claude Code, Codex,
18
+ * OpenCode, and an "AMR"-style OpenCode runtime — including their default
19
+ * config-home directory names (`.claude`, `.codex`, `opencode`) and env-var
20
+ * override names (`CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `OPENCODE_TEST_HOME`,
21
+ * `XDG_DATA_HOME`). "AMR" itself is OD's own internal name for an agent
22
+ * orchestration layer, not a generic term.
23
+ *
24
+ * This was ported anyway, deliberately, not dropped or trimmed, for three
25
+ * reasons: (1) the task brief explicitly lists `agent-logs` as one of the
26
+ * seven modules that make up "diagnostics-bundle tooling" and does not flag it
27
+ * for exclusion the way Target 2's task brief explicitly excluded
28
+ * `project-storage.ts`; (2) every one of these CLI integrations is optional
29
+ * and caller-parameterized (`homeDir`/`claudeConfigDir`/`codexHome`/
30
+ * `amrOpenCodeHome`/`xdgDataHome` are all inputs, not hardcoded paths the
31
+ * function reaches for on its own) — a Jini-based product that drives the same
32
+ * external agent CLIs (Claude Code, Codex, OpenCode are all plausible
33
+ * `@jini/agent-runtime` targets per extraction-plan.md's roadmap) can reuse
34
+ * this verbatim, and one that doesn't simply never calls
35
+ * `buildAgentCliLogSources`; (3) the "AMR" agent slot is additive-only (only
36
+ * appended to `agentDirs` when `amrOpenCodeHome`/`dataDir` is supplied) so a
37
+ * non-OD consumer never sees it activate. Flagged here explicitly rather than
38
+ * silently ported, per this porting session's own standard: a future
39
+ * Coordinator/Software-Architect review of this not-yet-locked package should
40
+ * weigh whether the Claude/Codex/OpenCode/AMR-specific vocabulary belongs in a
41
+ * neutral diagnostics package or should be generalized further (e.g. a
42
+ * caller-supplied list of `{agent, dir}` pairs instead of the four names being
43
+ * baked into the function body). Not resolved here — this is exactly the kind
44
+ * of judgment call flagged for sign-off, not a decision this task should make
45
+ * unilaterally.
10
46
  */
11
47
  export { DIAGNOSTICS_CONTENT_TYPE, DIAGNOSTICS_EXPORT_PATH, DIAGNOSTICS_FILENAME_PREFIX, } from "./contract.js";
12
48
  export { redactJsonValue, redactJsonText, redactText, } from "./redaction.js";
@@ -14,4 +50,5 @@ export { collectLogSource, collectLogSources, findMacOSCrashReports, } from "./s
14
50
  export { buildManifest, buildMachineInfo, diagnosticsFileName, } from "./manifest.js";
15
51
  export { buildDiagnosticsZip, } from "./zip.js";
16
52
  export { buildRunEventLogSources, buildAgentCliLogSources, } from "./agent-logs.js";
53
+ export { createNodeDiagnosticsPorts } from "./node-ports.js";
17
54
  //# sourceMappingURL=index.js.map
@@ -1,4 +1,7 @@
1
- import type { CollectedFile } from "./sources.js";
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { DiagnosticsSystemPort } from "./ports.js";
3
+ import type { CollectedFile, MachineInfo } from "./types.js";
4
+ export type { MachineInfo } from "./types.js";
2
5
  export interface DiagnosticsAppInfo {
3
6
  name: string;
4
7
  version?: string | undefined;
@@ -41,20 +44,23 @@ export interface DiagnosticsManifest {
41
44
  warnings: string[];
42
45
  extra?: Record<string, unknown> | undefined;
43
46
  }
44
- export interface MachineInfo {
45
- hostname: string;
46
- platform: string;
47
- release: string;
48
- arch: string;
49
- type: string;
50
- totalMemoryBytes: number;
51
- nodeVersion: string;
52
- pid: number;
53
- ppid: number;
54
- cwd: string;
47
+ /** Combines file and host warnings using only the caller's clock for the export timestamp. */
48
+ export declare function buildManifest({ context, files, clock }: {
49
+ context: DiagnosticsContext;
50
+ files: CollectedFile[];
51
+ clock: Clock;
52
+ }): DiagnosticsManifest;
53
+ /** Reads the injected machine snapshot and adds the caller's optional username. */
54
+ export declare function buildMachineInfo({ system }: {
55
+ system: DiagnosticsSystemPort;
56
+ }, { username }?: {
55
57
  username?: string | undefined;
56
- }
57
- export declare function buildManifest(context: DiagnosticsContext, files: CollectedFile[]): DiagnosticsManifest;
58
- export declare function buildMachineInfo(username: string | undefined): MachineInfo;
59
- export declare function diagnosticsFileName(prefix: string, now?: Date): string;
58
+ }): MachineInfo;
59
+ /** Uses an explicit date override or the supplied clock; never reads the ambient clock. */
60
+ export declare function diagnosticsFileName({ prefix, clock }: {
61
+ prefix: string;
62
+ clock: Clock;
63
+ }, { now }?: {
64
+ now?: Date;
65
+ }): string;
60
66
  //# sourceMappingURL=manifest.d.ts.map
package/dist/manifest.js CHANGED
@@ -1,12 +1,12 @@
1
- import { arch, hostname, platform, release, totalmem, type } from "node:os";
2
- export function buildManifest(context, files) {
1
+ /** Combines file and host warnings using only the caller's clock for the export timestamp. */
2
+ export function buildManifest({ context, files, clock }) {
3
3
  const warnings = [...(context.warnings ?? [])];
4
4
  for (const file of files) {
5
5
  if (file.error)
6
6
  warnings.push(`${file.name}: ${file.error}`);
7
7
  }
8
8
  return {
9
- exportedAt: new Date().toISOString(),
9
+ exportedAt: new Date(clock.nowMs()).toISOString(),
10
10
  app: context.app,
11
11
  source: context.source,
12
12
  namespace: context.namespace,
@@ -22,23 +22,13 @@ export function buildManifest(context, files) {
22
22
  extra: context.extra,
23
23
  };
24
24
  }
25
- export function buildMachineInfo(username) {
26
- return {
27
- hostname: hostname(),
28
- platform: platform(),
29
- release: release(),
30
- arch: arch(),
31
- type: type(),
32
- totalMemoryBytes: totalmem(),
33
- nodeVersion: process.version,
34
- pid: process.pid,
35
- ppid: process.ppid,
36
- cwd: process.cwd(),
37
- username,
38
- };
25
+ /** Reads the injected machine snapshot and adds the caller's optional username. */
26
+ export function buildMachineInfo({ system }, { username } = {}) {
27
+ return { ...system.machineInfo({}), username };
39
28
  }
40
- export function diagnosticsFileName(prefix, now = new Date()) {
41
- const iso = now.toISOString().replace(/[:.]/g, "-").replace(/-\d{3}Z$/, "Z");
29
+ /** Uses an explicit date override or the supplied clock; never reads the ambient clock. */
30
+ export function diagnosticsFileName({ prefix, clock }, { now } = {}) {
31
+ const iso = (now ?? new Date(clock.nowMs())).toISOString().replace(/[:.]/g, "-").replace(/-\d{3}Z$/, "Z");
42
32
  return `${prefix}-${iso}.zip`;
43
33
  }
44
34
  //# sourceMappingURL=manifest.js.map
@@ -0,0 +1,6 @@
1
+ import type { DiagnosticsPorts } from "./ports.js";
2
+ /** Explicit Node/JSZip adapter. Hosts opt into local filesystem and process access here.
3
+ * Tail reads retain bounded memory usage and always close the file descriptor.
4
+ */
5
+ export declare function createNodeDiagnosticsPorts(_required: Record<string, never>): DiagnosticsPorts;
6
+ //# sourceMappingURL=node-ports.d.ts.map
@@ -0,0 +1,57 @@
1
+ import { open, readFile, readdir, stat } from "node:fs/promises";
2
+ import { arch, hostname, platform, release, totalmem, type } from "node:os";
3
+ import JSZip from "jszip";
4
+ /** Explicit Node/JSZip adapter. Hosts opt into local filesystem and process access here.
5
+ * Tail reads retain bounded memory usage and always close the file descriptor.
6
+ */
7
+ export function createNodeDiagnosticsPorts(_required) {
8
+ return {
9
+ filesystem: {
10
+ async readFile({ absolutePath }, { tailBytes } = {}) {
11
+ if (tailBytes == null || tailBytes <= 0)
12
+ return await readFile(absolutePath);
13
+ const info = await stat(absolutePath);
14
+ if (info.size <= tailBytes)
15
+ return await readFile(absolutePath);
16
+ const fd = await open(absolutePath, "r");
17
+ try {
18
+ const buffer = Buffer.alloc(tailBytes);
19
+ const { bytesRead } = await fd.read(buffer, 0, tailBytes, info.size - tailBytes);
20
+ return buffer.subarray(0, bytesRead);
21
+ }
22
+ finally {
23
+ await fd.close();
24
+ }
25
+ },
26
+ async readDirectory({ absolutePath }) {
27
+ return (await readdir(absolutePath, { withFileTypes: true }))
28
+ .map((entry) => ({ name: entry.name, isDirectory: entry.isDirectory() }));
29
+ },
30
+ async stat({ absolutePath }) {
31
+ const info = await stat(absolutePath);
32
+ return { isFile: info.isFile(), mtimeMs: info.mtimeMs };
33
+ },
34
+ },
35
+ clock: { nowMs: () => Date.now() },
36
+ system: {
37
+ platform: () => process.platform,
38
+ machineInfo: () => ({
39
+ hostname: hostname(), platform: platform(), release: release(), arch: arch(),
40
+ type: type(), totalMemoryBytes: totalmem(), nodeVersion: process.version,
41
+ pid: process.pid, ppid: process.ppid, cwd: process.cwd(),
42
+ }),
43
+ },
44
+ archiveFactory: {
45
+ create() {
46
+ const zip = new JSZip();
47
+ return {
48
+ file({ name, content }) { zip.file(name, content); },
49
+ async generate() {
50
+ return await zip.generateAsync({ type: "nodebuffer", compression: "DEFLATE", compressionOptions: { level: 6 } });
51
+ },
52
+ };
53
+ },
54
+ },
55
+ };
56
+ }
57
+ //# sourceMappingURL=node-ports.js.map
@@ -0,0 +1,24 @@
1
+ export interface ObservabilityConfigDisabled {
2
+ enabled: false;
3
+ }
4
+ export interface ObservabilityConfigEnabled {
5
+ enabled: true;
6
+ serviceName: string;
7
+ tracerName: string;
8
+ endpoint: string;
9
+ }
10
+ export type ObservabilityConfig = ObservabilityConfigDisabled | ObservabilityConfigEnabled;
11
+ /** Resolves explicit OTLP settings. Traces endpoint wins; general endpoint gets /v1/traces.
12
+ * @param required Caller-owned service and tracer identity.
13
+ * @param options Explicit endpoints; absence disables telemetry.
14
+ * @returns Enabled configuration or the disabled variant. Never reads environment or globals.
15
+ * @throws TypeError when enabled identities are blank.
16
+ */
17
+ export declare function resolveObservabilityConfig({ serviceName, tracerName }: {
18
+ serviceName: string;
19
+ tracerName: string;
20
+ }, { endpoint, tracesEndpoint }?: {
21
+ endpoint?: string;
22
+ tracesEndpoint?: string;
23
+ }): ObservabilityConfig;
24
+ //# sourceMappingURL=config.d.ts.map
@@ -0,0 +1,21 @@
1
+ /** Resolves explicit OTLP settings. Traces endpoint wins; general endpoint gets /v1/traces.
2
+ * @param required Caller-owned service and tracer identity.
3
+ * @param options Explicit endpoints; absence disables telemetry.
4
+ * @returns Enabled configuration or the disabled variant. Never reads environment or globals.
5
+ * @throws TypeError when enabled identities are blank.
6
+ */
7
+ export function resolveObservabilityConfig({ serviceName, tracerName }, { endpoint, tracesEndpoint } = {}) {
8
+ const traces = tracesEndpoint?.trim();
9
+ const base = endpoint?.trim();
10
+ // Endpoint presence is the opt-in; a host without collector configuration stays off by default.
11
+ if (!traces && !base)
12
+ return { enabled: false };
13
+ if (!serviceName.trim())
14
+ throw new TypeError('serviceName must be non-empty');
15
+ if (!tracerName.trim())
16
+ throw new TypeError('tracerName must be non-empty');
17
+ // A signal-specific endpoint already names its route; the general endpoint needs /v1/traces.
18
+ // Treating the general endpoint as complete would send traces to the collector's wrong route.
19
+ return { enabled: true, serviceName: serviceName.trim(), tracerName: tracerName.trim(), endpoint: traces || `${base.replace(/\/+$/, '')}/v1/traces` };
20
+ }
21
+ //# sourceMappingURL=config.js.map
@@ -0,0 +1,19 @@
1
+ import type { Clock } from "@jini-ai/core/primitives";
2
+ import type { RequestIdGenerator, RequestLogPort, RequestMetricsPort, ObservabilityPort } from './ports.js';
3
+ export interface RequestHookOptions {
4
+ logger?: RequestLogPort;
5
+ metrics?: RequestMetricsPort;
6
+ tracing?: ObservabilityPort;
7
+ }
8
+ /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
9
+ * @param required Clock and request ID generator, scoped by the host.
10
+ * @param options Optional logging, metrics and tracing adapters.
11
+ * @returns Request tracking with exactly one completion event per request; DB, outbound and
12
+ * agent-run signals go straight to the tracing adapter (the no-op without one).
13
+ * @throws Hook errors propagate to the caller; adapters choose their own error policy.
14
+ */
15
+ export declare function createHookObservabilityPort({ clock, requestIdGenerator }: {
16
+ clock: Clock;
17
+ requestIdGenerator: RequestIdGenerator;
18
+ }, { logger, metrics, tracing }?: RequestHookOptions): ObservabilityPort;
19
+ //# sourceMappingURL=hooks.d.ts.map
@@ -0,0 +1,32 @@
1
+ import { createNoopObservabilityPort } from './noop.js';
2
+ /** Adds request correlation and completed-request hooks using explicit ID and clock ports.
3
+ * @param required Clock and request ID generator, scoped by the host.
4
+ * @param options Optional logging, metrics and tracing adapters.
5
+ * @returns Request tracking with exactly one completion event per request; DB, outbound and
6
+ * agent-run signals go straight to the tracing adapter (the no-op without one).
7
+ * @throws Hook errors propagate to the caller; adapters choose their own error policy.
8
+ */
9
+ export function createHookObservabilityPort({ clock, requestIdGenerator }, { logger, metrics, tracing } = {}) {
10
+ const signals = tracing ?? createNoopObservabilityPort({});
11
+ return {
12
+ trackRequest(input, options = {}) {
13
+ const requestId = options.requestId ?? requestIdGenerator.generate({});
14
+ const startedAt = clock.nowMs();
15
+ const tracker = tracing?.trackRequest(input, { requestId });
16
+ let ended = false;
17
+ return { requestId, run: (fn) => (tracker?.run ? tracker.run(fn) : fn()), end(outcome) {
18
+ if (ended)
19
+ return;
20
+ ended = true;
21
+ const event = { requestId, method: input.method, ...outcome, durationMs: Math.max(0, clock.nowMs() - startedAt) };
22
+ tracker?.end(outcome);
23
+ logger?.log(event);
24
+ metrics?.recordRequest(event);
25
+ } };
26
+ },
27
+ trackDbQuery: (input) => signals.trackDbQuery(input),
28
+ trackOutboundCall: (input) => signals.trackOutboundCall(input),
29
+ trackAgentRun: (input, options) => signals.trackAgentRun(input, options),
30
+ };
31
+ }
32
+ //# sourceMappingURL=hooks.js.map
@@ -0,0 +1,17 @@
1
+ import type { ObservabilityConfig } from './config.js';
2
+ import type { ExporterFactory, TracerProviderFactory, ObservabilityPort } from './ports.js';
3
+ import { type OtelAdapterOptions } from './otel.js';
4
+ export * from './config.js';
5
+ export * from './ports.js';
6
+ export * from './noop.js';
7
+ export * from './otel.js';
8
+ export * from './hooks.js';
9
+ export * from './instrumentation.js';
10
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
11
+ * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
12
+ export declare function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }: {
13
+ config: ObservabilityConfig;
14
+ exporterFactory: ExporterFactory;
15
+ tracerProviderFactory: TracerProviderFactory;
16
+ }, options?: OtelAdapterOptions): ObservabilityPort;
17
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,16 @@
1
+ import { createNoopObservabilityPort } from './noop.js';
2
+ import { createOtelObservabilityPort } from './otel.js';
3
+ export * from './config.js';
4
+ export * from './ports.js';
5
+ export * from './noop.js';
6
+ export * from './otel.js';
7
+ export * from './hooks.js';
8
+ export * from './instrumentation.js';
9
+ /** Selects an adapter from explicit config; disabled telemetry never invokes either factory.
10
+ * @param options Adapter options (host span scope); ignored when telemetry is disabled. */
11
+ export function createObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options = {}) {
12
+ if (!config.enabled)
13
+ return createNoopObservabilityPort({});
14
+ return createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }, options);
15
+ }
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,61 @@
1
+ import type { HttpClientPort } from "@jini-ai/core/primitives";
2
+ import type { ObservabilityPort } from './ports.js';
3
+ /**
4
+ * @file Decorators that put a host's existing chokepoints on the observability port: the storage
5
+ * kernel (every repo query, on every dialect) and the guarded HTTP client (every vetted egress call).
6
+ * Both return their input untouched for the no-op port, so a disabled install keeps the exact
7
+ * objects and call paths it had — no wrapper frame, no per-query plugin, no allocation.
8
+ */
9
+ export interface QueryDescription {
10
+ operation: string;
11
+ table?: string;
12
+ }
13
+ /** Operation and table of one Kysely operation node. Reads node kinds and identifiers only — never
14
+ * parameter values or statement text, so the description is safe to export whatever the query binds.
15
+ * A raw statement contributes its leading keyword alone (`pragma`, `select`), or `raw`. */
16
+ export declare function describeQueryNode({ node }: {
17
+ node: unknown;
18
+ }): QueryDescription;
19
+ /** The kernel surface the decorator replaces; `StorageKernel<DB>` from `@jini-ai/db/kernel` fits it. */
20
+ export interface InstrumentableKernel {
21
+ readonly dialect: string;
22
+ run(fn: (db: any) => unknown): Promise<unknown>;
23
+ transaction(fn: () => Promise<unknown>): Promise<unknown>;
24
+ query(statement: any): Promise<unknown>;
25
+ execute(statement: any): Promise<unknown>;
26
+ }
27
+ /**
28
+ * Tracks every kernel `run`/`transaction`/`query`/`execute` as one DB span, decorating the kernel
29
+ * IN PLACE. A replacement object would break identity-keyed lookups hosts already rely on (the
30
+ * SQLite driver's connection reverse cache, kernels cached per connection), and in-place keeps every
31
+ * holder of the same kernel covered. `run` bodies get the builder with a capture plugin, so the span
32
+ * is named from the first query the body builds (operation + table), never its SQL text.
33
+ * @param required The kernel and the port. A no-op port, or a kernel already decorated, is left alone.
34
+ * @returns The same kernel object.
35
+ * @complexity O(1) per call beyond one plugin pass per built query.
36
+ */
37
+ export declare function instrumentStorageKernel<K extends InstrumentableKernel>({ kernel, observability }: {
38
+ kernel: K;
39
+ observability: ObservabilityPort;
40
+ }): K;
41
+ /** Any `fetch`-shaped function: the global, a timeout wrapper, a SigV4 client's `fetch`. Structural,
42
+ * so this universal entry needs no DOM or undici types. */
43
+ export type FetchLike = (input: any, init?: any) => Promise<{
44
+ status: number;
45
+ }>;
46
+ /** One outbound span per call of a raw `fetch` — the egress paths that do not go through a guarded
47
+ * client (deploy hosts, git hosts, object stores, loopback). Input, init and the response pass through
48
+ * untouched; the span gets scheme/host/port and status only, like {@link trackHttpClient}.
49
+ * @returns `fetch` itself for the no-op port.
50
+ * @complexity O(1) per call. */
51
+ export declare function trackFetch<F extends FetchLike>({ fetch, observability }: {
52
+ fetch: F;
53
+ observability: ObservabilityPort;
54
+ }): F;
55
+ /** One outbound span per `send`, with the response status or the transport failure; the call itself
56
+ * is unchanged. Returns `client` itself for the no-op port. */
57
+ export declare function trackHttpClient({ client, observability }: {
58
+ client: HttpClientPort;
59
+ observability: ObservabilityPort;
60
+ }): HttpClientPort;
61
+ //# sourceMappingURL=instrumentation.d.ts.map
@@ -0,0 +1,139 @@
1
+ import { isNoopObservabilityPort } from './noop.js';
2
+ function tableName(node) {
3
+ const n = node;
4
+ if (n?.kind === 'AliasNode')
5
+ return tableName(n.node);
6
+ const name = n?.kind === 'TableNode' ? n.table?.identifier?.name : undefined;
7
+ return typeof name === 'string' ? name : undefined;
8
+ }
9
+ function withTable(operation, node) {
10
+ const table = tableName(node);
11
+ return table ? { operation, table } : { operation };
12
+ }
13
+ /** Operation and table of one Kysely operation node. Reads node kinds and identifiers only — never
14
+ * parameter values or statement text, so the description is safe to export whatever the query binds.
15
+ * A raw statement contributes its leading keyword alone (`pragma`, `select`), or `raw`. */
16
+ export function describeQueryNode({ node }) {
17
+ const n = node;
18
+ switch (n?.kind) {
19
+ case 'SelectQueryNode': return withTable('select', n.from?.froms?.[0]);
20
+ case 'InsertQueryNode': return withTable('insert', n.into);
21
+ case 'UpdateQueryNode': return withTable('update', n.table);
22
+ case 'DeleteQueryNode': return withTable('delete', n.from?.froms?.[0]);
23
+ case 'RawNode': {
24
+ // The keyword must end at a boundary: a fragment that opens with a quoted literal is not one.
25
+ const keyword = /^\s*([A-Za-z]+)(?![A-Za-z0-9_'"])/.exec(n.sqlFragments?.[0] ?? '')?.[1];
26
+ return { operation: keyword ? keyword.toLowerCase() : 'raw' };
27
+ }
28
+ default:
29
+ if (typeof n?.kind !== 'string')
30
+ return { operation: 'query' };
31
+ return { operation: n.kind.replace(/(Query)?Node$/, '').replace(/([a-z0-9])([A-Z])/g, '$1_$2').toLowerCase() };
32
+ }
33
+ }
34
+ const INSTRUMENTED = new WeakSet();
35
+ async function settle({ tracker, describe }, work) {
36
+ let result;
37
+ try {
38
+ result = await tracker.run(work);
39
+ }
40
+ catch (error) {
41
+ tracker.end({ ...describe(), error });
42
+ throw error;
43
+ }
44
+ tracker.end(describe());
45
+ return result;
46
+ }
47
+ function rawDescription(statement) {
48
+ const toNode = statement?.toOperationNode;
49
+ return describeQueryNode({ node: typeof toNode === 'function' ? toNode.call(statement) : null });
50
+ }
51
+ /**
52
+ * Tracks every kernel `run`/`transaction`/`query`/`execute` as one DB span, decorating the kernel
53
+ * IN PLACE. A replacement object would break identity-keyed lookups hosts already rely on (the
54
+ * SQLite driver's connection reverse cache, kernels cached per connection), and in-place keeps every
55
+ * holder of the same kernel covered. `run` bodies get the builder with a capture plugin, so the span
56
+ * is named from the first query the body builds (operation + table), never its SQL text.
57
+ * @param required The kernel and the port. A no-op port, or a kernel already decorated, is left alone.
58
+ * @returns The same kernel object.
59
+ * @complexity O(1) per call beyond one plugin pass per built query.
60
+ */
61
+ export function instrumentStorageKernel({ kernel, observability }) {
62
+ if (isNoopObservabilityPort(observability) || INSTRUMENTED.has(kernel))
63
+ return kernel;
64
+ INSTRUMENTED.add(kernel);
65
+ const target = kernel;
66
+ const system = target.dialect === 'postgres' ? 'postgresql' : target.dialect;
67
+ const run = target.run.bind(target), transaction = target.transaction.bind(target);
68
+ const query = target.query.bind(target), execute = target.execute.bind(target);
69
+ target.run = (fn) => {
70
+ let seen;
71
+ const capture = {
72
+ transformQuery: ({ node }) => { seen ??= describeQueryNode({ node }); return node; },
73
+ transformResult: async ({ result }) => result,
74
+ };
75
+ const withCapture = (db) => {
76
+ const builder = db;
77
+ return typeof builder?.withPlugin === 'function' ? builder.withPlugin(capture) : db;
78
+ };
79
+ return settle({ tracker: observability.trackDbQuery({ system }), describe: () => seen ?? { operation: 'run' } }, () => run((db) => fn(withCapture(db))));
80
+ };
81
+ // Inner run() spans start inside the transaction's scope, so they nest under it.
82
+ target.transaction = (fn) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => ({ operation: 'transaction' }) }, () => transaction(fn));
83
+ target.query = (statement) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => rawDescription(statement) }, () => query(statement));
84
+ target.execute = (statement) => settle({ tracker: observability.trackDbQuery({ system }), describe: () => rawDescription(statement) }, () => execute(statement));
85
+ return kernel;
86
+ }
87
+ /** URL and method of one fetch call: `init.method` wins over a Request's own, as in `fetch` itself.
88
+ * Anything that is not a string, URL or Request-shaped object becomes '' (the adapter's `invalid-url`). */
89
+ function fetchTarget(input, init) {
90
+ const shaped = (typeof input === 'object' && input !== null ? input : {});
91
+ const raw = typeof input === 'string' ? input : shaped.href ?? shaped.url;
92
+ const method = init?.method ?? shaped.method;
93
+ return { url: typeof raw === 'string' ? raw : '', method: typeof method === 'string' ? method.toUpperCase() : 'GET' };
94
+ }
95
+ /** One outbound span per call of a raw `fetch` — the egress paths that do not go through a guarded
96
+ * client (deploy hosts, git hosts, object stores, loopback). Input, init and the response pass through
97
+ * untouched; the span gets scheme/host/port and status only, like {@link trackHttpClient}.
98
+ * @returns `fetch` itself for the no-op port.
99
+ * @complexity O(1) per call. */
100
+ export function trackFetch({ fetch, observability }) {
101
+ if (isNoopObservabilityPort(observability))
102
+ return fetch;
103
+ const tracked = async (input, init) => {
104
+ const tracker = observability.trackOutboundCall(fetchTarget(input, init));
105
+ let response;
106
+ try {
107
+ response = await tracker.run(() => fetch(input, init));
108
+ }
109
+ catch (error) {
110
+ tracker.end({ error });
111
+ throw error;
112
+ }
113
+ tracker.end({ statusCode: response.status });
114
+ return response;
115
+ };
116
+ return tracked;
117
+ }
118
+ /** One outbound span per `send`, with the response status or the transport failure; the call itself
119
+ * is unchanged. Returns `client` itself for the no-op port. */
120
+ export function trackHttpClient({ client, observability }) {
121
+ if (isNoopObservabilityPort(observability))
122
+ return client;
123
+ return {
124
+ async send(required, optional) {
125
+ const tracker = observability.trackOutboundCall({ method: required.request.method, url: required.request.url });
126
+ let response;
127
+ try {
128
+ response = await tracker.run(() => client.send(required, optional));
129
+ }
130
+ catch (error) {
131
+ tracker.end({ error });
132
+ throw error;
133
+ }
134
+ tracker.end({ statusCode: response.status });
135
+ return response;
136
+ },
137
+ };
138
+ }
139
+ //# sourceMappingURL=instrumentation.js.map
@@ -0,0 +1,12 @@
1
+ import type { SpanScopePort } from './ports.js';
2
+ /**
3
+ * The active span per async context, for Node hosts: pass it as the adapter's `scope` so a DB query
4
+ * or outbound call made while serving a request becomes that request span's child. Kept out of the
5
+ * universal `./observability` entry because AsyncLocalStorage is Node-only. A continuation resumed
6
+ * from a callback registered outside the scope (some stream/body-parser paths) sees no active span
7
+ * and starts a root span: it is never attributed to the wrong request.
8
+ * @param _required Empty; each call owns a fresh store.
9
+ * @returns A scope port over one AsyncLocalStorage instance.
10
+ */
11
+ export declare function createAsyncLocalSpanScope(_required: Record<string, never>): SpanScopePort;
12
+ //# sourceMappingURL=node.d.ts.map
@@ -0,0 +1,15 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ /**
3
+ * The active span per async context, for Node hosts: pass it as the adapter's `scope` so a DB query
4
+ * or outbound call made while serving a request becomes that request span's child. Kept out of the
5
+ * universal `./observability` entry because AsyncLocalStorage is Node-only. A continuation resumed
6
+ * from a callback registered outside the scope (some stream/body-parser paths) sees no active span
7
+ * and starts a root span: it is never attributed to the wrong request.
8
+ * @param _required Empty; each call owns a fresh store.
9
+ * @returns A scope port over one AsyncLocalStorage instance.
10
+ */
11
+ export function createAsyncLocalSpanScope(_required) {
12
+ const storage = new AsyncLocalStorage();
13
+ return { active: () => storage.getStore(), run: ({ span, fn }) => storage.run(span, fn) };
14
+ }
15
+ //# sourceMappingURL=node.js.map
@@ -0,0 +1,7 @@
1
+ import type { ObservabilityPort } from './ports.js';
2
+ /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
3
+ export declare function createNoopObservabilityPort(_required: Record<string, never>): ObservabilityPort;
4
+ /** True for a port this module built. Decorators use it to skip wrapping entirely when telemetry is
5
+ * off, so a disabled install pays no per-query or per-call indirection, not merely no export. */
6
+ export declare function isNoopObservabilityPort(port: ObservabilityPort): boolean;
7
+ //# sourceMappingURL=noop.d.ts.map
@@ -0,0 +1,22 @@
1
+ const run = (fn) => fn();
2
+ const NOOP_TRACKER = Object.freeze({ end() { }, run });
3
+ // One frozen tracker serves every non-request signal too: their end() outcomes differ only in type.
4
+ const NOOP_SIGNAL_TRACKER = Object.freeze({ end() { }, run });
5
+ const NOOP_PORTS = new WeakSet();
6
+ /** Creates disabled telemetry; every request shares one frozen tracker without allocation. */
7
+ export function createNoopObservabilityPort(_required) {
8
+ const port = {
9
+ trackRequest: () => NOOP_TRACKER,
10
+ trackDbQuery: () => NOOP_SIGNAL_TRACKER,
11
+ trackOutboundCall: () => NOOP_SIGNAL_TRACKER,
12
+ trackAgentRun: () => NOOP_SIGNAL_TRACKER,
13
+ };
14
+ NOOP_PORTS.add(port);
15
+ return port;
16
+ }
17
+ /** True for a port this module built. Decorators use it to skip wrapping entirely when telemetry is
18
+ * off, so a disabled install pays no per-query or per-call indirection, not merely no export. */
19
+ export function isNoopObservabilityPort(port) {
20
+ return NOOP_PORTS.has(port);
21
+ }
22
+ //# sourceMappingURL=noop.js.map
@@ -0,0 +1,28 @@
1
+ import type { ObservabilityConfigEnabled } from './config.js';
2
+ import type { ExporterFactory, TracerProviderFactory, ObservabilityPort, SpanScopePort } from './ports.js';
3
+ export interface OtelAdapterDependencies {
4
+ config: ObservabilityConfigEnabled;
5
+ exporterFactory: ExporterFactory;
6
+ tracerProviderFactory: TracerProviderFactory;
7
+ }
8
+ export interface OtelAdapterOptions {
9
+ scope?: SpanScopePort;
10
+ }
11
+ type Attributes = Record<string, string | number>;
12
+ /** A low-cardinality error label: a SCREAMING_CASE code (ECONNREFUSED, SQLITE_BUSY), else the class
13
+ * name. Messages are never exported: they carry SQL fragments, hostnames, emails, even credentials. */
14
+ export declare function errorType(error: unknown): string;
15
+ /** Query and fragment are dropped (tokens ride there most often); secret-shaped path values are
16
+ * blanked. Ids stay: an operator searches by them, and a route pattern alone cannot name a record. */
17
+ export declare function redactRequestTarget(path: string): string;
18
+ /** Scheme, host and explicit port only. Paths carry bot tokens and signed-URL keys; userinfo carries passwords. */
19
+ export declare function outboundTargetAttributes(url: string): Attributes;
20
+ /** Builds request, DB, outbound and agent-run spans through injected provider/exporter factories.
21
+ * @param required Explicit config and structural factories. Hosts wrap their SDK here.
22
+ * @param options Optional host scope storage; with it, spans started inside a tracker's run() are its children.
23
+ * @returns One adapter whose spans end once, with final names, redacted attributes and error status.
24
+ * @throws Provider/exporter errors propagate during setup. No globals or SDK imports are used.
25
+ */
26
+ export declare function createOtelObservabilityPort({ config, exporterFactory, tracerProviderFactory }: OtelAdapterDependencies, { scope }?: OtelAdapterOptions): ObservabilityPort;
27
+ export {};
28
+ //# sourceMappingURL=otel.d.ts.map