@burdenoff/be-sdk 2026.1017.10 → 2026.1021.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -135,6 +135,31 @@ await sdk.translation.upsertProductTranslations({
135
135
  - **payments**: Payment processing
136
136
  - **bootstrap**: Server initialization
137
137
  - **platform**: Scale primitives (see below)
138
+ - **validation**: User-field validators and the `@rbac` coverage guard (see below)
139
+
140
+ ### RBAC coverage guard (`@burdenoff/be-sdk/validation`)
141
+
142
+ `assertRbacCoverage(pathOrDocuments, options)` parses a svc's SDL (a directory of
143
+ `.gql`/`.graphql` files, or a single file such as `.hive-schema.graphql`) and fails when a
144
+ Query/Mutation/Subscription field has no `@rbac`, has one the gateway would deny as invalid
145
+ (missing `action`/`resource`/`scopeType`, unknown `scopeType`, `entity` without `scopeArg`),
146
+ or has a `resourceIdArg`/`scopeArg` that does not resolve to one `ID`/`String` within two
147
+ segments. Pass `selfScopedFields` to pin the reviewed `scopeType: "self"` surface. Call it
148
+ from one unit test per svc:
149
+
150
+ ```typescript
151
+ import { join } from 'node:path';
152
+ import { assertRbacCoverage } from '@burdenoff/be-sdk/validation';
153
+
154
+ it('gates every root field with a well-formed @rbac', () => {
155
+ assertRbacCoverage(join(__dirname, '../modules'), {
156
+ minRootFields: 200, // a wrong path must not pass
157
+ selfScopedFields: { mySettings: 'type C: resolver filters by ctx.actorId' },
158
+ });
159
+ });
160
+ ```
161
+
162
+ `analyzeRbacCoverage` returns the same report without throwing.
138
163
 
139
164
  ### Platform Primitives (`@burdenoff/be-sdk/platform`)
140
165
 
@@ -0,0 +1,394 @@
1
+ import { logger } from './chunk-RU266375.js';
2
+ import { __name } from './chunk-XE4OXN2W.js';
3
+ import { AsyncLocalStorage } from 'async_hooks';
4
+ import { randomUUID } from 'crypto';
5
+
6
+ var scopeStorage = new AsyncLocalStorage();
7
+ function createExplicitActivityScope() {
8
+ return {
9
+ explicitCount: 0,
10
+ suppressed: false
11
+ };
12
+ }
13
+ __name(createExplicitActivityScope, "createExplicitActivityScope");
14
+ function runInExplicitActivityScope(scope, fn) {
15
+ return scopeStorage.run(scope, fn);
16
+ }
17
+ __name(runInExplicitActivityScope, "runInExplicitActivityScope");
18
+ function markExplicitActivity() {
19
+ const scope = scopeStorage.getStore();
20
+ if (scope) scope.explicitCount += 1;
21
+ }
22
+ __name(markExplicitActivity, "markExplicitActivity");
23
+ function suppressMutationAudit() {
24
+ const scope = scopeStorage.getStore();
25
+ if (scope) scope.suppressed = true;
26
+ }
27
+ __name(suppressMutationAudit, "suppressMutationAudit");
28
+ var _gatewayUrl;
29
+ var _gatewayLayer;
30
+ var _gatewayUrlResolved = false;
31
+ function getGatewayUrl() {
32
+ if (!_gatewayUrlResolved) {
33
+ const wspaceUrl = process.env["WSPACE_INT_GATEWAY_URL"];
34
+ const globalUrl = process.env["GLOBAL_INT_GATEWAY_URL"];
35
+ if (wspaceUrl) {
36
+ _gatewayUrl = wspaceUrl;
37
+ _gatewayLayer = "wspace";
38
+ } else if (globalUrl) {
39
+ _gatewayUrl = globalUrl;
40
+ _gatewayLayer = "global";
41
+ } else {
42
+ _gatewayUrl = void 0;
43
+ _gatewayLayer = void 0;
44
+ }
45
+ _gatewayUrlResolved = true;
46
+ if (_gatewayUrl) {
47
+ logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);
48
+ } else {
49
+ logger.debug("[trackOperation] No gateway URL configured \u2014 running in stub mode");
50
+ }
51
+ }
52
+ return _gatewayUrl;
53
+ }
54
+ __name(getGatewayUrl, "getGatewayUrl");
55
+ function getGatewayLayer() {
56
+ return _gatewayLayer ?? "wspace";
57
+ }
58
+ __name(getGatewayLayer, "getGatewayLayer");
59
+ var LOG_ACTIVITY_MUTATION = (
60
+ /* GraphQL */
61
+ `
62
+ mutation RecordActivity($input: RecordActivityInput!) {
63
+ recordActivity(input: $input) {
64
+ id
65
+ }
66
+ }
67
+ `
68
+ );
69
+ function deriveResource(options) {
70
+ const explicit = options.activityOptions?.resourceType ?? options.resourceType;
71
+ if (explicit && explicit.trim().length > 0) return explicit;
72
+ const op = options.operationName;
73
+ if (op && op.trim().length > 0) {
74
+ const [head] = op.split(".");
75
+ if (head && head.trim().length > 0) return head;
76
+ }
77
+ return "unknown";
78
+ }
79
+ __name(deriveResource, "deriveResource");
80
+ function buildActivityInput(options, layer) {
81
+ const actOpts = options.activityOptions;
82
+ const action = actOpts?.activityType ?? options.action ?? options.operationName ?? "unknown";
83
+ const description = actOpts?.description ?? `${options.operationName ?? "operation"} executed`;
84
+ const resourceType = actOpts?.resourceType ?? options.resourceType;
85
+ const resourceId = actOpts?.resourceId ?? options.resourceId;
86
+ const workspaceId = actOpts?.workspaceId ?? options.workspaceId;
87
+ const metadata = {
88
+ ...actOpts?.metadata,
89
+ success: options.success ?? true,
90
+ ...options.operationName ? {
91
+ operationName: options.operationName
92
+ } : {},
93
+ ...options.errorMessage ? {
94
+ errorMessage: options.errorMessage
95
+ } : {}
96
+ };
97
+ const input = layer === "global" ? {
98
+ action,
99
+ // Required (non-nullable) on global-activity-svc.
100
+ resource: deriveResource(options),
101
+ description,
102
+ resourceType,
103
+ resourceId,
104
+ userId: options.userId,
105
+ actorId: options.userId,
106
+ tenantId: options.tenantId,
107
+ workspaceId,
108
+ metadata
109
+ } : {
110
+ action,
111
+ description,
112
+ resourceType,
113
+ resourceId,
114
+ workspaceId,
115
+ targetUserId: actOpts?.targetUserId,
116
+ teamId: actOpts?.teamId,
117
+ productId: options.productId,
118
+ success: options.success ?? true,
119
+ ...options.errorMessage ? {
120
+ errorMessage: options.errorMessage
121
+ } : {},
122
+ metadata: {
123
+ ...metadata,
124
+ userId: options.userId
125
+ }
126
+ };
127
+ input["dedupeKey"] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;
128
+ return input;
129
+ }
130
+ __name(buildActivityInput, "buildActivityInput");
131
+ var ACTIVITY_ATTEMPT_TIMEOUT_MS = 5e3;
132
+ var DEFAULT_ACTIVITY_RETRY_DELAYS_MS = [
133
+ 1e3,
134
+ 3e3,
135
+ 8e3
136
+ ];
137
+ var activityRetryDelaysMs = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;
138
+ var RETRYABLE_HTTP_STATUSES = /* @__PURE__ */ new Set([
139
+ 408,
140
+ 425,
141
+ 429,
142
+ 500,
143
+ 502,
144
+ 503,
145
+ 504
146
+ ]);
147
+ var RETRYABLE_GRAPHQL_CODES = /* @__PURE__ */ new Set([
148
+ "INTERNAL_SERVER_ERROR",
149
+ "SERVICE_UNAVAILABLE",
150
+ "AUTH_SERVICE_UNAVAILABLE",
151
+ "DOWNSTREAM_SERVICE_ERROR",
152
+ "GATEWAY_TIMEOUT"
153
+ ]);
154
+ function classifyGraphQLErrors(errors) {
155
+ const detail = errors.map((e) => e?.message ?? "unknown error").join("; ").slice(0, 500);
156
+ const transient = errors.every((e) => {
157
+ const code = e?.extensions?.code;
158
+ return typeof code === "string" && RETRYABLE_GRAPHQL_CODES.has(code);
159
+ });
160
+ return transient ? {
161
+ kind: "transient",
162
+ detail
163
+ } : {
164
+ kind: "rejected",
165
+ detail
166
+ };
167
+ }
168
+ __name(classifyGraphQLErrors, "classifyGraphQLErrors");
169
+ async function attemptActivityDelivery(gatewayUrl, headers, body) {
170
+ try {
171
+ const response = await fetch(gatewayUrl, {
172
+ method: "POST",
173
+ headers,
174
+ body,
175
+ signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS)
176
+ });
177
+ if (!response.ok) {
178
+ const detail = `HTTP ${response.status}`;
179
+ return RETRYABLE_HTTP_STATUSES.has(response.status) ? {
180
+ kind: "transient",
181
+ detail
182
+ } : {
183
+ kind: "rejected",
184
+ detail
185
+ };
186
+ }
187
+ const parsed = await response.json().catch(() => void 0);
188
+ const errors = parsed?.errors;
189
+ if (errors && errors.length > 0) {
190
+ return classifyGraphQLErrors(errors);
191
+ }
192
+ return {
193
+ kind: "delivered"
194
+ };
195
+ } catch (err) {
196
+ return {
197
+ kind: "transient",
198
+ detail: err.message
199
+ };
200
+ }
201
+ }
202
+ __name(attemptActivityDelivery, "attemptActivityDelivery");
203
+ async function fireActivityLog(gatewayUrl, options, layer) {
204
+ try {
205
+ const actOpts = options.activityOptions;
206
+ const input = buildActivityInput(options, layer);
207
+ for (const key of Object.keys(input)) {
208
+ if (input[key] === void 0) delete input[key];
209
+ }
210
+ const headers = {
211
+ "Content-Type": "application/json"
212
+ };
213
+ if (options.userId) {
214
+ headers["x-actor-id"] = options.userId;
215
+ headers["x-actor-type"] = "service";
216
+ }
217
+ if (options.workspaceId ?? actOpts?.workspaceId) {
218
+ headers["x-workspace-id"] = options.workspaceId ?? actOpts?.workspaceId;
219
+ }
220
+ const operation = options.operationName ?? "operation";
221
+ const body = JSON.stringify({
222
+ query: LOG_ACTIVITY_MUTATION,
223
+ variables: {
224
+ input
225
+ }
226
+ });
227
+ const maxAttempts = activityRetryDelaysMs.length + 1;
228
+ for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
229
+ const outcome = await attemptActivityDelivery(gatewayUrl, headers, body);
230
+ if (outcome.kind === "delivered") {
231
+ if (attempt > 1) {
232
+ logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);
233
+ }
234
+ return;
235
+ }
236
+ if (outcome.kind === "rejected") {
237
+ logger.error(`[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for "${operation}": ${outcome.detail}`);
238
+ return;
239
+ }
240
+ const delay = activityRetryDelaysMs[attempt - 1];
241
+ if (delay === void 0) {
242
+ logger.error(`[trackOperation] Activity log failed after ${attempt} attempts for "${operation}": ${outcome.detail}`);
243
+ return;
244
+ }
245
+ logger.warn(`[trackOperation] Activity log attempt ${attempt} failed for "${operation}" (${outcome.detail}); retrying in ${delay}ms`);
246
+ await new Promise((resolve) => setTimeout(resolve, delay));
247
+ }
248
+ } catch (err) {
249
+ logger.warn(`[trackOperation] Activity log failed: ${err.message}`);
250
+ }
251
+ }
252
+ __name(fireActivityLog, "fireActivityLog");
253
+ var UnifiedTrackerStub = class _UnifiedTrackerStub {
254
+ static {
255
+ __name(this, "UnifiedTrackerStub");
256
+ }
257
+ static instance;
258
+ static getInstance() {
259
+ if (!_UnifiedTrackerStub.instance) {
260
+ _UnifiedTrackerStub.instance = new _UnifiedTrackerStub();
261
+ }
262
+ return _UnifiedTrackerStub.instance;
263
+ }
264
+ async track(event) {
265
+ markExplicitActivity();
266
+ const gatewayUrl = getGatewayUrl();
267
+ if (gatewayUrl) {
268
+ await fireActivityLog(gatewayUrl, {
269
+ operationName: event.eventType,
270
+ userId: event.userId,
271
+ workspaceId: event.workspaceId,
272
+ resourceType: event.entityType,
273
+ resourceId: event.entityId,
274
+ activityOptions: {
275
+ activityType: event.eventType,
276
+ metadata: event.metadata,
277
+ workspaceId: event.workspaceId,
278
+ resourceType: event.entityType,
279
+ resourceId: event.entityId,
280
+ enabled: true
281
+ }
282
+ }, getGatewayLayer());
283
+ } else {
284
+ logger.debug("[UnifiedTracker:Stub]", event.eventType, event.entityType, event.entityId);
285
+ }
286
+ }
287
+ async trackBatch(events) {
288
+ for (const event of events) {
289
+ await this.track(event);
290
+ }
291
+ }
292
+ };
293
+ var trackerStub = UnifiedTrackerStub.getInstance();
294
+ async function trackOperation(options) {
295
+ const { operationName, userId, success = true } = options;
296
+ const gatewayUrl = getGatewayUrl();
297
+ const activityEnabled = options.activityOptions?.enabled !== false;
298
+ if (activityEnabled) markExplicitActivity();
299
+ if (!gatewayUrl) {
300
+ logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);
301
+ return true;
302
+ }
303
+ if (activityEnabled) {
304
+ void fireActivityLog(gatewayUrl, options, getGatewayLayer());
305
+ } else {
306
+ logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);
307
+ }
308
+ return true;
309
+ }
310
+ __name(trackOperation, "trackOperation");
311
+ function createProductTracker(productId, userId, billingAccountId, defaultContext) {
312
+ return {
313
+ async track(operationName, additionalOptions) {
314
+ return trackOperation({
315
+ ...defaultContext,
316
+ productId,
317
+ operationName,
318
+ userId,
319
+ ...additionalOptions
320
+ });
321
+ },
322
+ async freeUp(operationName, additionalOptions) {
323
+ return trackOperation({
324
+ ...defaultContext,
325
+ productId,
326
+ operationName,
327
+ userId,
328
+ ...additionalOptions,
329
+ activityOptions: {
330
+ ...defaultContext?.activityOptions,
331
+ ...additionalOptions?.activityOptions,
332
+ activityType: "free_up"
333
+ }
334
+ });
335
+ },
336
+ async trackActivityOnly(operationName, additionalOptions) {
337
+ return trackOperation({
338
+ ...defaultContext,
339
+ productId,
340
+ operationName,
341
+ userId,
342
+ ...additionalOptions,
343
+ activityOptions: {
344
+ ...defaultContext?.activityOptions,
345
+ ...additionalOptions?.activityOptions,
346
+ enabled: true
347
+ },
348
+ usageOptions: {
349
+ enabled: false
350
+ }
351
+ });
352
+ },
353
+ async trackUsageOnly(operationName, additionalOptions) {
354
+ return trackOperation({
355
+ ...defaultContext,
356
+ productId,
357
+ operationName,
358
+ userId,
359
+ ...additionalOptions,
360
+ activityOptions: {
361
+ enabled: false
362
+ },
363
+ usageOptions: {
364
+ ...defaultContext?.usageOptions,
365
+ ...additionalOptions?.usageOptions,
366
+ enabled: true
367
+ }
368
+ });
369
+ },
370
+ async trackCustom(operationName, additionalOptions) {
371
+ return trackOperation({
372
+ ...defaultContext,
373
+ productId,
374
+ operationName,
375
+ userId,
376
+ ...additionalOptions
377
+ });
378
+ },
379
+ productId,
380
+ userId,
381
+ billingAccountId,
382
+ defaultContext
383
+ };
384
+ }
385
+ __name(createProductTracker, "createProductTracker");
386
+ var UNIFIED_TRACKER_CONSTANTS = {
387
+ DEFAULT_PRODUCT_ID: "module",
388
+ OPERATIONS: {},
389
+ PRODUCTS: {}
390
+ };
391
+
392
+ export { UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, createExplicitActivityScope, createProductTracker, markExplicitActivity, runInExplicitActivityScope, suppressMutationAudit, trackOperation, trackerStub };
393
+ //# sourceMappingURL=chunk-GRGTUP44.js.map
394
+ //# sourceMappingURL=chunk-GRGTUP44.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activity/explicit-activity-scope.ts","../src/tracker/stub.ts"],"names":["scopeStorage","AsyncLocalStorage","createExplicitActivityScope","explicitCount","suppressed","runInExplicitActivityScope","scope","fn","run","markExplicitActivity","getStore","suppressMutationAudit","_gatewayUrl","_gatewayLayer","_gatewayUrlResolved","getGatewayUrl","wspaceUrl","process","env","globalUrl","undefined","logger","info","debug","getGatewayLayer","LOG_ACTIVITY_MUTATION","deriveResource","options","explicit","activityOptions","resourceType","trim","length","op","operationName","head","split","buildActivityInput","layer","actOpts","action","activityType","description","resourceId","workspaceId","metadata","success","errorMessage","input","resource","userId","actorId","tenantId","targetUserId","teamId","productId","dedupeKey","randomUUID","ACTIVITY_ATTEMPT_TIMEOUT_MS","DEFAULT_ACTIVITY_RETRY_DELAYS_MS","activityRetryDelaysMs","RETRYABLE_HTTP_STATUSES","Set","RETRYABLE_GRAPHQL_CODES","classifyGraphQLErrors","errors","detail","map","e","message","join","slice","transient","every","code","extensions","has","kind","attemptActivityDelivery","gatewayUrl","headers","body","response","fetch","method","signal","AbortSignal","timeout","ok","status","parsed","json","catch","err","fireActivityLog","key","Object","keys","operation","JSON","stringify","query","variables","maxAttempts","attempt","outcome","error","delay","warn","Promise","resolve","setTimeout","UnifiedTrackerStub","instance","getInstance","track","event","eventType","entityType","entityId","enabled","trackBatch","events","trackerStub","trackOperation","activityEnabled","createProductTracker","billingAccountId","defaultContext","additionalOptions","freeUp","trackActivityOnly","usageOptions","trackUsageOnly","trackCustom","UNIFIED_TRACKER_CONSTANTS","DEFAULT_PRODUCT_ID","OPERATIONS","PRODUCTS"],"mappings":";;;;;AA6BA,IAAMA,YAAAA,GAAe,IAAIC,iBAAAA,EAAAA;AAGlB,SAASC,2BAAAA,GAAAA;AACd,EAAA,OAAO;IAAEC,aAAAA,EAAe,CAAA;IA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ACAL,IAAAA,MAAAA;AACA6E,IAAAA,gBAAAA;AACAC,IAAAA;AACF,GAAA;AACF;AAlEgBF,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA;AAuET,IAAMS,yBAAAA,GAA4B;EACvCC,kBAAAA,EAAoB,QAAA;AACpBC,EAAAA,UAAAA,EAAY,EAAC;AACbC,EAAAA,QAAAA,EAAU;AACZ","file":"chunk-GRGTUP44.js","sourcesContent":["/**\n * Explicit-activity scope\n *\n * Lets the mutation-audit backstop (`createMutationAuditPlugin` in\n * `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an\n * activity row through an explicit call (`trackOperation`, `trackerStub.track`,\n * `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it\n * did, the backstop skips its generic `graphql.mutation` row so the activity feed\n * never carries two rows for one mutation.\n *\n * The scope is entered with `AsyncLocalStorage.run()` around the operation's\n * execute function. `run()` (unlike `enterWith()`) propagates through every\n * promise continuation started inside it, including fire-and-forget calls made\n * by resolvers, so concurrent requests never see each other's marks.\n *\n * Outside a scope (background jobs, event consumers, REST handlers) every\n * function here is a no-op.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/** Per-operation record of explicit activity writes. */\nexport interface ExplicitActivityScope {\n /** Number of explicit activity writes made while the operation executed. */\n explicitCount: number;\n /** True once `suppressMutationAudit()` was called for this operation. */\n suppressed: boolean;\n}\n\nconst scopeStorage = new AsyncLocalStorage<ExplicitActivityScope>();\n\n/** Create a fresh, unmarked scope. */\nexport function createExplicitActivityScope(): ExplicitActivityScope {\n return { explicitCount: 0, suppressed: false };\n}\n\n/** Run `fn` with `scope` as the active explicit-activity scope. */\nexport function runInExplicitActivityScope<T>(scope: ExplicitActivityScope, fn: () => T): T {\n return scopeStorage.run(scope, fn);\n}\n\n/** The active scope, or undefined outside a GraphQL operation that mounts the backstop. */\nexport function getExplicitActivityScope(): ExplicitActivityScope | undefined {\n return scopeStorage.getStore();\n}\n\n/**\n * Record that an explicit activity write happened in the current operation.\n * Called by the SDK's own activity writers; services never need to call it.\n */\nexport function markExplicitActivity(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.explicitCount += 1;\n}\n\n/**\n * Tell the mutation-audit backstop not to write its generic row for the current\n * operation.\n *\n * Use it in a resolver whose audit trail goes through a path the SDK cannot see\n * (for example a direct call to the activity subgraph), or for a mutation that\n * must deliberately leave no activity row. Has no effect outside an operation\n * that mounts the backstop.\n */\nexport function suppressMutationAudit(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.suppressed = true;\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';\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 * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\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 * Resolve the internal gateway URL from environment.\n * Workspace services use WSPACE_INT_GATEWAY_URL, global services use GLOBAL_INT_GATEWAY_URL.\n * Falls back to undefined (stub mode) if neither 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\n if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else if (globalUrl) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\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\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 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 }\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 };\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' }\n | { kind: 'rejected'; detail: string }\n | { 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 const body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\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 (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"]}