@burdenoff/be-sdk 2026.1130.3 → 2026.1201.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 +6 -1
- package/dist/context/index.js +7 -2
- package/dist/context/index.js.map +1 -1
- package/dist/files/index.d.ts +2 -2
- package/dist/files/index.js +2 -2
- package/dist/{files-h5U-D2AF.js → files-BISdM0fh.js} +188 -28
- package/dist/files-BISdM0fh.js.map +1 -0
- package/dist/{bun-runtime-metrics-CPy5D6NT.js → incoming-request-span-DCou42Il.js} +56 -2
- package/dist/incoming-request-span-DCou42Il.js.map +1 -0
- package/dist/{index-8pUSoT85.d.ts → index-ieSQpD9r.d.ts} +26 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +3 -3
- package/dist/prisma/index.js +2 -2
- package/dist/{prisma-Bo-C0XUv.js → prisma-D0f-THMv.js} +2 -2
- package/dist/{prisma-Bo-C0XUv.js.map → prisma-D0f-THMv.js.map} +1 -1
- package/dist/{sdk-7TBR987n.js → sdk-Oooulm2n.js} +22 -6
- package/dist/sdk-Oooulm2n.js.map +1 -0
- package/dist/server/index.js +5 -5
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-DNkzpQvR.js → stub-CmVOE6ql.js} +2 -2
- package/dist/{stub-DNkzpQvR.js.map → stub-CmVOE6ql.js.map} +1 -1
- package/dist/telemetry/index.d.ts +40 -2
- package/dist/telemetry/index.js +3 -3
- package/dist/telemetry/index.js.map +1 -1
- package/dist/tracker/index.js +2 -2
- package/dist/{tracker-CDVYIoCb.js → tracker-CNF8TRpk.js} +2 -2
- package/dist/{tracker-CDVYIoCb.js.map → tracker-CNF8TRpk.js.map} +1 -1
- package/dist/{workspace-extension-BcMPoGWr.js → workspace-extension-feJYFO9e.js} +41 -8
- package/dist/workspace-extension-feJYFO9e.js.map +1 -0
- package/package.json +1 -1
- package/dist/bun-runtime-metrics-CPy5D6NT.js.map +0 -1
- package/dist/files-h5U-D2AF.js.map +0 -1
- package/dist/sdk-7TBR987n.js.map +0 -1
- package/dist/workspace-extension-BcMPoGWr.js.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
2
2
|
import { n as markExplicitActivity } from "./explicit-activity-scope-DikJ7NAE.js";
|
|
3
|
-
import { c as getScopedWorkspaceContext, l as getWorkspaceContext } from "./workspace-extension-
|
|
3
|
+
import { c as getScopedWorkspaceContext, l as getWorkspaceContext } from "./workspace-extension-feJYFO9e.js";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
|
|
6
6
|
// src/activity/assistant-session.ts
|
|
@@ -574,4 +574,4 @@ const UNIFIED_TRACKER_CONSTANTS = {
|
|
|
574
574
|
};
|
|
575
575
|
|
|
576
576
|
export { resolveAssistantSession as a, ACTOR_ORIGIN_HEADER as c, ASSISTANT_SESSION_ID_HEADER as d, parseAssistantSessionHeaders as f, isTrackedActorType as i, AI_ASSISTANT_ACTOR_ORIGIN as l, toAssistantSessionAttribution as m, UnifiedTrackerStub as n, trackOperation as o, readAssistantSessionAttribution as p, createProductTracker as r, trackerStub as s, UNIFIED_TRACKER_CONSTANTS as t, ASSISTANT_CORRELATION_ID_HEADER as u };
|
|
577
|
-
//# sourceMappingURL=stub-
|
|
577
|
+
//# sourceMappingURL=stub-CmVOE6ql.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stub-DNkzpQvR.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const actOpts = options.activityOptions;\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending \"${operation}\" without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for \"${operation}\" (${outcome.detail}); retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC;CACzD,OAAO,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,IAAI,QAAQ;AACnF;;;;;;AAOA,SAAgB,8BACd,aACA,oBACA,wBACyC;CACzC,IAAI,gCAA2C,OAAO;CACtD,MAAM,YAAY,cAAc,kBAAkB;CAClD,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,gBAAgB,cAAc,sBAAsB;CAC1D,OAAO;EACL,aAAa;EACb,oBAAoB;EACpB,GAAI,gBAAgB,EAAE,wBAAwB,cAAc,IAAI,CAAC;CACnE;AACF;;;;;AAMA,SAAgB,6BACd,WACyC;CACzC,OAAO,8BACL,UAAU,mBAAmB,GA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;CACpB,YAAY,CAAC;CACb,UAAU,CAAC;AACb"}
|
|
1
|
+
{"version":3,"file":"stub-CmVOE6ql.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const actOpts = options.activityOptions;\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending \"${operation}\" without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for \"${operation}\": ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for \"${operation}\" (${outcome.detail}); retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC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,SAAS,MAAM;GACjC,CAAC;EACH;EACA,MAAM,eAAe,eAAe,mBAAqC;GACvE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB,EAAE,SAAS,MAAM;IAClC,cAAc;KAAE,GAAG,gBAAgB;KAAc,GAAG,mBAAmB;KAAc,SAAS;IAAK;GACrG,CAAC;EACH;EACA,MAAM,YAAY,eAAe,mBAAqC;GACpE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;GACL,CAAC;EACH;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,4BAA4B;CACvC,oBAAoB;CACpB,YAAY,CAAC;CACb,UAAU,CAAC;AACb"}
|
|
@@ -5,7 +5,7 @@ interface TelemetryIdGenerator {
|
|
|
5
5
|
generateSpanId(): string;
|
|
6
6
|
}
|
|
7
7
|
export declare function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined;
|
|
8
|
-
type OtelPeerPackage = '@opentelemetry/api' | '@opentelemetry/auto-instrumentations-node' | '@opentelemetry/exporter-metrics-otlp-http' | '@opentelemetry/exporter-trace-otlp-http' | '@opentelemetry/resources' | '@opentelemetry/sdk-metrics' | '@opentelemetry/sdk-node' | '@opentelemetry/sdk-trace-base' | '@opentelemetry/semantic-conventions';
|
|
8
|
+
type OtelPeerPackage = '@opentelemetry/api' | '@opentelemetry/auto-instrumentations-node' | '@opentelemetry/exporter-metrics-otlp-http' | '@opentelemetry/exporter-trace-otlp-http' | '@opentelemetry/resources' | '@opentelemetry/sdk-metrics' | '@opentelemetry/sdk-node' | '@opentelemetry/sdk-trace' | '@opentelemetry/sdk-trace-base' | '@opentelemetry/semantic-conventions';
|
|
9
9
|
type OtelModules = Partial<Record<OtelPeerPackage | InstrumentationPackage, unknown>>;
|
|
10
10
|
type InstrumentationPackage = `@opentelemetry/instrumentation-${string}`;
|
|
11
11
|
interface PrismaLike {
|
|
@@ -28,6 +28,44 @@ interface HealthDeps {
|
|
|
28
28
|
serviceName?: string;
|
|
29
29
|
}
|
|
30
30
|
export declare function createHealthRoutes(_deps?: HealthDeps): unknown;
|
|
31
|
+
interface IncomingSpanApi {
|
|
32
|
+
ROOT_CONTEXT: unknown;
|
|
33
|
+
SpanKind: {
|
|
34
|
+
SERVER: number;
|
|
35
|
+
};
|
|
36
|
+
SpanStatusCode: {
|
|
37
|
+
ERROR: number;
|
|
38
|
+
};
|
|
39
|
+
propagation: {
|
|
40
|
+
extract: (ctx: unknown, carrier: Headers, getter: {
|
|
41
|
+
get: (carrier: Headers, key: string) => string | undefined;
|
|
42
|
+
keys: (carrier: Headers) => string[];
|
|
43
|
+
}) => unknown;
|
|
44
|
+
};
|
|
45
|
+
context: {
|
|
46
|
+
with: <T>(ctx: unknown, fn: () => T) => T;
|
|
47
|
+
};
|
|
48
|
+
trace: {
|
|
49
|
+
getTracer: (name: string) => {
|
|
50
|
+
startSpan: (name: string, options: {
|
|
51
|
+
kind: number;
|
|
52
|
+
attributes: Record<string, string | number>;
|
|
53
|
+
}, ctx: unknown) => IncomingSpan;
|
|
54
|
+
};
|
|
55
|
+
setSpan: (ctx: unknown, span: IncomingSpan) => unknown;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
interface IncomingSpan {
|
|
59
|
+
setAttribute: (key: string, value: string | number) => unknown;
|
|
60
|
+
setStatus: (status: {
|
|
61
|
+
code: number;
|
|
62
|
+
message?: string;
|
|
63
|
+
}) => unknown;
|
|
64
|
+
recordException: (exception: Error) => unknown;
|
|
65
|
+
end: () => void;
|
|
66
|
+
}
|
|
67
|
+
export declare const INCOMING_REQUEST_TRACER = "@burdenoff/be-sdk/server";
|
|
68
|
+
export declare function withIncomingRequestSpan(request: Request, route: string, handle: () => Promise<Response>, api?: IncomingSpanApi | null): Promise<Response>;
|
|
31
69
|
interface PromRegistryLike {
|
|
32
70
|
metrics: () => Promise<string> | string;
|
|
33
71
|
contentType?: string;
|
|
@@ -87,4 +125,4 @@ export interface TelemetryHandle {
|
|
|
87
125
|
shutdown: () => Promise<void>;
|
|
88
126
|
}
|
|
89
127
|
export declare function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle>;
|
|
90
|
-
export { type CollectorLayer, type OtelModules, type OtelPeerPackage, type TelemetryIdGenerator, initializeInstrumentation, setupInstrumentation };
|
|
128
|
+
export { type CollectorLayer, type IncomingSpan, type IncomingSpanApi, type OtelModules, type OtelPeerPackage, type TelemetryIdGenerator, initializeInstrumentation, setupInstrumentation };
|
package/dist/telemetry/index.js
CHANGED
|
@@ -2,7 +2,7 @@ import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
|
|
|
2
2
|
import { a as logger, s as redactSensitiveFields, t as Logger } from "../logger-B6rCpb7D.js";
|
|
3
3
|
import { D as setActiveTelemetryLogger, n as initializeInstrumentation, o as setupInstrumentation } from "../instrumentation-DKHAGCoz.js";
|
|
4
4
|
import { a as resolveCollectorLayer, i as defaultCollectorTracesEndpoint, n as OTLP_HTTP_PORT, r as defaultCollectorEndpoint, t as COLLECTOR_SERVICE } from "../collector-endpoint-iyQYeI50.js";
|
|
5
|
-
import {
|
|
5
|
+
import { n as withIncomingRequestSpan, r as collectPromDefaultMetrics, t as INCOMING_REQUEST_TRACER } from "../incoming-request-span-DCou42Il.js";
|
|
6
6
|
|
|
7
7
|
// src/telemetry/id-generator.ts
|
|
8
8
|
/**
|
|
@@ -352,7 +352,7 @@ async function bootstrapTelemetry(cfg) {
|
|
|
352
352
|
if (resolveOtelSdkEnabled()) {
|
|
353
353
|
console.log("[telemetry] OTel SDK bootstrap starting...");
|
|
354
354
|
try {
|
|
355
|
-
const { createOtelSdk } = await import("../sdk-
|
|
355
|
+
const { createOtelSdk } = await import("../sdk-Oooulm2n.js");
|
|
356
356
|
otelSdk = await createOtelSdk({
|
|
357
357
|
serviceName: cfg.serviceName,
|
|
358
358
|
serviceVersion,
|
|
@@ -405,5 +405,5 @@ async function bootstrapTelemetry(cfg) {
|
|
|
405
405
|
};
|
|
406
406
|
}
|
|
407
407
|
|
|
408
|
-
export { COLLECTOR_SERVICE, DEFAULT_REDACT_PATHS, OTLP_HTTP_PORT, assertTelemetryIdGenerator, bootstrapTelemetry, createHealthRoutes, createMetricsRoutes, createPinoLogger, createPrismaLoggingExtension, defaultCollectorEndpoint, defaultCollectorTracesEndpoint, initializeInstrumentation, resolveCollectorLayer, setupInstrumentation };
|
|
408
|
+
export { COLLECTOR_SERVICE, DEFAULT_REDACT_PATHS, INCOMING_REQUEST_TRACER, OTLP_HTTP_PORT, assertTelemetryIdGenerator, bootstrapTelemetry, createHealthRoutes, createMetricsRoutes, createPinoLogger, createPrismaLoggingExtension, defaultCollectorEndpoint, defaultCollectorTracesEndpoint, initializeInstrumentation, resolveCollectorLayer, setupInstrumentation, withIncomingRequestSpan };
|
|
409
409
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\nimport { collectPromDefaultMetrics, type PromDefaultMetricsClient } from './bun-runtime-metrics.js';\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as PromDefaultMetricsClient & {\n register: PromRegistryLike;\n };\n // Kick runtime metrics into the default registry if not already. Under Bun\n // this leaves out the heap-space gauges, whose collect walks the heap (BOFF-12287).\n collectPromDefaultMetrics(mod);\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2FAA2F;CAEjH,MAAM,EAAE,iBAAiB,mBAAmB;CAI5C,IAAI,OAAO,oBAAoB,cAAc,OAAO,mBAAmB,YACrE,MAAM,IAAI,UAAU,4FAA4F;AAEpH;;;ACyCA,SAAgB,mBAAmB,QAAoB,CAAC,GAAY;CAElE,OAAO,IAAI,MACT,CAA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QAAQ,mBAAmB;IACxD,SAAO,KAAK,kFAAkF;KAC5F,aAAa,IAAI;KACjB,QAAQ,QAAQ;IAClB,CAAC;IACD,QAAQ,KAAK,iDAAiD,QAAQ,iBAAiB;GACzF;EACF,SAAS,KAAK;GACZ,SAAO,KAAK,0FAA0F,EACpG,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;GAGD,QAAQ,MAAM,gCAAgC,GAAG;EACnD;CACF,OAAO;EACL,SAAO,KAAK,+CAA+C;EAC3D,QAAQ,IAAI,+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\nimport { collectPromDefaultMetrics, type PromDefaultMetricsClient } from './bun-runtime-metrics.js';\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as PromDefaultMetricsClient & {\n register: PromRegistryLike;\n };\n // Kick runtime metrics into the default registry if not already. Under Bun\n // this leaves out the heap-space gauges, whose collect walks the heap (BOFF-12287).\n collectPromDefaultMetrics(mod);\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { INCOMING_REQUEST_TRACER, withIncomingRequestSpan } from './incoming-request-span.js';\nexport type { IncomingSpan, IncomingSpanApi } from './incoming-request-span.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2F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GAGD,SAAO,KAAK,uDAAuD;IACjE,aAAa,IAAI;IACjB,cAAc,eAAe,iBAAiB;IAC9C;IACA,gBAAgB,QAAQ;IACxB,mBAAmB,IAAI,gBAAgB;GACzC,CAAC;GACD,QAAQ,IAAI,gDAAgD;GAE5D,IAAI,CAAC,QAAQ,kBAAkB,QAAQ,mBAAmB;IACxD,SAAO,KAAK,kFAAkF;KAC5F,aAAa,IAAI;KACjB,QAAQ,QAAQ;IAClB,CAAC;IACD,QAAQ,KAAK,iDAAiD,QAAQ,iBAAiB;GACzF;EACF,SAAS,KAAK;GACZ,SAAO,KAAK,0FAA0F,EACpG,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;GAGD,QAAQ,MAAM,gCAAgC,GAAG;EACnD;CACF,OAAO;EACL,SAAO,KAAK,+CAA+C;EAC3D,QAAQ,IAAI,+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
|
package/dist/tracker/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { i as suppressMutationAudit } from "../explicit-activity-scope-DikJ7NAE.js";
|
|
2
2
|
import "../activity/index.js";
|
|
3
3
|
import { i as UsageMetricType } from "../usage-BK7eyP42.js";
|
|
4
|
-
import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-
|
|
5
|
-
import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-
|
|
4
|
+
import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-CmVOE6ql.js";
|
|
5
|
+
import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-CNF8TRpk.js";
|
|
6
6
|
|
|
7
7
|
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, TrackerModule, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, UsageMetricType, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
|
|
8
8
|
//# sourceMappingURL=index.js.map
|
|
@@ -4,7 +4,7 @@ import { t as RBACModule } from "./rbac-pRCcWVS_.js";
|
|
|
4
4
|
import { ActivityModule, ActivitySeverity, ActivityStatus, ActivityType } from "./activity/index.js";
|
|
5
5
|
import { a as UsageModule } from "./usage-BK7eyP42.js";
|
|
6
6
|
import { n as NotificationType, r as NotificationsModule } from "./notifications-DY_i37WN.js";
|
|
7
|
-
import { o as trackOperation } from "./stub-
|
|
7
|
+
import { o as trackOperation } from "./stub-CmVOE6ql.js";
|
|
8
8
|
import { r as runInExplicitActivityScope, t as createExplicitActivityScope } from "./explicit-activity-scope-DikJ7NAE.js";
|
|
9
9
|
|
|
10
10
|
// src/tracker/agent-activity.ts
|
|
@@ -455,4 +455,4 @@ var TrackerModule = class {
|
|
|
455
455
|
};
|
|
456
456
|
|
|
457
457
|
export { trackAgentActivity as i, AGENT_ACTIVITY_ACTIONS as n, AGENT_ACTIVITY_RESOURCE_TYPE as r, TrackerModule as t };
|
|
458
|
-
//# sourceMappingURL=tracker-
|
|
458
|
+
//# sourceMappingURL=tracker-CNF8TRpk.js.map
|