@burdenoff/be-sdk 2026.1110.3 → 2026.1110.4
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/dist/activity/index.d.ts +165 -0
- package/dist/activity/index.js +389 -0
- package/dist/activity/index.js.map +1 -0
- package/dist/ai-credits/index.js +1 -1
- package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
- package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
- package/dist/auth/index.d.ts +1 -1
- package/dist/auth/index.js +1 -1
- package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
- package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
- package/dist/bootstrap/index.d.ts +74 -0
- package/dist/bootstrap/index.js +282 -0
- package/dist/bootstrap/index.js.map +1 -0
- package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
- package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
- package/dist/context/index.d.ts +35 -0
- package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
- package/dist/context/index.js.map +1 -0
- package/dist/database/index.js +1 -1
- package/dist/event-queue/index.d.ts +1 -1
- package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
- package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
- package/dist/export/index.js +1 -1
- package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
- package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
- package/dist/feature-flags/index.js +1 -1
- package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
- package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
- package/dist/files/index.js +1 -1
- package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
- package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
- package/dist/gateway/index.js +2 -2
- package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
- package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
- package/dist/graph/index.d.ts +1 -1
- package/dist/graph/index.js +1 -1
- package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
- package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
- package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
- package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
- package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
- package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
- package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
- package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
- package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
- package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
- package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
- package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
- package/dist/index-cmR9k9ga.d.ts +26 -0
- package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
- package/dist/index.d.ts +19 -479
- package/dist/index.js +22 -1492
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +1 -1
- package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
- package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
- package/dist/instrumentation/index.d.ts +2 -2
- package/dist/logger/index.d.ts +1 -1
- package/dist/notifications/index.d.ts +1 -1
- package/dist/notifications/index.js +1 -1
- package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
- package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
- package/dist/payments/index.d.ts +144 -0
- package/dist/payments/index.js +404 -0
- package/dist/payments/index.js.map +1 -0
- package/dist/rate-limit-CBrK_U5H.js +142 -0
- package/dist/rate-limit-CBrK_U5H.js.map +1 -0
- package/dist/rbac/index.d.ts +1 -1
- package/dist/rbac/index.js +1 -1
- package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
- package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
- package/dist/resource-caps/index.d.ts +1 -1
- package/dist/search/index.d.ts +112 -0
- package/dist/search/index.js +266 -0
- package/dist/search/index.js.map +1 -0
- package/dist/security/index.d.ts +2 -0
- package/dist/security/index.js +4 -0
- package/dist/security/index.js.map +1 -0
- package/dist/security/rate-limit/index.d.ts +2 -0
- package/dist/security/rate-limit/index.js +4 -0
- package/dist/security/rate-limit/index.js.map +1 -0
- package/dist/server/index.js +3 -2
- package/dist/server/index.js.map +1 -1
- package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
- package/dist/stub-BUnfMiAS.js.map +1 -0
- package/dist/tags/index.js +1 -1
- package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
- package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
- package/dist/telemetry/index.d.ts +2 -2
- package/dist/tracker/index.d.ts +2 -2
- package/dist/tracker/index.js +5 -3
- package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
- package/dist/tracker-PQztSlhJ.js.map +1 -0
- package/dist/translation/index.d.ts +120 -0
- package/dist/translation/index.js +573 -0
- package/dist/translation/index.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
- package/dist/types/index.js.map +1 -0
- package/dist/usage/index.d.ts +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
- package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
- package/package.json +1 -1
- package/dist/context-CZnXf2yb.js.map +0 -1
- package/dist/stub-BqwKn4eh.js.map +0 -1
- package/dist/tracker-BQVoEFUo.js.map +0 -1
- package/dist/types-Cj2RWXbz.js.map +0 -1
|
@@ -1,61 +1,8 @@
|
|
|
1
1
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
2
|
+
import { n as markExplicitActivity } from "./explicit-activity-scope-DikJ7NAE.js";
|
|
2
3
|
import { a as getScopedWorkspaceContext, o as getWorkspaceContext } from "./workspace-extension-COrC0dYi.js";
|
|
3
|
-
import { AsyncLocalStorage } from "node:async_hooks";
|
|
4
4
|
import { randomUUID } from "node:crypto";
|
|
5
5
|
|
|
6
|
-
// src/activity/explicit-activity-scope.ts
|
|
7
|
-
/**
|
|
8
|
-
* Explicit-activity scope
|
|
9
|
-
*
|
|
10
|
-
* Lets the mutation-audit backstop (`createMutationAuditPlugin` in
|
|
11
|
-
* `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an
|
|
12
|
-
* activity row through an explicit call (`trackOperation`, `trackerStub.track`,
|
|
13
|
-
* `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it
|
|
14
|
-
* did, the backstop skips its generic `graphql.mutation` row so the activity feed
|
|
15
|
-
* never carries two rows for one mutation.
|
|
16
|
-
*
|
|
17
|
-
* The scope is entered with `AsyncLocalStorage.run()` around the operation's
|
|
18
|
-
* execute function. `run()` (unlike `enterWith()`) propagates through every
|
|
19
|
-
* promise continuation started inside it, including fire-and-forget calls made
|
|
20
|
-
* by resolvers, so concurrent requests never see each other's marks.
|
|
21
|
-
*
|
|
22
|
-
* Outside a scope (background jobs, event consumers, REST handlers) every
|
|
23
|
-
* function here is a no-op.
|
|
24
|
-
*/
|
|
25
|
-
const scopeStorage = new AsyncLocalStorage();
|
|
26
|
-
/** Create a fresh, unmarked scope. */
|
|
27
|
-
function createExplicitActivityScope() {
|
|
28
|
-
return {
|
|
29
|
-
explicitCount: 0,
|
|
30
|
-
suppressed: false
|
|
31
|
-
};
|
|
32
|
-
}
|
|
33
|
-
/** Run `fn` with `scope` as the active explicit-activity scope. */
|
|
34
|
-
function runInExplicitActivityScope(scope, fn) {
|
|
35
|
-
return scopeStorage.run(scope, fn);
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Record that an explicit activity write happened in the current operation.
|
|
39
|
-
* Called by the SDK's own activity writers; services never need to call it.
|
|
40
|
-
*/
|
|
41
|
-
function markExplicitActivity() {
|
|
42
|
-
const scope = scopeStorage.getStore();
|
|
43
|
-
if (scope) scope.explicitCount += 1;
|
|
44
|
-
}
|
|
45
|
-
/**
|
|
46
|
-
* Tell the mutation-audit backstop not to write its generic row for the current
|
|
47
|
-
* operation.
|
|
48
|
-
*
|
|
49
|
-
* Use it in a resolver whose audit trail goes through a path the SDK cannot see
|
|
50
|
-
* (for example a direct call to the activity subgraph), or for a mutation that
|
|
51
|
-
* must deliberately leave no activity row. Has no effect outside an operation
|
|
52
|
-
* that mounts the backstop.
|
|
53
|
-
*/
|
|
54
|
-
function suppressMutationAudit() {
|
|
55
|
-
const scope = scopeStorage.getStore();
|
|
56
|
-
if (scope) scope.suppressed = true;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
6
|
// src/activity/assistant-session.ts
|
|
60
7
|
/**
|
|
61
8
|
* Assistant-session attribution (BOFF-9649)
|
|
@@ -626,5 +573,5 @@ const UNIFIED_TRACKER_CONSTANTS = {
|
|
|
626
573
|
PRODUCTS: {}
|
|
627
574
|
};
|
|
628
575
|
|
|
629
|
-
export {
|
|
630
|
-
//# sourceMappingURL=stub-
|
|
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-BUnfMiAS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stub-BUnfMiAS.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: {}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AC;EACH;EACA,MAAM,kBAAkB,eAAe,mBAAqC;GAC1E,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB;KAAE,GAAG,gBAAgB;KAAiB,GAAG,mBAAmB;KAAiB,SAAS;IAAK;IAC5G,cAAc,EAAE,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"}
|
package/dist/tags/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as buildEntityTagsSdl, c as slugifyTagKey, d as entityTagsTypeNames, f as ENTITY_TAGS_GRAPHQL_CODES, g as TAG_ASSIGNMENT_SOURCES, h as TAG_ACTOR_TYPES, i as UNIVERSAL_TAG_STUB_SDL, l as assertTagPrefix, m as isEntityTagsError, n as createEntityTagResolvers, o as TagsGatewayAdapter, p as EntityTagsError, r as defaultTagActor, s as mapTagAssignment, u as entityTagsFieldNames } from "../tags-
|
|
1
|
+
import { a as buildEntityTagsSdl, c as slugifyTagKey, d as entityTagsTypeNames, f as ENTITY_TAGS_GRAPHQL_CODES, g as TAG_ASSIGNMENT_SOURCES, h as TAG_ACTOR_TYPES, i as UNIVERSAL_TAG_STUB_SDL, l as assertTagPrefix, m as isEntityTagsError, n as createEntityTagResolvers, o as TagsGatewayAdapter, p as EntityTagsError, r as defaultTagActor, s as mapTagAssignment, u as entityTagsFieldNames } from "../tags-CbijgoqR.js";
|
|
2
2
|
|
|
3
3
|
export { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, TagsGatewayAdapter, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey };
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -442,7 +442,7 @@ var TagsGatewayAdapter = class {
|
|
|
442
442
|
this.clientPromise = (async () => {
|
|
443
443
|
if (typeof option === "function") return option();
|
|
444
444
|
if (option) return option;
|
|
445
|
-
const gateway = await import("./client-
|
|
445
|
+
const gateway = await import("./client-sAJTrb4i.js").then((n) => n.n);
|
|
446
446
|
if (this.serviceName) return new gateway.GatewayClient({
|
|
447
447
|
layer: "wspace",
|
|
448
448
|
serviceName: this.serviceName,
|
|
@@ -865,4 +865,4 @@ var tags_exports = /* @__PURE__ */ __exportAll({
|
|
|
865
865
|
});
|
|
866
866
|
|
|
867
867
|
export { buildEntityTagsSdl as a, slugifyTagKey as c, entityTagsTypeNames as d, ENTITY_TAGS_GRAPHQL_CODES as f, TAG_ASSIGNMENT_SOURCES as g, TAG_ACTOR_TYPES as h, UNIVERSAL_TAG_STUB_SDL as i, assertTagPrefix as l, isEntityTagsError as m, createEntityTagResolvers as n, TagsGatewayAdapter as o, EntityTagsError as p, defaultTagActor as r, mapTagAssignment as s, tags_exports as t, entityTagsFieldNames as u };
|
|
868
|
-
//# sourceMappingURL=tags-
|
|
868
|
+
//# sourceMappingURL=tags-CbijgoqR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tags-B5xpbgsk.js","names":[],"sources":["../src/tags/types.ts","../src/tags/errors.ts","../src/tags/naming.ts","../src/tags/adapter.ts","../src/tags/sdl.ts","../src/tags/resolvers.ts","../src/tags/index.ts"],"sourcesContent":["/**\n * Entity tags — shared types.\n *\n * Every product service that lets users tag its own entities talks to the one\n * polymorphic tag owner, **wspace-tags-svc**, through the internal workspace\n * gateway. These types describe both the tags-svc wire shape and the\n * projection the service publishes in its own subgraph.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const TAG_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type TagActorType = (typeof TAG_ACTOR_TYPES)[number];\n\n/** The caller a tag operation runs on behalf of (forwarded as `x-actor-*` / `x-workspace-id`). */\nexport interface TagActor {\n /** `x-actor-id` — the user/app/service id the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — tags-svc scopes every vocabulary, tag and assignment by it. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: TagActorType;\n}\n\n/** `AssignmentSource` enum members accepted by wspace-tags-svc. */\nexport const TAG_ASSIGNMENT_SOURCES = ['AUTOMATIC', 'COMPUTED', 'IMPORTED', 'INHERITED', 'MANUAL', 'MIGRATED'] as const;\n\nexport type TagAssignmentSource = (typeof TAG_ASSIGNMENT_SOURCES)[number];\n\n/** `UniversalTagAssignment` as it comes back over the wire from wspace-tags-svc. */\nexport interface RawTagAssignment {\n id: string;\n tagId: string;\n entityType: string;\n entityId: string;\n source: string;\n assignedById?: string | null;\n createdAt?: string | null;\n validFrom?: string | null;\n validTo?: string | null;\n metadata?: unknown;\n tag?: { id: string; key?: string | null; label?: string | null; color?: string | null } | null;\n}\n\n/** Inline (non-federated) tag projection so clients render labels in one round-trip. */\nexport interface EntityTagInfo {\n id: string;\n key: string | null;\n label: string | null;\n color: string | null;\n}\n\n/** A tag assigned to one of the service's entities, in the shape its subgraph publishes. */\nexport interface EntityTagAssignment {\n id: string;\n tagId: string;\n /** Federated `UniversalTag` reference — only `id` resolves locally; tags-svc owns the rest. */\n tag: { id: string } | null;\n tagInfo: EntityTagInfo | null;\n entityType: string;\n entityId: string;\n source: string;\n assignedBy: string | null;\n assignedAt: Date | null;\n validFrom: Date | null;\n validTo: Date | null;\n metadata: unknown;\n}\n\n/** An assignable workspace tag. */\nexport interface AvailableTag {\n id: string;\n key: string;\n label: string;\n color: string | null;\n}\n\n/** Minimal vocabulary reference returned by tags-svc. */\nexport interface TagVocabularyRef {\n id: string;\n key: string;\n name: string;\n}\n\n/** The workspace-scoped vocabulary that inline-created tags land in. */\nexport interface TagVocabularyConfig {\n /** Stable vocabulary key, e.g. `fluidgrids-tags`. Looked up first, created when missing. */\n key: string;\n /** Display name used when the vocabulary has to be created. */\n name: string;\n description?: string;\n /**\n * A pinned vocabulary id. Used when it exists in the caller's workspace; ignored\n * (falls back to `key`) when it does not, so one id never leaks across workspaces.\n */\n id?: string;\n}\n\n/** Options for {@link TagsGatewayAdapter.tagEntity}. */\nexport interface TagEntityOptions {\n tagId: string;\n source?: string | null;\n validFrom?: Date | null;\n validTo?: Date | null;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.createTag}. */\nexport interface CreateTagOptions {\n label: string;\n color?: string | null;\n /**\n * Target vocabulary. `undefined`/`null` resolves (or creates) the adapter's default\n * vocabulary. Any explicit value, even an empty string, is sent as-is so an unknown id\n * surfaces as a tags-svc error instead of silently misfiling the tag.\n */\n vocabularyId?: string | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.findEntityIdsByTags}. */\nexport interface FindEntitiesByTagsOptions {\n /** `true` = entity must carry every tag; `false` (default) = any of them. */\n matchAll?: boolean;\n /** Clamped to 1..200; default 50. */\n limit?: number | null;\n cursor?: string | null;\n}\n\n/** One page of entity ids carrying the requested tags. */\nexport interface TaggedEntityPage {\n entityIds: string[];\n total: number;\n hasMore: boolean;\n nextCursor: string | null;\n}\n\n/** The slice of the be-sdk `GatewayClient` the adapter needs (lets tests pass a fake). */\nexport interface TagsGatewayClient {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n","/**\n * Entity tags — error type.\n *\n * Services map {@link EntityTagsError} onto their own i18n GraphQL errors (see the\n * `invalidEntityTypeError` / `mapError` hooks of `createEntityTagResolvers`); the\n * `code` is stable so that mapping never has to parse messages.\n */\n\nexport type EntityTagsErrorCode =\n /** `entityType` is not one the service registered as taggable. */\n | 'INVALID_ENTITY_TYPE'\n /** `source` is not a tags-svc `AssignmentSource`. */\n | 'INVALID_SOURCE'\n /** A required argument (entity id, tag id, label, …) is empty. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — tags are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** tags-svc answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The adapter / resolver factory was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link EntityTagsErrorCode} should surface as. */\nexport const ENTITY_TAGS_GRAPHQL_CODES: Record<EntityTagsErrorCode, string> = {\n INVALID_ENTITY_TYPE: 'BAD_USER_INPUT',\n INVALID_SOURCE: 'BAD_USER_INPUT',\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\nexport class EntityTagsError extends Error {\n readonly code: EntityTagsErrorCode;\n readonly details: Record<string, unknown>;\n\n constructor(code: EntityTagsErrorCode, message: string, details: Record<string, unknown> = {}) {\n super(message);\n this.name = 'EntityTagsError';\n this.code = code;\n this.details = details;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return ENTITY_TAGS_GRAPHQL_CODES[this.code];\n }\n}\n\nexport function isEntityTagsError(error: unknown): error is EntityTagsError {\n return error instanceof EntityTagsError;\n}\n","/**\n * Entity tags — GraphQL naming.\n *\n * Every service in the workspaces supergraph publishes its own tag surface, so\n * every type and root field must be unique to the service: unprefixed\n * `EntityTagAssignment` / `AvailableTag` / `EntityTagInfo` declared by two\n * subgraphs are non-shareable value types and break composition. The SDL\n * builder and the resolver factory both derive their names from here, so a\n * service's schema and its resolver map can never drift apart.\n */\nimport { EntityTagsError } from './errors.js';\n\nconst PREFIX_PATTERN = /^[A-Z][A-Za-z0-9]*$/;\n\n/** Root field names, derived from the service prefix (`Fluidgrids` → `fluidgridsEntityTags`, …). */\nexport interface EntityTagsFieldNames {\n entityTags: string;\n searchTags: string;\n availableTags: string;\n entitiesByTags: string;\n tagEntity: string;\n untagEntity: string;\n replaceEntityTags: string;\n createTag: string;\n}\n\n/** Type / input names the tag surface declares. */\nexport interface EntityTagsTypeNames {\n getEntityTagsInput: string;\n tagEntityInput: string;\n untagEntityInput: string;\n replaceEntityTagsInput: string;\n createTagInput: string;\n entitiesByTagsInput: string;\n tagInfo: string;\n tagAssignment: string;\n availableTag: string;\n taggedEntityPage: string;\n}\n\nexport function assertTagPrefix(prefix: string): void {\n if (!PREFIX_PATTERN.test(prefix)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags prefix must be PascalCase ([A-Z][A-Za-z0-9]*), got \"${prefix}\"`,\n { prefix }\n );\n }\n}\n\nfunction lowerFirst(value: string): string {\n return value.charAt(0).toLowerCase() + value.slice(1);\n}\n\nexport function entityTagsFieldNames(prefix: string): EntityTagsFieldNames {\n assertTagPrefix(prefix);\n const camel = lowerFirst(prefix);\n return {\n entityTags: `${camel}EntityTags`,\n searchTags: `search${prefix}Tags`,\n availableTags: `available${prefix}Tags`,\n entitiesByTags: `${camel}EntitiesByTags`,\n tagEntity: `tag${prefix}Entity`,\n untagEntity: `untag${prefix}Entity`,\n replaceEntityTags: `replace${prefix}EntityTags`,\n createTag: `create${prefix}Tag`,\n };\n}\n\n/**\n * Type names for `prefix`. Defaults carry the prefix everywhere (the FluidGrids\n * convention). `overrides` exists for services that already published legacy\n * names (VibeControls ships `EntityTagAssignment`, `TagEntityInput`, …) and must\n * keep them for existing clients' fragments.\n */\nexport function entityTagsTypeNames(prefix: string, overrides: Partial<EntityTagsTypeNames> = {}): EntityTagsTypeNames {\n assertTagPrefix(prefix);\n const names: EntityTagsTypeNames = {\n getEntityTagsInput: `Get${prefix}EntityTagsInput`,\n tagEntityInput: `Tag${prefix}EntityInput`,\n untagEntityInput: `Untag${prefix}EntityInput`,\n replaceEntityTagsInput: `Replace${prefix}EntityTagsInput`,\n createTagInput: `Create${prefix}TagInput`,\n entitiesByTagsInput: `${prefix}EntitiesByTagsInput`,\n tagInfo: `${prefix}TagInfo`,\n tagAssignment: `${prefix}TagAssignment`,\n availableTag: `${prefix}AvailableTag`,\n taggedEntityPage: `${prefix}TaggedEntityPage`,\n ...overrides,\n };\n\n const seen = new Map<string, string>();\n for (const [role, name] of Object.entries(names)) {\n if (!PREFIX_PATTERN.test(name)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags type name for ${role} is not a valid type name`, {\n role,\n name,\n });\n }\n const clash = seen.get(name);\n if (clash) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags type name \"${name}\" is used for both ${clash} and ${role}`,\n {\n name,\n }\n );\n }\n seen.set(name, role);\n }\n return names;\n}\n","/**\n * TagsGatewayAdapter — one implementation of \"tag my entities\" for every service.\n *\n * Thirteen services carried their own copy of this adapter (VibeControls,\n * FluidGrids, BigConsole, files, integrations, …) and the copies drifted:\n * argument order (`userId, workspaceId` vs `workspaceId, userId`), a hard-coded\n * `x-actor-type: user`, `response.data!` non-null assertions, no source\n * validation. This class is the lifted, configurable version: a service\n * supplies its taggable entity types, its default vocabulary and (optionally)\n * the gateway client, and gets the full tag surface.\n *\n * All calls are same-layer M2M to wspace-tags-svc through the internal\n * workspace gateway (`GatewayClient.internalQuery`, which signs the service JWT);\n * the caller's actor and workspace are forwarded explicitly because tags-svc\n * scopes every vocabulary, tag and assignment by `x-workspace-id`.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter } from '@burdenoff/be-sdk/tags';\n *\n * export const entityTags = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN', 'FLUIDGRIDS_DATATABLE'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n *\n * await entityTags.tagEntity('FLUIDGRIDS_RUN', run.id, { tagId }, { actorId, workspaceId });\n * ```\n */\nimport { EntityTagsError } from './errors.js';\nimport type {\n AvailableTag,\n CreateTagOptions,\n EntityTagAssignment,\n FindEntitiesByTagsOptions,\n RawTagAssignment,\n TagActor,\n TagAssignmentSource,\n TagEntityOptions,\n TagsGatewayClient,\n TaggedEntityPage,\n TagVocabularyConfig,\n TagVocabularyRef,\n} from './types.js';\nimport { TAG_ASSIGNMENT_SOURCES } from './types.js';\n\n/** tags-svc caps; requests outside are clamped rather than rejected. */\nconst SEARCH_LIMIT = { default: 20, max: 100 };\nconst AVAILABLE_LIMIT = { default: 50, max: 200 };\nconst ENTITIES_BY_TAGS_LIMIT = { default: 50, max: 200 };\n\n/** Same-layer tag calls should fail fast; the GatewayClient default is 30s. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\nconst ENTITY_TYPE_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\nconst ASSIGNMENT_FIELDS =\n 'id tagId entityType entityId source assignedById createdAt validFrom validTo metadata tag { id key label color }';\n\nexport interface TagsGatewayAdapterOptions {\n /**\n * The entity types this service owns, e.g. `['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN']`.\n * UPPER_SNAKE_CASE and namespaced by product so two services never share a type.\n */\n entityTypes: readonly string[];\n /** Default vocabulary that inline-created tags (no `vocabularyId`) land in. */\n vocabulary: TagVocabularyConfig;\n /** `source` sent when a caller passes none. Default `MANUAL`. */\n defaultSource?: TagAssignmentSource;\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: TagsGatewayClient | (() => TagsGatewayClient | Promise<TagsGatewayClient>);\n /** Service name for the default GatewayClient, e.g. `wspace-workflow-svc`. */\n serviceName?: string;\n /** Per-request timeout for tags-svc calls. Default 10s. */\n requestTimeoutMs?: number;\n}\n\nfunction clampLimit(value: number | null | undefined, bounds: { default: number; max: number }): number {\n if (value === null || value === undefined || !Number.isFinite(value)) return bounds.default;\n return Math.min(Math.max(Math.trunc(value), 1), bounds.max);\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new EntityTagsError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\n/** FNV-1a, used only to give non-ASCII labels a stable, non-empty key. */\nfunction shortHash(value: string): string {\n let hash = 0x811c9dc5;\n for (const char of value) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(36);\n}\n\n/**\n * Tag key for a label: lowercase ASCII slug (`\"Needs Review!\"` → `needs-review`).\n * Labels with no ASCII letters or digits (`\"日本\"`) get `tag-<hash>` so the key is\n * never empty (tags-svc rejects an empty key) and stays stable for the same label.\n */\nexport function slugifyTagKey(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || `tag-${shortHash(label.trim())}`;\n}\n\n/** Map a tags-svc `UniversalTagAssignment` onto the published assignment shape. */\nexport function mapTagAssignment(raw: RawTagAssignment): EntityTagAssignment {\n return {\n id: raw.id,\n tagId: raw.tagId,\n entityType: raw.entityType,\n entityId: raw.entityId,\n source: raw.source,\n assignedBy: raw.assignedById ?? null,\n assignedAt: toDate(raw.createdAt) ?? toDate(raw.validFrom),\n validFrom: toDate(raw.validFrom),\n validTo: toDate(raw.validTo),\n metadata: raw.metadata ?? null,\n tag: raw.tag ? { id: raw.tag.id } : null,\n tagInfo: raw.tag\n ? {\n id: raw.tag.id,\n key: raw.tag.key ?? null,\n label: raw.tag.label ?? null,\n color: raw.tag.color ?? null,\n }\n : null,\n };\n}\n\nexport class TagsGatewayAdapter {\n readonly entityTypes: readonly string[];\n readonly vocabulary: Readonly<TagVocabularyConfig>;\n readonly defaultSource: TagAssignmentSource;\n\n private readonly entityTypeSet: ReadonlySet<string>;\n private readonly requestTimeoutMs: number;\n private readonly clientOption: TagsGatewayAdapterOptions['client'];\n private readonly serviceName: string | undefined;\n private clientPromise: Promise<TagsGatewayClient> | null = null;\n\n constructor(options: TagsGatewayAdapterOptions) {\n if (options.entityTypes.length === 0) {\n throw new EntityTagsError('CONFIGURATION_ERROR', 'TagsGatewayAdapter needs at least one entity type');\n }\n for (const entityType of options.entityTypes) {\n if (!ENTITY_TYPE_PATTERN.test(entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity type \"${entityType}\" must be UPPER_SNAKE_CASE (e.g. FLUIDGRIDS_WORKFLOW)`,\n { entityType }\n );\n }\n }\n requireNonEmpty(options.vocabulary.key, 'vocabulary.key');\n requireNonEmpty(options.vocabulary.name, 'vocabulary.name');\n const defaultSource = options.defaultSource ?? 'MANUAL';\n if (!TAG_ASSIGNMENT_SOURCES.includes(defaultSource)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Unknown default tag source \"${defaultSource}\"`);\n }\n\n this.entityTypes = Object.freeze([...new Set(options.entityTypes)]);\n this.entityTypeSet = new Set(this.entityTypes);\n this.vocabulary = Object.freeze({ ...options.vocabulary });\n this.defaultSource = defaultSource;\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n }\n\n // ── Validation ────────────────────────────────────────────────────────\n\n isValidEntityType(entityType: string): boolean {\n return this.entityTypeSet.has(entityType);\n }\n\n assertEntityType(entityType: string): void {\n if (!this.isValidEntityType(entityType)) {\n throw new EntityTagsError('INVALID_ENTITY_TYPE', `Unsupported entity type \"${entityType}\"`, {\n entityType,\n supported: this.entityTypes,\n });\n }\n }\n\n /** Validate a caller-supplied source; empty means the adapter default. */\n resolveSource(source: string | null | undefined): TagAssignmentSource {\n if (source === null || source === undefined || source === '') return this.defaultSource;\n const normalized = source.toUpperCase();\n const match = TAG_ASSIGNMENT_SOURCES.find((candidate) => candidate === normalized);\n if (!match) {\n throw new EntityTagsError('INVALID_SOURCE', `Unknown tag source \"${source}\"`, {\n source,\n supported: TAG_ASSIGNMENT_SOURCES,\n });\n }\n return match;\n }\n\n // ── Assignments ───────────────────────────────────────────────────────\n\n /** Tags currently assigned to an entity. */\n async getEntityTags(entityType: string, entityId: string, actor: TagActor): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const data = await this.request<{ getEntityTags: RawTagAssignment[] | null }>(\n `query GetEntityTags($entityType: String!, $entityId: ID!) {\n getEntityTags(entityType: $entityType, entityId: $entityId) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id },\n actor\n );\n return (data.getEntityTags ?? []).map(mapTagAssignment);\n }\n\n /** Assign one tag to an entity. */\n async tagEntity(\n entityType: string,\n entityId: string,\n options: TagEntityOptions,\n actor: TagActor\n ): Promise<EntityTagAssignment> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const tagId = requireNonEmpty(options.tagId, 'tagId');\n const source = this.resolveSource(options.source);\n const context = this.requireActor(actor);\n\n const data = await this.request<{ assignTag: RawTagAssignment | null }>(\n `mutation AssignTag($input: AssignTagInput!) {\n assignTag(input: $input) { ${ASSIGNMENT_FIELDS} }\n }`,\n {\n input: {\n tagId,\n entityType,\n entityId: id,\n source,\n validFrom: options.validFrom?.toISOString(),\n validTo: options.validTo?.toISOString(),\n metadata: options.metadata ?? undefined,\n context: { workspaceId: context.workspaceId },\n },\n },\n context\n );\n if (!data.assignTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no assignment', { entityType, tagId });\n }\n return mapTagAssignment(data.assignTag);\n }\n\n /**\n * Remove a tag from an entity. Removes every assignment of that tag on the entity\n * (tags-svc allows several with different validity windows). `false` when the tag\n * was not assigned.\n */\n async untagEntity(entityType: string, entityId: string, tagId: string, actor: TagActor): Promise<boolean> {\n const id = requireNonEmpty(tagId, 'tagId');\n const assignments = await this.getEntityTags(entityType, entityId, actor);\n const matches = assignments.filter((assignment) => assignment.tagId === id);\n if (matches.length === 0) return false;\n\n let removed = false;\n for (const assignment of matches) {\n const data = await this.request<{ removeTagAssignment: boolean | null }>(\n `mutation RemoveTagAssignment($id: ID!) { removeTagAssignment(id: $id) }`,\n { id: assignment.id },\n actor\n );\n removed = data.removeTagAssignment === true || removed;\n }\n return removed;\n }\n\n /** Replace the full tag set on an entity (an empty list clears it). */\n async replaceEntityTags(\n entityType: string,\n entityId: string,\n tagIds: readonly string[],\n actor: TagActor\n ): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n const data = await this.request<{ replaceEntityTags: RawTagAssignment[] | null }>(\n `mutation ReplaceEntityTags($entityType: String!, $entityId: ID!, $tagIds: [ID!]!) {\n replaceEntityTags(entityType: $entityType, entityId: $entityId, tagIds: $tagIds) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id, tagIds: uniqueTagIds },\n actor\n );\n return (data.replaceEntityTags ?? []).map(mapTagAssignment);\n }\n\n /**\n * Ids of `entityType` entities carrying the given tags — the server-side half of\n * \"filter this list by tag\". Intersect the ids with the service's own query.\n */\n async findEntityIdsByTags(\n entityType: string,\n tagIds: readonly string[],\n actor: TagActor,\n options: FindEntitiesByTagsOptions = {}\n ): Promise<TaggedEntityPage> {\n this.assertEntityType(entityType);\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n if (uniqueTagIds.length === 0) {\n throw new EntityTagsError('INVALID_INPUT', 'tagIds must contain at least one tag', { field: 'tagIds' });\n }\n const data = await this.request<{\n getEntitiesByTags: {\n entities: Array<{ entityId: string; entityType: string }>;\n total: number;\n hasMore: boolean;\n nextCursor?: string | null;\n } | null;\n }>(\n `query GetEntitiesByTags($tagIds: [ID!]!, $entityType: String, $matchAll: Boolean, $pagination: TagsPaginationInput) {\n getEntitiesByTags(tagIds: $tagIds, entityType: $entityType, matchAll: $matchAll, pagination: $pagination) {\n entities { entityId entityType } total hasMore nextCursor\n }\n }`,\n {\n tagIds: uniqueTagIds,\n entityType,\n matchAll: options.matchAll ?? false,\n pagination: {\n limit: clampLimit(options.limit, ENTITIES_BY_TAGS_LIMIT),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n },\n },\n actor\n );\n const page = data.getEntitiesByTags;\n if (!page) return { entityIds: [], total: 0, hasMore: false, nextCursor: null };\n return {\n // tags-svc already filters by entityType; re-check so a lax upstream never\n // leaks another product's ids into this service's list.\n entityIds: page.entities.filter((entity) => entity.entityType === entityType).map((entity) => entity.entityId),\n total: page.total,\n hasMore: page.hasMore,\n nextCursor: page.nextCursor ?? null,\n };\n }\n\n // ── Workspace tags ────────────────────────────────────────────────────\n\n /** Search assignable tags in the workspace. */\n async searchTags(query: string, actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ searchTags: AvailableTag[] | null }>(\n `query SearchTags($query: String!, $limit: Int) {\n searchTags(query: $query, limit: $limit) { id key label color }\n }`,\n { query: query.trim(), limit: clampLimit(limit, SEARCH_LIMIT) },\n actor\n );\n return data.searchTags ?? [];\n }\n\n /** List assignable tags in the workspace. */\n async getAvailableTags(actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ getTags: { items: AvailableTag[] | null } | null }>(\n `query GetTags($pagination: TagsPaginationInput) {\n getTags(pagination: $pagination) { items { id key label color } }\n }`,\n { pagination: { limit: clampLimit(limit, AVAILABLE_LIMIT) } },\n actor\n );\n return data.getTags?.items ?? [];\n }\n\n /** Create a workspace tag, in the default vocabulary unless `vocabularyId` is given. */\n async createTag(options: CreateTagOptions, actor: TagActor): Promise<AvailableTag> {\n const label = requireNonEmpty(options.label, 'label');\n const vocabularyId =\n options.vocabularyId !== undefined && options.vocabularyId !== null\n ? options.vocabularyId\n : await this.ensureWorkspaceVocabulary(actor);\n\n const data = await this.request<{ createTag: AvailableTag | null }>(\n `mutation CreateTag($input: CreateTagInput!) {\n createTag(input: $input) { id key label color }\n }`,\n {\n input: {\n vocabularyId,\n key: slugifyTagKey(label),\n label,\n color: options.color || undefined,\n },\n },\n actor\n );\n if (!data.createTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no tag', { label });\n }\n return data.createTag;\n }\n\n // ── Vocabularies ──────────────────────────────────────────────────────\n\n /**\n * Resolve the workspace's default vocabulary id, creating the vocabulary on first\n * use. Order: pinned `id` (if it exists in this workspace) → lookup by `key` →\n * create → re-read by key (a concurrent request may have created it first).\n */\n async ensureWorkspaceVocabulary(actor: TagActor, override: Partial<TagVocabularyConfig> = {}): Promise<string> {\n const vocabulary = { ...this.vocabulary, ...override };\n\n if (vocabulary.id) {\n const byId = await this.getVocabularyById(vocabulary.id, actor);\n if (byId?.id) return byId.id;\n }\n\n const byKey = await this.getVocabularyByKey(vocabulary.key, actor);\n if (byKey?.id) return byKey.id;\n\n let createError: unknown = null;\n try {\n const created = await this.createVocabulary(vocabulary, actor);\n if (created?.id) return created.id;\n } catch (error) {\n // Most likely a unique-key race with a concurrent request; the re-read below\n // decides. Kept so the failure is not swallowed when the re-read finds nothing.\n createError = error;\n }\n\n const afterCreate = await this.getVocabularyByKey(vocabulary.key, actor);\n if (afterCreate?.id) return afterCreate.id;\n\n if (createError) throw createError;\n throw new EntityTagsError('UPSTREAM_ERROR', `Failed to resolve tag vocabulary \"${vocabulary.key}\"`, {\n vocabularyKey: vocabulary.key,\n });\n }\n\n async getVocabularyById(id: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabulary: TagVocabularyRef | null }>(\n `query GetVocabulary($id: ID!) { getVocabulary(id: $id) { id key name } }`,\n { id },\n actor\n );\n return data.getVocabulary ?? null;\n }\n\n async getVocabularyByKey(key: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabularyByKey: TagVocabularyRef | null }>(\n `query GetVocabularyByKey($key: String!) { getVocabularyByKey(key: $key) { id key name } }`,\n { key },\n actor\n );\n return data.getVocabularyByKey ?? null;\n }\n\n /** Create a WORKSPACE-scoped, multi-valued, open (custom tags allowed) string vocabulary. */\n async createVocabulary(vocabulary: TagVocabularyConfig, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ createVocabulary: TagVocabularyRef | null }>(\n `mutation CreateVocabulary($input: CreateVocabularyInput!) {\n createVocabulary(input: $input) { id key name }\n }`,\n {\n input: {\n key: requireNonEmpty(vocabulary.key, 'vocabulary.key'),\n name: requireNonEmpty(vocabulary.name, 'vocabulary.name'),\n description: vocabulary.description,\n scope: 'WORKSPACE',\n dataType: 'STRING',\n cardinality: 'MULTIPLE',\n allowCustomTags: true,\n },\n },\n actor\n );\n return data.createVocabulary ?? null;\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private requireActor(actor: TagActor): TagActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new EntityTagsError('MISSING_CONTEXT', 'Tag operations need an authenticated actor and a workspace');\n }\n return actor;\n }\n\n private getClient(): Promise<TagsGatewayClient> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<TagsGatewayClient> => {\n if (typeof option === 'function') return option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/tags` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(query: string, variables: Record<string, unknown>, actor: TagActor): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n const response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType || 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n if (response.errors?.length) {\n throw new EntityTagsError(\n 'UPSTREAM_ERROR',\n `wspace-tags-svc error: ${response.errors.map((error) => error.message).join('; ')}`,\n { errors: response.errors }\n );\n }\n if (!response.data) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no data');\n }\n return response.data;\n }\n}\n","/**\n * Entity tags — SDL generator.\n *\n * One fixed SDL fragment cannot be shared: two subgraphs declaring the same\n * non-`@shareable` value type (`EntityTagAssignment`, `AvailableTag`, …) fail\n * Federation composition. {@link buildEntityTagsSdl} therefore emits the whole\n * tag surface under a per-service prefix (names from `./naming.ts`), with a\n * static `@rbac` directive on every root field — the gateway enforces RBAC from\n * the composed supergraph and needs a literal action/resource per field.\n *\n * The SDL references `@rbac`, `JSON`, `DateTime` and the federated\n * `UniversalTag` entity, which the host subgraph already declares (pass\n * `includeUniversalTagStub: true` if it does not declare `UniversalTag` yet).\n */\nimport { EntityTagsError } from './errors.js';\nimport { entityTagsFieldNames, entityTagsTypeNames, type EntityTagsTypeNames } from './naming.js';\n\nconst TYPE_NAME_PATTERN = /^[A-Z]\\w*$/;\nconst RBAC_TOKEN_PATTERN = /^[a-z0-9][a-z0-9:_-]*$/i;\n\n/** The `@rbac` arguments stamped on the generated root fields. */\nexport interface EntityTagsRbacOptions {\n /** RBAC resource the service already gates its entities on, e.g. `workflow`, `agent`. */\n resource: string;\n /** Default `wspace`. */\n scopeType?: string;\n /** Action for the read fields. Default `read`. */\n readAction?: string;\n /** Action for tag/untag/replace. Default `update`. */\n updateAction?: string;\n /** Action for creating a workspace tag. Default `create`. */\n createAction?: string;\n}\n\nexport interface EntityTagsSdlOptions {\n /** PascalCase service prefix, e.g. `Fluidgrids` → `fluidgridsEntityTags`, `FluidgridsTagAssignment`. */\n prefix: string;\n /** Product name used in field descriptions. Defaults to `prefix`. */\n productLabel?: string;\n rbac: EntityTagsRbacOptions;\n /** Types (owned elsewhere in the subgraph) that get a `tagAssignments` field. */\n extendTypes?: readonly string[];\n /** Override generated type names, for services with already-published legacy names. */\n typeNames?: Partial<EntityTagsTypeNames>;\n /** Types the subgraph already declares elsewhere: referenced, not declared. */\n externalTypes?: readonly (keyof EntityTagsTypeNames)[];\n /** Also emit the `…EntitiesByTags` query (server-side filter-by-tag). Default `false`. */\n includeEntitiesByTags?: boolean;\n /** Also declare the non-resolvable `UniversalTag @key(fields: \"id\")` stub. Default `false`. */\n includeUniversalTagStub?: boolean;\n}\n\n/** Non-resolvable stub for the tags-svc-owned `UniversalTag` entity. */\nexport const UNIVERSAL_TAG_STUB_SDL = /* GraphQL */ `\n \"UniversalTag is owned by wspace-tags-svc; only its key is resolvable here.\"\n type UniversalTag @key(fields: \"id\", resolvable: false) {\n id: ID!\n }\n`;\n\nfunction rbacToken(value: string, field: string): string {\n if (!RBAC_TOKEN_PATTERN.test(value)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags rbac.${field} \"${value}\" is not a valid RBAC token`, {\n field,\n value,\n });\n }\n return value;\n}\n\nfunction rbacDirective(action: string, resource: string, scopeType: string): string {\n return `@rbac(action: \"${action}\", resource: \"${resource}\", scopeType: \"${scopeType}\")`;\n}\n\nfunction sanitizeDescription(value: string): string {\n // Config-time text inside a \"...\" description: no quote or backslash may end/escape it.\n return value.replace(/[\"\\\\]/g, \"'\").replace(/\\s+/g, ' ').trim();\n}\n\nexport function buildEntityTagsSdl(options: EntityTagsSdlOptions): string {\n const fields = entityTagsFieldNames(options.prefix);\n const types = entityTagsTypeNames(options.prefix, options.typeNames);\n const external = new Set<keyof EntityTagsTypeNames>(options.externalTypes ?? []);\n const label = sanitizeDescription(options.productLabel ?? options.prefix);\n\n const resource = rbacToken(options.rbac.resource, 'resource');\n const scopeType = rbacToken(options.rbac.scopeType ?? 'wspace', 'scopeType');\n const read = rbacDirective(rbacToken(options.rbac.readAction ?? 'read', 'readAction'), resource, scopeType);\n const update = rbacDirective(rbacToken(options.rbac.updateAction ?? 'update', 'updateAction'), resource, scopeType);\n const create = rbacDirective(rbacToken(options.rbac.createAction ?? 'create', 'createAction'), resource, scopeType);\n\n const extendTypes = [...new Set(options.extendTypes ?? [])];\n for (const typeName of extendTypes) {\n if (!TYPE_NAME_PATTERN.test(typeName)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Cannot extend \"${typeName}\": not a valid type name`, {\n typeName,\n });\n }\n }\n\n const blocks: string[] = [];\n const emitType = (role: keyof EntityTagsTypeNames, sdl: string): void => {\n if (!external.has(role)) blocks.push(sdl);\n };\n\n if (options.includeUniversalTagStub) blocks.push(UNIVERSAL_TAG_STUB_SDL.trim());\n\n emitType(\n 'getEntityTagsInput',\n `input ${types.getEntityTagsInput} {\n entityType: String!\n entityId: ID!\n}`\n );\n emitType(\n 'tagEntityInput',\n `input ${types.tagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n \"AssignmentSource (MANUAL, AUTOMATIC, IMPORTED, ...). Defaults to the service default.\"\n source: String\n metadata: JSON\n}`\n );\n emitType(\n 'untagEntityInput',\n `input ${types.untagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n}`\n );\n emitType(\n 'replaceEntityTagsInput',\n `input ${types.replaceEntityTagsInput} {\n entityType: String!\n entityId: ID!\n tagIds: [ID!]!\n}`\n );\n emitType(\n 'createTagInput',\n `input ${types.createTagInput} {\n \"Optional. When omitted the tag goes to the workspace's default ${label} vocabulary (created on first use).\"\n vocabularyId: ID\n label: String!\n color: String\n}`\n );\n emitType(\n 'tagInfo',\n `\"Inline (non-federated) tag projection, so clients render labels without a federated round-trip.\"\ntype ${types.tagInfo} {\n id: ID!\n key: String\n label: String\n color: String\n}`\n );\n emitType(\n 'tagAssignment',\n `\"A tag assigned to a ${label} entity.\"\ntype ${types.tagAssignment} {\n id: ID!\n tagId: ID!\n \"Federated UniversalTag reference (owned by wspace-tags-svc). Prefer tagInfo for label/colour.\"\n tag: UniversalTag\n \"Inline projection of the tag (key/label/colour).\"\n tagInfo: ${types.tagInfo}\n entityType: String!\n entityId: ID!\n source: String!\n assignedBy: ID\n assignedAt: DateTime\n validFrom: DateTime\n validTo: DateTime\n metadata: JSON\n}`\n );\n emitType(\n 'availableTag',\n `\"An assignable workspace tag.\"\ntype ${types.availableTag} {\n id: ID!\n key: String!\n label: String!\n color: String\n}`\n );\n\n if (options.includeEntitiesByTags) {\n emitType(\n 'entitiesByTagsInput',\n `input ${types.entitiesByTagsInput} {\n entityType: String!\n tagIds: [ID!]!\n \"true = entity must carry every tag; false (default) = any of them.\"\n matchAll: Boolean\n limit: Int\n cursor: String\n}`\n );\n emitType(\n 'taggedEntityPage',\n `\"Ids of entities carrying the requested tags.\"\ntype ${types.taggedEntityPage} {\n entityIds: [ID!]!\n total: Int!\n hasMore: Boolean!\n nextCursor: String\n}`\n );\n }\n\n const queryFields = [\n ` \"Tags currently assigned to a ${label} entity\"\n ${fields.entityTags}(input: ${types.getEntityTagsInput}!): [${types.tagAssignment}!]! ${read}`,\n ` \"Search assignable tags in the workspace\"\n ${fields.searchTags}(query: String!, limit: Int): [${types.availableTag}!]! ${read}`,\n ` \"List assignable tags in the workspace\"\n ${fields.availableTags}(limit: Int): [${types.availableTag}!]! ${read}`,\n ];\n if (options.includeEntitiesByTags) {\n queryFields.push(` \"Ids of ${label} entities carrying the given tags (filter-by-tag)\"\n ${fields.entitiesByTags}(input: ${types.entitiesByTagsInput}!): ${types.taggedEntityPage}! ${read}`);\n }\n blocks.push(`extend type Query {\\n${queryFields.join('\\n\\n')}\\n}`);\n\n blocks.push(`extend type Mutation {\n \"Assign a tag to a ${label} entity\"\n ${fields.tagEntity}(input: ${types.tagEntityInput}!): ${types.tagAssignment}! ${update}\n\n \"Remove a tag from a ${label} entity\"\n ${fields.untagEntity}(input: ${types.untagEntityInput}!): Boolean! ${update}\n\n \"Replace the full tag set on a ${label} entity\"\n ${fields.replaceEntityTags}(input: ${types.replaceEntityTagsInput}!): [${types.tagAssignment}!]! ${update}\n\n \"Create a new assignable tag (inline creation from a picker)\"\n ${fields.createTag}(input: ${types.createTagInput}!): ${types.availableTag}! ${create}\n}`);\n\n for (const typeName of extendTypes) {\n blocks.push(`extend type ${typeName} {\n \"Structured tag assignments (wspace-tags-svc).\"\n tagAssignments: [${types.tagAssignment}!]!\n}`);\n }\n\n return `${blocks.join('\\n\\n')}\\n`;\n}\n","/**\n * Entity tags — resolver factory.\n *\n * Builds the Query / Mutation / `tagAssignments` resolvers that match the SDL\n * from {@link buildEntityTagsSdl} for the same `prefix` (both derive names from\n * `./naming.ts`). The service supplies only what differs: how to read the actor\n * off its context, which GraphQL types map to which entity types, how to map\n * errors onto its i18n errors, and optional ownership/audit hooks.\n *\n * @example\n * ```ts\n * import { buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const { Query, Mutation, types } = createEntityTagResolvers({\n * prefix: 'Fluidgrids',\n * adapter: entityTags,\n * entities: {\n * WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },\n * WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },\n * },\n * mapError: (error, ctx) => workflowError(`tags.errors.${error.code}`, error.graphqlCode, ctx, error.details),\n * });\n * ```\n */\nimport { GraphQLError } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { TagsGatewayAdapter } from './adapter.js';\nimport { EntityTagsError, isEntityTagsError } from './errors.js';\nimport { entityTagsFieldNames } from './naming.js';\nimport type { AvailableTag, EntityTagAssignment, TagActor, TagActorType, TaggedEntityPage } from './types.js';\nimport { TAG_ACTOR_TYPES } from './types.js';\n\n/** Maps a GraphQL object type onto the entity type and id its tags are stored under. */\nexport interface EntityTagBinding {\n entityType: string;\n /**\n * Entity id for a parent object. Defaults to `parent.id`. Use a stable logical id\n * when rows are versioned (FluidGrids tags `workflowKey`, not the per-version row id).\n */\n entityId?: (parent: Record<string, unknown>) => string | null | undefined;\n}\n\nexport type EntityTagOperation = 'tag' | 'untag' | 'replace' | 'createTag';\n\n/** Emitted after a successful write, for audit/activity logging. */\nexport interface EntityTagMutationEvent {\n operation: EntityTagOperation;\n /** Root field name, e.g. `tagFluidgridsEntity`. */\n fieldName: string;\n actor: TagActor;\n entityType?: string;\n entityId?: string;\n tagId?: string;\n tagIds?: string[];\n source?: string;\n /** For `createTag`. */\n tag?: AvailableTag;\n vocabularyId?: string;\n}\n\n/** Passed to `authorizeEntity` before any entity-addressed operation. */\nexport interface EntityTagAccessCheck {\n entityType: string;\n entityId: string;\n access: 'read' | 'write';\n actor: TagActor;\n}\n\nexport interface CreateEntityTagResolversOptions<TContext> {\n /** Same prefix as passed to `buildEntityTagsSdl`. */\n prefix: string;\n adapter: TagsGatewayAdapter;\n /** GraphQL type name → binding, for the `tagAssignments` field on each extended type. */\n entities?: Readonly<Record<string, EntityTagBinding>>;\n /**\n * Reads the caller off the request context. Default: be-sdk server context\n * (`context.actor.{id,type}`, `context.workspace.id`), falling back to flat\n * `context.actorId` / `context.workspaceId`.\n */\n getActor?: (context: TContext) => TagActor;\n /**\n * Ownership check for entity-addressed operations (throw to deny). Use it to\n * confirm the entity exists in the caller's workspace before tags are read or\n * written for an arbitrary `entityId`; throw NOT_FOUND, never FORBIDDEN.\n */\n authorizeEntity?: (check: EntityTagAccessCheck, context: TContext) => void | Promise<void>;\n /** Called after each successful write. Failures are logged, never surfaced. */\n onMutation?: (event: EntityTagMutationEvent, context: TContext) => void | Promise<void>;\n /** Map an adapter error onto the service's own (i18n) GraphQL error. */\n mapError?: (error: EntityTagsError, context: TContext) => Error;\n /** Must match `includeEntitiesByTags` on the SDL. Default `false`. */\n includeEntitiesByTags?: boolean;\n}\n\ntype Resolver<TArgs, TResult, TContext> = (parent: unknown, args: TArgs, context: TContext) => Promise<TResult>;\n\ntype TagAssignmentsResolver<TContext> = (\n parent: Record<string, unknown>,\n args: unknown,\n context: TContext\n) => Promise<EntityTagAssignment[]>;\n\ninterface EntityRefInput {\n entityType: string;\n entityId: string;\n}\n\nexport interface EntityTagResolvers<TContext> {\n Query: Record<string, Resolver<never, unknown, TContext>>;\n Mutation: Record<string, Resolver<never, unknown, TContext>>;\n /** `{ [GraphQLTypeName]: { tagAssignments } }`, ready to spread into the resolver map. */\n types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }>;\n}\n\nfunction readRecord(value: unknown, key: string): unknown {\n if (value === null || typeof value !== 'object') return undefined;\n return (value as Record<string, unknown>)[key];\n}\n\nfunction readString(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction toActorType(value: unknown): TagActorType {\n return TAG_ACTOR_TYPES.find((candidate) => candidate === value) ?? 'user';\n}\n\n/** Default actor reader for the be-sdk server context shape. */\nexport function defaultTagActor(context: unknown): TagActor {\n const actor = readRecord(context, 'actor');\n const workspace = readRecord(context, 'workspace');\n return {\n actorId: readString(readRecord(actor, 'id')) || readString(readRecord(context, 'actorId')),\n actorType: toActorType(readRecord(actor, 'type') ?? readRecord(context, 'actorType')),\n workspaceId: readString(readRecord(workspace, 'id')) || readString(readRecord(context, 'workspaceId')),\n };\n}\n\nfunction defaultMapError(error: EntityTagsError): Error {\n if (error.code === 'UPSTREAM_ERROR' || error.code === 'CONFIGURATION_ERROR') {\n // Upstream payloads can carry internal detail; log it, return a generic message.\n logger.error('[be-sdk/tags] Tag operation failed', { code: error.code, message: error.message });\n return new GraphQLError('Tag operation failed', { extensions: { code: error.graphqlCode } });\n }\n return new GraphQLError(error.message, { extensions: { code: error.graphqlCode, reason: error.code } });\n}\n\nexport function createEntityTagResolvers<TContext>(\n options: CreateEntityTagResolversOptions<TContext>\n): EntityTagResolvers<TContext> {\n const { adapter } = options;\n const fields = entityTagsFieldNames(options.prefix);\n const getActor = options.getActor ?? ((context: TContext) => defaultTagActor(context));\n const mapError = options.mapError ?? ((error: EntityTagsError) => defaultMapError(error));\n\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n if (!adapter.isValidEntityType(binding.entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `${typeName} is bound to entity type \"${binding.entityType}\", which the adapter does not register`,\n { typeName, entityType: binding.entityType }\n );\n }\n }\n\n const guard = async <T>(context: TContext, run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (isEntityTagsError(error)) throw mapError(error, context);\n throw error;\n }\n };\n\n const authorize = async (\n input: EntityRefInput,\n access: EntityTagAccessCheck['access'],\n actor: TagActor,\n context: TContext\n ): Promise<void> => {\n adapter.assertEntityType(input.entityType);\n if (!input.entityId?.trim()) {\n throw new EntityTagsError('INVALID_INPUT', 'entityId is required', { field: 'entityId' });\n }\n if (options.authorizeEntity) {\n await options.authorizeEntity({ entityType: input.entityType, entityId: input.entityId, access, actor }, context);\n }\n };\n\n const notify = async (event: EntityTagMutationEvent, context: TContext): Promise<void> => {\n if (!options.onMutation) return;\n try {\n await options.onMutation(event, context);\n } catch (error) {\n logger.warn('[be-sdk/tags] onMutation hook failed', {\n fieldName: event.fieldName,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n const Query: Record<string, Resolver<never, unknown, TContext>> = {};\n const Mutation: Record<string, Resolver<never, unknown, TContext>> = {};\n\n const entityTags: Resolver<{ input: EntityRefInput }, EntityTagAssignment[], TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'read', actor, context);\n return adapter.getEntityTags(input.entityType, input.entityId, actor);\n });\n Query[fields.entityTags] = entityTags;\n\n const searchTags: Resolver<{ query: string; limit?: number | null }, AvailableTag[], TContext> = (\n _parent,\n { query, limit },\n context\n ) => guard(context, () => adapter.searchTags(query, getActor(context), limit));\n Query[fields.searchTags] = searchTags;\n\n const availableTags: Resolver<{ limit?: number | null }, AvailableTag[], TContext> = (_parent, { limit }, context) =>\n guard(context, () => adapter.getAvailableTags(getActor(context), limit));\n Query[fields.availableTags] = availableTags;\n\n if (options.includeEntitiesByTags) {\n const entitiesByTags: Resolver<\n {\n input: {\n entityType: string;\n tagIds: string[];\n matchAll?: boolean | null;\n limit?: number | null;\n cursor?: string | null;\n };\n },\n TaggedEntityPage,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, () =>\n adapter.findEntityIdsByTags(input.entityType, input.tagIds, getActor(context), {\n matchAll: input.matchAll ?? false,\n limit: input.limit,\n cursor: input.cursor,\n })\n );\n Query[fields.entitiesByTags] = entitiesByTags;\n }\n\n const tagEntity: Resolver<\n { input: EntityRefInput & { tagId: string; source?: string | null; metadata?: Record<string, unknown> | null } },\n EntityTagAssignment,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignment = await adapter.tagEntity(\n input.entityType,\n input.entityId,\n { tagId: input.tagId, source: input.source, metadata: input.metadata },\n actor\n );\n await notify(\n {\n operation: 'tag',\n fieldName: fields.tagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n source: assignment.source,\n },\n context\n );\n return assignment;\n });\n Mutation[fields.tagEntity] = tagEntity;\n\n const untagEntity: Resolver<{ input: EntityRefInput & { tagId: string } }, boolean, TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const removed = await adapter.untagEntity(input.entityType, input.entityId, input.tagId, actor);\n if (removed) {\n await notify(\n {\n operation: 'untag',\n fieldName: fields.untagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n },\n context\n );\n }\n return removed;\n });\n Mutation[fields.untagEntity] = untagEntity;\n\n const replaceEntityTags: Resolver<\n { input: EntityRefInput & { tagIds: string[] } },\n EntityTagAssignment[],\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignments = await adapter.replaceEntityTags(input.entityType, input.entityId, input.tagIds, actor);\n await notify(\n {\n operation: 'replace',\n fieldName: fields.replaceEntityTags,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagIds: [...new Set(input.tagIds)],\n },\n context\n );\n return assignments;\n });\n Mutation[fields.replaceEntityTags] = replaceEntityTags;\n\n const createTag: Resolver<\n { input: { vocabularyId?: string | null; label: string; color?: string | null } },\n AvailableTag,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n const vocabularyId =\n input.vocabularyId !== undefined && input.vocabularyId !== null\n ? input.vocabularyId\n : await adapter.ensureWorkspaceVocabulary(actor);\n const tag = await adapter.createTag({ label: input.label, color: input.color, vocabularyId }, actor);\n await notify({ operation: 'createTag', fieldName: fields.createTag, actor, tag, vocabularyId }, context);\n return tag;\n });\n Mutation[fields.createTag] = createTag;\n\n const types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }> = {};\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n const selectId = binding.entityId ?? ((parent: Record<string, unknown>) => readString(parent['id']));\n types[typeName] = {\n tagAssignments: async (parent, _args, context) => {\n const entityId = selectId(parent);\n if (!entityId) return [];\n try {\n return await adapter.getEntityTags(binding.entityType, entityId, getActor(context));\n } catch (error) {\n // The field is non-nullable decoration: a tags-svc outage must never fail\n // the parent query (a workflow list, a run page, …).\n logger.warn('[be-sdk/tags] Failed to resolve tagAssignments', {\n typeName,\n entityType: binding.entityType,\n entityId,\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n },\n };\n }\n\n return { Query, Mutation, types };\n}\n","/**\n * @burdenoff/be-sdk/tags\n *\n * Shared \"tag my entities\" surface for product services, backed by\n * wspace-tags-svc through the internal workspace gateway:\n *\n * - {@link TagsGatewayAdapter} — the configurable adapter (entity types, default\n * vocabulary, default source) that replaces the per-service EntityTagAdapter copies.\n * - {@link buildEntityTagsSdl} — the per-service, prefixed SDL (unique type names so\n * subgraphs never collide in composition; static `@rbac` on every root field).\n * - {@link createEntityTagResolvers} — the matching Query / Mutation /\n * `tagAssignments` resolvers, with ownership, audit and error-mapping hooks.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter, buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const adapter = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n * export const typeDefs = buildEntityTagsSdl({\n * prefix: 'Fluidgrids',\n * productLabel: 'FluidGrids',\n * rbac: { resource: 'workflow' },\n * extendTypes: ['WorkflowDefinition', 'WorkflowRun'],\n * });\n * export const resolvers = createEntityTagResolvers({ prefix: 'Fluidgrids', adapter, entities: { … } });\n * ```\n */\n\nexport {\n TAG_ACTOR_TYPES,\n TAG_ASSIGNMENT_SOURCES,\n type AvailableTag,\n type CreateTagOptions,\n type EntityTagAssignment,\n type EntityTagInfo,\n type FindEntitiesByTagsOptions,\n type RawTagAssignment,\n type TagActor,\n type TagActorType,\n type TagAssignmentSource,\n type TagEntityOptions,\n type TaggedEntityPage,\n type TagsGatewayClient,\n type TagVocabularyConfig,\n type TagVocabularyRef,\n} from './types.js';\n\nexport { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, isEntityTagsError, type EntityTagsErrorCode } from './errors.js';\n\nexport {\n assertTagPrefix,\n entityTagsFieldNames,\n entityTagsTypeNames,\n type EntityTagsFieldNames,\n type EntityTagsTypeNames,\n} from './naming.js';\n\nexport { TagsGatewayAdapter, mapTagAssignment, slugifyTagKey, type TagsGatewayAdapterOptions } from './adapter.js';\n\nexport {\n UNIVERSAL_TAG_STUB_SDL,\n buildEntityTagsSdl,\n type EntityTagsRbacOptions,\n type EntityTagsSdlOptions,\n} from './sdl.js';\n\nexport {\n createEntityTagResolvers,\n defaultTagActor,\n type CreateEntityTagResolversOptions,\n type EntityTagAccessCheck,\n type EntityTagBinding,\n type EntityTagMutationEvent,\n type EntityTagOperation,\n type EntityTagResolvers,\n} from './resolvers.js';\n"],"mappings":";;;;;;AAWA,MAAa,kBAAkB;CAAC;CAAQ;CAAO;CAAW;AAAa;;AAevE,MAAa,yBAAyB;CAAC;CAAa;CAAY;CAAY;CAAa;CAAU;AAAU;;;;ACH7G,MAAa,4BAAiE;CAC5E,qBAAqB;CACrB,gBAAgB;CAChB,eAAe;CACf,iBAAiB;CACjB,gBAAgB;CAChB,qBAAqB;AACvB;AAEA,IAAa,kBAAb,cAAqC,MAAM;CACzC,AAAS;CACT,AAAS;CAET,YAAY,MAA2B,SAAiB,UAAmC,CAAC,GAAG;EAC7F,MAAM,OAAO;EACb,KAAK,OAAO;EACZ,KAAK,OAAO;EACZ,KAAK,UAAU;CACjB;;CAGA,IAAI,cAAsB;EACxB,OAAO,0BAA0B,KAAK;CACxC;AACF;AAEA,SAAgB,kBAAkB,OAA0C;CAC1E,OAAO,iBAAiB;AAC1B;;;;;;;;;;;;;ACvCA,MAAM,iBAAiB;AA4BvB,SAAgB,gBAAgB,QAAsB;CACpD,IAAI,CAAC,eAAe,KAAK,MAAM,GAC7B,MAAM,IAAI,gBACR,uBACA,mEAAmE,OAAO,IAC1E,EAAE,OAAO,CACX;AAEJ;AAEA,SAAS,WAAW,OAAuB;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OAAO;CACT,CAAC;CACH,SAAS,OAAO,aAAa;CAE7B,MAAM,QAA8E,CAAC;CACrF,KAAK,MAAM,CAAC,UAAU,YAAY,OAAO,QAAQ,QAAQ,YAAY,CAAC,CAAC,GAAG;EACxE,MAAM,WAAW,QAAQ,cAAc,WAAoC,WAAW,OAAO,KAAK;EAClG,MAAM,YAAY,EAChB,gBAAgB,OAAO,QAAQ,OAAO,YAAY;GAChD,MAAM,WAAW,SAAS,MAAM;GAChC,IAAI,CAAC,UAAU,OAAO,CAAC;GACvB,IAAI;IACF,OAAO,MAAM,QAAQ,cAAc,QAAQ,YAAY,UAAU,SAAS,OAAO,CAAC;GACpF,SAAS,OAAO;IAGd,OAAO,KAAK,kDAAkD;KAC5D;KACA,YAAY,QAAQ;KACpB;KACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,CAAC;IACD,OAAO,CAAC;GACV;EACF,EACF;CACF;CAEA,OAAO;EAAE;EAAO;EAAU;CAAM;AAClC"}
|
|
1
|
+
{"version":3,"file":"tags-CbijgoqR.js","names":[],"sources":["../src/tags/types.ts","../src/tags/errors.ts","../src/tags/naming.ts","../src/tags/adapter.ts","../src/tags/sdl.ts","../src/tags/resolvers.ts","../src/tags/index.ts"],"sourcesContent":["/**\n * Entity tags — shared types.\n *\n * Every product service that lets users tag its own entities talks to the one\n * polymorphic tag owner, **wspace-tags-svc**, through the internal workspace\n * gateway. These types describe both the tags-svc wire shape and the\n * projection the service publishes in its own subgraph.\n */\nimport type { GraphQLRequestOptions, GraphQLResponse } from '../gateway/types.js';\n\n/** Actor types the gateway forwards in `x-actor-type`. */\nexport const TAG_ACTOR_TYPES = ['user', 'app', 'service', 'super_admin'] as const;\n\nexport type TagActorType = (typeof TAG_ACTOR_TYPES)[number];\n\n/** The caller a tag operation runs on behalf of (forwarded as `x-actor-*` / `x-workspace-id`). */\nexport interface TagActor {\n /** `x-actor-id` — the user/app/service id the gateway authenticated. */\n actorId: string;\n /** `x-workspace-id` — tags-svc scopes every vocabulary, tag and assignment by it. */\n workspaceId: string;\n /** `x-actor-type`; defaults to `user`. */\n actorType?: TagActorType;\n}\n\n/** `AssignmentSource` enum members accepted by wspace-tags-svc. */\nexport const TAG_ASSIGNMENT_SOURCES = ['AUTOMATIC', 'COMPUTED', 'IMPORTED', 'INHERITED', 'MANUAL', 'MIGRATED'] as const;\n\nexport type TagAssignmentSource = (typeof TAG_ASSIGNMENT_SOURCES)[number];\n\n/** `UniversalTagAssignment` as it comes back over the wire from wspace-tags-svc. */\nexport interface RawTagAssignment {\n id: string;\n tagId: string;\n entityType: string;\n entityId: string;\n source: string;\n assignedById?: string | null;\n createdAt?: string | null;\n validFrom?: string | null;\n validTo?: string | null;\n metadata?: unknown;\n tag?: { id: string; key?: string | null; label?: string | null; color?: string | null } | null;\n}\n\n/** Inline (non-federated) tag projection so clients render labels in one round-trip. */\nexport interface EntityTagInfo {\n id: string;\n key: string | null;\n label: string | null;\n color: string | null;\n}\n\n/** A tag assigned to one of the service's entities, in the shape its subgraph publishes. */\nexport interface EntityTagAssignment {\n id: string;\n tagId: string;\n /** Federated `UniversalTag` reference — only `id` resolves locally; tags-svc owns the rest. */\n tag: { id: string } | null;\n tagInfo: EntityTagInfo | null;\n entityType: string;\n entityId: string;\n source: string;\n assignedBy: string | null;\n assignedAt: Date | null;\n validFrom: Date | null;\n validTo: Date | null;\n metadata: unknown;\n}\n\n/** An assignable workspace tag. */\nexport interface AvailableTag {\n id: string;\n key: string;\n label: string;\n color: string | null;\n}\n\n/** Minimal vocabulary reference returned by tags-svc. */\nexport interface TagVocabularyRef {\n id: string;\n key: string;\n name: string;\n}\n\n/** The workspace-scoped vocabulary that inline-created tags land in. */\nexport interface TagVocabularyConfig {\n /** Stable vocabulary key, e.g. `fluidgrids-tags`. Looked up first, created when missing. */\n key: string;\n /** Display name used when the vocabulary has to be created. */\n name: string;\n description?: string;\n /**\n * A pinned vocabulary id. Used when it exists in the caller's workspace; ignored\n * (falls back to `key`) when it does not, so one id never leaks across workspaces.\n */\n id?: string;\n}\n\n/** Options for {@link TagsGatewayAdapter.tagEntity}. */\nexport interface TagEntityOptions {\n tagId: string;\n source?: string | null;\n validFrom?: Date | null;\n validTo?: Date | null;\n metadata?: Record<string, unknown> | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.createTag}. */\nexport interface CreateTagOptions {\n label: string;\n color?: string | null;\n /**\n * Target vocabulary. `undefined`/`null` resolves (or creates) the adapter's default\n * vocabulary. Any explicit value, even an empty string, is sent as-is so an unknown id\n * surfaces as a tags-svc error instead of silently misfiling the tag.\n */\n vocabularyId?: string | null;\n}\n\n/** Options for {@link TagsGatewayAdapter.findEntityIdsByTags}. */\nexport interface FindEntitiesByTagsOptions {\n /** `true` = entity must carry every tag; `false` (default) = any of them. */\n matchAll?: boolean;\n /** Clamped to 1..200; default 50. */\n limit?: number | null;\n cursor?: string | null;\n}\n\n/** One page of entity ids carrying the requested tags. */\nexport interface TaggedEntityPage {\n entityIds: string[];\n total: number;\n hasMore: boolean;\n nextCursor: string | null;\n}\n\n/** The slice of the be-sdk `GatewayClient` the adapter needs (lets tests pass a fake). */\nexport interface TagsGatewayClient {\n internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;\n}\n","/**\n * Entity tags — error type.\n *\n * Services map {@link EntityTagsError} onto their own i18n GraphQL errors (see the\n * `invalidEntityTypeError` / `mapError` hooks of `createEntityTagResolvers`); the\n * `code` is stable so that mapping never has to parse messages.\n */\n\nexport type EntityTagsErrorCode =\n /** `entityType` is not one the service registered as taggable. */\n | 'INVALID_ENTITY_TYPE'\n /** `source` is not a tags-svc `AssignmentSource`. */\n | 'INVALID_SOURCE'\n /** A required argument (entity id, tag id, label, …) is empty. */\n | 'INVALID_INPUT'\n /** No actor/workspace on the request — tags are always workspace-scoped. */\n | 'MISSING_CONTEXT'\n /** tags-svc answered without the expected payload. */\n | 'UPSTREAM_ERROR'\n /** The adapter / resolver factory was configured inconsistently (thrown at boot). */\n | 'CONFIGURATION_ERROR';\n\n/** GraphQL `extensions.code` each {@link EntityTagsErrorCode} should surface as. */\nexport const ENTITY_TAGS_GRAPHQL_CODES: Record<EntityTagsErrorCode, string> = {\n INVALID_ENTITY_TYPE: 'BAD_USER_INPUT',\n INVALID_SOURCE: 'BAD_USER_INPUT',\n INVALID_INPUT: 'BAD_USER_INPUT',\n MISSING_CONTEXT: 'UNAUTHENTICATED',\n UPSTREAM_ERROR: 'INTERNAL_SERVER_ERROR',\n CONFIGURATION_ERROR: 'INTERNAL_SERVER_ERROR',\n};\n\nexport class EntityTagsError extends Error {\n readonly code: EntityTagsErrorCode;\n readonly details: Record<string, unknown>;\n\n constructor(code: EntityTagsErrorCode, message: string, details: Record<string, unknown> = {}) {\n super(message);\n this.name = 'EntityTagsError';\n this.code = code;\n this.details = details;\n }\n\n /** The GraphQL `extensions.code` this error maps to. */\n get graphqlCode(): string {\n return ENTITY_TAGS_GRAPHQL_CODES[this.code];\n }\n}\n\nexport function isEntityTagsError(error: unknown): error is EntityTagsError {\n return error instanceof EntityTagsError;\n}\n","/**\n * Entity tags — GraphQL naming.\n *\n * Every service in the workspaces supergraph publishes its own tag surface, so\n * every type and root field must be unique to the service: unprefixed\n * `EntityTagAssignment` / `AvailableTag` / `EntityTagInfo` declared by two\n * subgraphs are non-shareable value types and break composition. The SDL\n * builder and the resolver factory both derive their names from here, so a\n * service's schema and its resolver map can never drift apart.\n */\nimport { EntityTagsError } from './errors.js';\n\nconst PREFIX_PATTERN = /^[A-Z][A-Za-z0-9]*$/;\n\n/** Root field names, derived from the service prefix (`Fluidgrids` → `fluidgridsEntityTags`, …). */\nexport interface EntityTagsFieldNames {\n entityTags: string;\n searchTags: string;\n availableTags: string;\n entitiesByTags: string;\n tagEntity: string;\n untagEntity: string;\n replaceEntityTags: string;\n createTag: string;\n}\n\n/** Type / input names the tag surface declares. */\nexport interface EntityTagsTypeNames {\n getEntityTagsInput: string;\n tagEntityInput: string;\n untagEntityInput: string;\n replaceEntityTagsInput: string;\n createTagInput: string;\n entitiesByTagsInput: string;\n tagInfo: string;\n tagAssignment: string;\n availableTag: string;\n taggedEntityPage: string;\n}\n\nexport function assertTagPrefix(prefix: string): void {\n if (!PREFIX_PATTERN.test(prefix)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags prefix must be PascalCase ([A-Z][A-Za-z0-9]*), got \"${prefix}\"`,\n { prefix }\n );\n }\n}\n\nfunction lowerFirst(value: string): string {\n return value.charAt(0).toLowerCase() + value.slice(1);\n}\n\nexport function entityTagsFieldNames(prefix: string): EntityTagsFieldNames {\n assertTagPrefix(prefix);\n const camel = lowerFirst(prefix);\n return {\n entityTags: `${camel}EntityTags`,\n searchTags: `search${prefix}Tags`,\n availableTags: `available${prefix}Tags`,\n entitiesByTags: `${camel}EntitiesByTags`,\n tagEntity: `tag${prefix}Entity`,\n untagEntity: `untag${prefix}Entity`,\n replaceEntityTags: `replace${prefix}EntityTags`,\n createTag: `create${prefix}Tag`,\n };\n}\n\n/**\n * Type names for `prefix`. Defaults carry the prefix everywhere (the FluidGrids\n * convention). `overrides` exists for services that already published legacy\n * names (VibeControls ships `EntityTagAssignment`, `TagEntityInput`, …) and must\n * keep them for existing clients' fragments.\n */\nexport function entityTagsTypeNames(prefix: string, overrides: Partial<EntityTagsTypeNames> = {}): EntityTagsTypeNames {\n assertTagPrefix(prefix);\n const names: EntityTagsTypeNames = {\n getEntityTagsInput: `Get${prefix}EntityTagsInput`,\n tagEntityInput: `Tag${prefix}EntityInput`,\n untagEntityInput: `Untag${prefix}EntityInput`,\n replaceEntityTagsInput: `Replace${prefix}EntityTagsInput`,\n createTagInput: `Create${prefix}TagInput`,\n entitiesByTagsInput: `${prefix}EntitiesByTagsInput`,\n tagInfo: `${prefix}TagInfo`,\n tagAssignment: `${prefix}TagAssignment`,\n availableTag: `${prefix}AvailableTag`,\n taggedEntityPage: `${prefix}TaggedEntityPage`,\n ...overrides,\n };\n\n const seen = new Map<string, string>();\n for (const [role, name] of Object.entries(names)) {\n if (!PREFIX_PATTERN.test(name)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags type name for ${role} is not a valid type name`, {\n role,\n name,\n });\n }\n const clash = seen.get(name);\n if (clash) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity tags type name \"${name}\" is used for both ${clash} and ${role}`,\n {\n name,\n }\n );\n }\n seen.set(name, role);\n }\n return names;\n}\n","/**\n * TagsGatewayAdapter — one implementation of \"tag my entities\" for every service.\n *\n * Thirteen services carried their own copy of this adapter (VibeControls,\n * FluidGrids, BigConsole, files, integrations, …) and the copies drifted:\n * argument order (`userId, workspaceId` vs `workspaceId, userId`), a hard-coded\n * `x-actor-type: user`, `response.data!` non-null assertions, no source\n * validation. This class is the lifted, configurable version: a service\n * supplies its taggable entity types, its default vocabulary and (optionally)\n * the gateway client, and gets the full tag surface.\n *\n * All calls are same-layer M2M to wspace-tags-svc through the internal\n * workspace gateway (`GatewayClient.internalQuery`, which signs the service JWT);\n * the caller's actor and workspace are forwarded explicitly because tags-svc\n * scopes every vocabulary, tag and assignment by `x-workspace-id`.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter } from '@burdenoff/be-sdk/tags';\n *\n * export const entityTags = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN', 'FLUIDGRIDS_DATATABLE'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n *\n * await entityTags.tagEntity('FLUIDGRIDS_RUN', run.id, { tagId }, { actorId, workspaceId });\n * ```\n */\nimport { EntityTagsError } from './errors.js';\nimport type {\n AvailableTag,\n CreateTagOptions,\n EntityTagAssignment,\n FindEntitiesByTagsOptions,\n RawTagAssignment,\n TagActor,\n TagAssignmentSource,\n TagEntityOptions,\n TagsGatewayClient,\n TaggedEntityPage,\n TagVocabularyConfig,\n TagVocabularyRef,\n} from './types.js';\nimport { TAG_ASSIGNMENT_SOURCES } from './types.js';\n\n/** tags-svc caps; requests outside are clamped rather than rejected. */\nconst SEARCH_LIMIT = { default: 20, max: 100 };\nconst AVAILABLE_LIMIT = { default: 50, max: 200 };\nconst ENTITIES_BY_TAGS_LIMIT = { default: 50, max: 200 };\n\n/** Same-layer tag calls should fail fast; the GatewayClient default is 30s. */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 10_000;\n\nconst ENTITY_TYPE_PATTERN = /^[A-Z][A-Z0-9_]*$/;\n\nconst ASSIGNMENT_FIELDS =\n 'id tagId entityType entityId source assignedById createdAt validFrom validTo metadata tag { id key label color }';\n\nexport interface TagsGatewayAdapterOptions {\n /**\n * The entity types this service owns, e.g. `['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN']`.\n * UPPER_SNAKE_CASE and namespaced by product so two services never share a type.\n */\n entityTypes: readonly string[];\n /** Default vocabulary that inline-created tags (no `vocabularyId`) land in. */\n vocabulary: TagVocabularyConfig;\n /** `source` sent when a caller passes none. Default `MANUAL`. */\n defaultSource?: TagAssignmentSource;\n /**\n * Gateway client, or a factory for one. Defaults to a lazily constructed be-sdk\n * `GatewayClient` (`layer: 'wspace'`, `serviceName` below, or the\n * `SERVICE_LAYER`/`SERVICE_NAME` env when `serviceName` is omitted).\n */\n client?: TagsGatewayClient | (() => TagsGatewayClient | Promise<TagsGatewayClient>);\n /** Service name for the default GatewayClient, e.g. `wspace-workflow-svc`. */\n serviceName?: string;\n /** Per-request timeout for tags-svc calls. Default 10s. */\n requestTimeoutMs?: number;\n}\n\nfunction clampLimit(value: number | null | undefined, bounds: { default: number; max: number }): number {\n if (value === null || value === undefined || !Number.isFinite(value)) return bounds.default;\n return Math.min(Math.max(Math.trunc(value), 1), bounds.max);\n}\n\nfunction toDate(value: string | null | undefined): Date | null {\n if (!value) return null;\n const date = new Date(value);\n return Number.isNaN(date.getTime()) ? null : date;\n}\n\nfunction requireNonEmpty(value: string | null | undefined, field: string): string {\n const trimmed = typeof value === 'string' ? value.trim() : '';\n if (!trimmed) {\n throw new EntityTagsError('INVALID_INPUT', `${field} is required`, { field });\n }\n return trimmed;\n}\n\n/** FNV-1a, used only to give non-ASCII labels a stable, non-empty key. */\nfunction shortHash(value: string): string {\n let hash = 0x811c9dc5;\n for (const char of value) {\n hash ^= char.codePointAt(0) ?? 0;\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(36);\n}\n\n/**\n * Tag key for a label: lowercase ASCII slug (`\"Needs Review!\"` → `needs-review`).\n * Labels with no ASCII letters or digits (`\"日本\"`) get `tag-<hash>` so the key is\n * never empty (tags-svc rejects an empty key) and stays stable for the same label.\n */\nexport function slugifyTagKey(label: string): string {\n const slug = label\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-|-$/g, '');\n return slug || `tag-${shortHash(label.trim())}`;\n}\n\n/** Map a tags-svc `UniversalTagAssignment` onto the published assignment shape. */\nexport function mapTagAssignment(raw: RawTagAssignment): EntityTagAssignment {\n return {\n id: raw.id,\n tagId: raw.tagId,\n entityType: raw.entityType,\n entityId: raw.entityId,\n source: raw.source,\n assignedBy: raw.assignedById ?? null,\n assignedAt: toDate(raw.createdAt) ?? toDate(raw.validFrom),\n validFrom: toDate(raw.validFrom),\n validTo: toDate(raw.validTo),\n metadata: raw.metadata ?? null,\n tag: raw.tag ? { id: raw.tag.id } : null,\n tagInfo: raw.tag\n ? {\n id: raw.tag.id,\n key: raw.tag.key ?? null,\n label: raw.tag.label ?? null,\n color: raw.tag.color ?? null,\n }\n : null,\n };\n}\n\nexport class TagsGatewayAdapter {\n readonly entityTypes: readonly string[];\n readonly vocabulary: Readonly<TagVocabularyConfig>;\n readonly defaultSource: TagAssignmentSource;\n\n private readonly entityTypeSet: ReadonlySet<string>;\n private readonly requestTimeoutMs: number;\n private readonly clientOption: TagsGatewayAdapterOptions['client'];\n private readonly serviceName: string | undefined;\n private clientPromise: Promise<TagsGatewayClient> | null = null;\n\n constructor(options: TagsGatewayAdapterOptions) {\n if (options.entityTypes.length === 0) {\n throw new EntityTagsError('CONFIGURATION_ERROR', 'TagsGatewayAdapter needs at least one entity type');\n }\n for (const entityType of options.entityTypes) {\n if (!ENTITY_TYPE_PATTERN.test(entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `Entity type \"${entityType}\" must be UPPER_SNAKE_CASE (e.g. FLUIDGRIDS_WORKFLOW)`,\n { entityType }\n );\n }\n }\n requireNonEmpty(options.vocabulary.key, 'vocabulary.key');\n requireNonEmpty(options.vocabulary.name, 'vocabulary.name');\n const defaultSource = options.defaultSource ?? 'MANUAL';\n if (!TAG_ASSIGNMENT_SOURCES.includes(defaultSource)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Unknown default tag source \"${defaultSource}\"`);\n }\n\n this.entityTypes = Object.freeze([...new Set(options.entityTypes)]);\n this.entityTypeSet = new Set(this.entityTypes);\n this.vocabulary = Object.freeze({ ...options.vocabulary });\n this.defaultSource = defaultSource;\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n this.clientOption = options.client;\n this.serviceName = options.serviceName;\n }\n\n // ── Validation ────────────────────────────────────────────────────────\n\n isValidEntityType(entityType: string): boolean {\n return this.entityTypeSet.has(entityType);\n }\n\n assertEntityType(entityType: string): void {\n if (!this.isValidEntityType(entityType)) {\n throw new EntityTagsError('INVALID_ENTITY_TYPE', `Unsupported entity type \"${entityType}\"`, {\n entityType,\n supported: this.entityTypes,\n });\n }\n }\n\n /** Validate a caller-supplied source; empty means the adapter default. */\n resolveSource(source: string | null | undefined): TagAssignmentSource {\n if (source === null || source === undefined || source === '') return this.defaultSource;\n const normalized = source.toUpperCase();\n const match = TAG_ASSIGNMENT_SOURCES.find((candidate) => candidate === normalized);\n if (!match) {\n throw new EntityTagsError('INVALID_SOURCE', `Unknown tag source \"${source}\"`, {\n source,\n supported: TAG_ASSIGNMENT_SOURCES,\n });\n }\n return match;\n }\n\n // ── Assignments ───────────────────────────────────────────────────────\n\n /** Tags currently assigned to an entity. */\n async getEntityTags(entityType: string, entityId: string, actor: TagActor): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const data = await this.request<{ getEntityTags: RawTagAssignment[] | null }>(\n `query GetEntityTags($entityType: String!, $entityId: ID!) {\n getEntityTags(entityType: $entityType, entityId: $entityId) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id },\n actor\n );\n return (data.getEntityTags ?? []).map(mapTagAssignment);\n }\n\n /** Assign one tag to an entity. */\n async tagEntity(\n entityType: string,\n entityId: string,\n options: TagEntityOptions,\n actor: TagActor\n ): Promise<EntityTagAssignment> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const tagId = requireNonEmpty(options.tagId, 'tagId');\n const source = this.resolveSource(options.source);\n const context = this.requireActor(actor);\n\n const data = await this.request<{ assignTag: RawTagAssignment | null }>(\n `mutation AssignTag($input: AssignTagInput!) {\n assignTag(input: $input) { ${ASSIGNMENT_FIELDS} }\n }`,\n {\n input: {\n tagId,\n entityType,\n entityId: id,\n source,\n validFrom: options.validFrom?.toISOString(),\n validTo: options.validTo?.toISOString(),\n metadata: options.metadata ?? undefined,\n context: { workspaceId: context.workspaceId },\n },\n },\n context\n );\n if (!data.assignTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no assignment', { entityType, tagId });\n }\n return mapTagAssignment(data.assignTag);\n }\n\n /**\n * Remove a tag from an entity. Removes every assignment of that tag on the entity\n * (tags-svc allows several with different validity windows). `false` when the tag\n * was not assigned.\n */\n async untagEntity(entityType: string, entityId: string, tagId: string, actor: TagActor): Promise<boolean> {\n const id = requireNonEmpty(tagId, 'tagId');\n const assignments = await this.getEntityTags(entityType, entityId, actor);\n const matches = assignments.filter((assignment) => assignment.tagId === id);\n if (matches.length === 0) return false;\n\n let removed = false;\n for (const assignment of matches) {\n const data = await this.request<{ removeTagAssignment: boolean | null }>(\n `mutation RemoveTagAssignment($id: ID!) { removeTagAssignment(id: $id) }`,\n { id: assignment.id },\n actor\n );\n removed = data.removeTagAssignment === true || removed;\n }\n return removed;\n }\n\n /** Replace the full tag set on an entity (an empty list clears it). */\n async replaceEntityTags(\n entityType: string,\n entityId: string,\n tagIds: readonly string[],\n actor: TagActor\n ): Promise<EntityTagAssignment[]> {\n this.assertEntityType(entityType);\n const id = requireNonEmpty(entityId, 'entityId');\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n const data = await this.request<{ replaceEntityTags: RawTagAssignment[] | null }>(\n `mutation ReplaceEntityTags($entityType: String!, $entityId: ID!, $tagIds: [ID!]!) {\n replaceEntityTags(entityType: $entityType, entityId: $entityId, tagIds: $tagIds) { ${ASSIGNMENT_FIELDS} }\n }`,\n { entityType, entityId: id, tagIds: uniqueTagIds },\n actor\n );\n return (data.replaceEntityTags ?? []).map(mapTagAssignment);\n }\n\n /**\n * Ids of `entityType` entities carrying the given tags — the server-side half of\n * \"filter this list by tag\". Intersect the ids with the service's own query.\n */\n async findEntityIdsByTags(\n entityType: string,\n tagIds: readonly string[],\n actor: TagActor,\n options: FindEntitiesByTagsOptions = {}\n ): Promise<TaggedEntityPage> {\n this.assertEntityType(entityType);\n const uniqueTagIds = [...new Set(tagIds.map((tagId) => requireNonEmpty(tagId, 'tagIds[]')))];\n if (uniqueTagIds.length === 0) {\n throw new EntityTagsError('INVALID_INPUT', 'tagIds must contain at least one tag', { field: 'tagIds' });\n }\n const data = await this.request<{\n getEntitiesByTags: {\n entities: Array<{ entityId: string; entityType: string }>;\n total: number;\n hasMore: boolean;\n nextCursor?: string | null;\n } | null;\n }>(\n `query GetEntitiesByTags($tagIds: [ID!]!, $entityType: String, $matchAll: Boolean, $pagination: TagsPaginationInput) {\n getEntitiesByTags(tagIds: $tagIds, entityType: $entityType, matchAll: $matchAll, pagination: $pagination) {\n entities { entityId entityType } total hasMore nextCursor\n }\n }`,\n {\n tagIds: uniqueTagIds,\n entityType,\n matchAll: options.matchAll ?? false,\n pagination: {\n limit: clampLimit(options.limit, ENTITIES_BY_TAGS_LIMIT),\n ...(options.cursor ? { cursor: options.cursor } : {}),\n },\n },\n actor\n );\n const page = data.getEntitiesByTags;\n if (!page) return { entityIds: [], total: 0, hasMore: false, nextCursor: null };\n return {\n // tags-svc already filters by entityType; re-check so a lax upstream never\n // leaks another product's ids into this service's list.\n entityIds: page.entities.filter((entity) => entity.entityType === entityType).map((entity) => entity.entityId),\n total: page.total,\n hasMore: page.hasMore,\n nextCursor: page.nextCursor ?? null,\n };\n }\n\n // ── Workspace tags ────────────────────────────────────────────────────\n\n /** Search assignable tags in the workspace. */\n async searchTags(query: string, actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ searchTags: AvailableTag[] | null }>(\n `query SearchTags($query: String!, $limit: Int) {\n searchTags(query: $query, limit: $limit) { id key label color }\n }`,\n { query: query.trim(), limit: clampLimit(limit, SEARCH_LIMIT) },\n actor\n );\n return data.searchTags ?? [];\n }\n\n /** List assignable tags in the workspace. */\n async getAvailableTags(actor: TagActor, limit?: number | null): Promise<AvailableTag[]> {\n const data = await this.request<{ getTags: { items: AvailableTag[] | null } | null }>(\n `query GetTags($pagination: TagsPaginationInput) {\n getTags(pagination: $pagination) { items { id key label color } }\n }`,\n { pagination: { limit: clampLimit(limit, AVAILABLE_LIMIT) } },\n actor\n );\n return data.getTags?.items ?? [];\n }\n\n /** Create a workspace tag, in the default vocabulary unless `vocabularyId` is given. */\n async createTag(options: CreateTagOptions, actor: TagActor): Promise<AvailableTag> {\n const label = requireNonEmpty(options.label, 'label');\n const vocabularyId =\n options.vocabularyId !== undefined && options.vocabularyId !== null\n ? options.vocabularyId\n : await this.ensureWorkspaceVocabulary(actor);\n\n const data = await this.request<{ createTag: AvailableTag | null }>(\n `mutation CreateTag($input: CreateTagInput!) {\n createTag(input: $input) { id key label color }\n }`,\n {\n input: {\n vocabularyId,\n key: slugifyTagKey(label),\n label,\n color: options.color || undefined,\n },\n },\n actor\n );\n if (!data.createTag) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no tag', { label });\n }\n return data.createTag;\n }\n\n // ── Vocabularies ──────────────────────────────────────────────────────\n\n /**\n * Resolve the workspace's default vocabulary id, creating the vocabulary on first\n * use. Order: pinned `id` (if it exists in this workspace) → lookup by `key` →\n * create → re-read by key (a concurrent request may have created it first).\n */\n async ensureWorkspaceVocabulary(actor: TagActor, override: Partial<TagVocabularyConfig> = {}): Promise<string> {\n const vocabulary = { ...this.vocabulary, ...override };\n\n if (vocabulary.id) {\n const byId = await this.getVocabularyById(vocabulary.id, actor);\n if (byId?.id) return byId.id;\n }\n\n const byKey = await this.getVocabularyByKey(vocabulary.key, actor);\n if (byKey?.id) return byKey.id;\n\n let createError: unknown = null;\n try {\n const created = await this.createVocabulary(vocabulary, actor);\n if (created?.id) return created.id;\n } catch (error) {\n // Most likely a unique-key race with a concurrent request; the re-read below\n // decides. Kept so the failure is not swallowed when the re-read finds nothing.\n createError = error;\n }\n\n const afterCreate = await this.getVocabularyByKey(vocabulary.key, actor);\n if (afterCreate?.id) return afterCreate.id;\n\n if (createError) throw createError;\n throw new EntityTagsError('UPSTREAM_ERROR', `Failed to resolve tag vocabulary \"${vocabulary.key}\"`, {\n vocabularyKey: vocabulary.key,\n });\n }\n\n async getVocabularyById(id: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabulary: TagVocabularyRef | null }>(\n `query GetVocabulary($id: ID!) { getVocabulary(id: $id) { id key name } }`,\n { id },\n actor\n );\n return data.getVocabulary ?? null;\n }\n\n async getVocabularyByKey(key: string, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ getVocabularyByKey: TagVocabularyRef | null }>(\n `query GetVocabularyByKey($key: String!) { getVocabularyByKey(key: $key) { id key name } }`,\n { key },\n actor\n );\n return data.getVocabularyByKey ?? null;\n }\n\n /** Create a WORKSPACE-scoped, multi-valued, open (custom tags allowed) string vocabulary. */\n async createVocabulary(vocabulary: TagVocabularyConfig, actor: TagActor): Promise<TagVocabularyRef | null> {\n const data = await this.request<{ createVocabulary: TagVocabularyRef | null }>(\n `mutation CreateVocabulary($input: CreateVocabularyInput!) {\n createVocabulary(input: $input) { id key name }\n }`,\n {\n input: {\n key: requireNonEmpty(vocabulary.key, 'vocabulary.key'),\n name: requireNonEmpty(vocabulary.name, 'vocabulary.name'),\n description: vocabulary.description,\n scope: 'WORKSPACE',\n dataType: 'STRING',\n cardinality: 'MULTIPLE',\n allowCustomTags: true,\n },\n },\n actor\n );\n return data.createVocabulary ?? null;\n }\n\n // ── Transport ─────────────────────────────────────────────────────────\n\n private requireActor(actor: TagActor): TagActor {\n if (!actor.actorId?.trim() || !actor.workspaceId?.trim()) {\n throw new EntityTagsError('MISSING_CONTEXT', 'Tag operations need an authenticated actor and a workspace');\n }\n return actor;\n }\n\n private getClient(): Promise<TagsGatewayClient> {\n if (!this.clientPromise) {\n const option = this.clientOption;\n this.clientPromise = (async (): Promise<TagsGatewayClient> => {\n if (typeof option === 'function') return option();\n if (option) return option;\n // Dynamic import keeps the gateway client (and its JWT/crypto deps) out of\n // the static module graph of `@burdenoff/be-sdk/tags` consumers.\n const gateway = await import('../gateway/client.js');\n if (this.serviceName) {\n return new gateway.GatewayClient({\n layer: 'wspace',\n serviceName: this.serviceName,\n serviceIdentity: this.serviceName,\n });\n }\n return gateway.createGatewayClientFromEnv();\n })();\n // A failed construction (bad env) must not be cached forever.\n this.clientPromise.catch(() => {\n this.clientPromise = null;\n });\n }\n return this.clientPromise;\n }\n\n private async request<T>(query: string, variables: Record<string, unknown>, actor: TagActor): Promise<T> {\n const { actorId, workspaceId, actorType } = this.requireActor(actor);\n const client = await this.getClient();\n const response = await client.internalQuery<T>({\n query,\n variables,\n timeout: this.requestTimeoutMs,\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType || 'user',\n 'x-workspace-id': workspaceId,\n },\n });\n if (response.errors?.length) {\n throw new EntityTagsError(\n 'UPSTREAM_ERROR',\n `wspace-tags-svc error: ${response.errors.map((error) => error.message).join('; ')}`,\n { errors: response.errors }\n );\n }\n if (!response.data) {\n throw new EntityTagsError('UPSTREAM_ERROR', 'wspace-tags-svc returned no data');\n }\n return response.data;\n }\n}\n","/**\n * Entity tags — SDL generator.\n *\n * One fixed SDL fragment cannot be shared: two subgraphs declaring the same\n * non-`@shareable` value type (`EntityTagAssignment`, `AvailableTag`, …) fail\n * Federation composition. {@link buildEntityTagsSdl} therefore emits the whole\n * tag surface under a per-service prefix (names from `./naming.ts`), with a\n * static `@rbac` directive on every root field — the gateway enforces RBAC from\n * the composed supergraph and needs a literal action/resource per field.\n *\n * The SDL references `@rbac`, `JSON`, `DateTime` and the federated\n * `UniversalTag` entity, which the host subgraph already declares (pass\n * `includeUniversalTagStub: true` if it does not declare `UniversalTag` yet).\n */\nimport { EntityTagsError } from './errors.js';\nimport { entityTagsFieldNames, entityTagsTypeNames, type EntityTagsTypeNames } from './naming.js';\n\nconst TYPE_NAME_PATTERN = /^[A-Z]\\w*$/;\nconst RBAC_TOKEN_PATTERN = /^[a-z0-9][a-z0-9:_-]*$/i;\n\n/** The `@rbac` arguments stamped on the generated root fields. */\nexport interface EntityTagsRbacOptions {\n /** RBAC resource the service already gates its entities on, e.g. `workflow`, `agent`. */\n resource: string;\n /** Default `wspace`. */\n scopeType?: string;\n /** Action for the read fields. Default `read`. */\n readAction?: string;\n /** Action for tag/untag/replace. Default `update`. */\n updateAction?: string;\n /** Action for creating a workspace tag. Default `create`. */\n createAction?: string;\n}\n\nexport interface EntityTagsSdlOptions {\n /** PascalCase service prefix, e.g. `Fluidgrids` → `fluidgridsEntityTags`, `FluidgridsTagAssignment`. */\n prefix: string;\n /** Product name used in field descriptions. Defaults to `prefix`. */\n productLabel?: string;\n rbac: EntityTagsRbacOptions;\n /** Types (owned elsewhere in the subgraph) that get a `tagAssignments` field. */\n extendTypes?: readonly string[];\n /** Override generated type names, for services with already-published legacy names. */\n typeNames?: Partial<EntityTagsTypeNames>;\n /** Types the subgraph already declares elsewhere: referenced, not declared. */\n externalTypes?: readonly (keyof EntityTagsTypeNames)[];\n /** Also emit the `…EntitiesByTags` query (server-side filter-by-tag). Default `false`. */\n includeEntitiesByTags?: boolean;\n /** Also declare the non-resolvable `UniversalTag @key(fields: \"id\")` stub. Default `false`. */\n includeUniversalTagStub?: boolean;\n}\n\n/** Non-resolvable stub for the tags-svc-owned `UniversalTag` entity. */\nexport const UNIVERSAL_TAG_STUB_SDL = /* GraphQL */ `\n \"UniversalTag is owned by wspace-tags-svc; only its key is resolvable here.\"\n type UniversalTag @key(fields: \"id\", resolvable: false) {\n id: ID!\n }\n`;\n\nfunction rbacToken(value: string, field: string): string {\n if (!RBAC_TOKEN_PATTERN.test(value)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Entity tags rbac.${field} \"${value}\" is not a valid RBAC token`, {\n field,\n value,\n });\n }\n return value;\n}\n\nfunction rbacDirective(action: string, resource: string, scopeType: string): string {\n return `@rbac(action: \"${action}\", resource: \"${resource}\", scopeType: \"${scopeType}\")`;\n}\n\nfunction sanitizeDescription(value: string): string {\n // Config-time text inside a \"...\" description: no quote or backslash may end/escape it.\n return value.replace(/[\"\\\\]/g, \"'\").replace(/\\s+/g, ' ').trim();\n}\n\nexport function buildEntityTagsSdl(options: EntityTagsSdlOptions): string {\n const fields = entityTagsFieldNames(options.prefix);\n const types = entityTagsTypeNames(options.prefix, options.typeNames);\n const external = new Set<keyof EntityTagsTypeNames>(options.externalTypes ?? []);\n const label = sanitizeDescription(options.productLabel ?? options.prefix);\n\n const resource = rbacToken(options.rbac.resource, 'resource');\n const scopeType = rbacToken(options.rbac.scopeType ?? 'wspace', 'scopeType');\n const read = rbacDirective(rbacToken(options.rbac.readAction ?? 'read', 'readAction'), resource, scopeType);\n const update = rbacDirective(rbacToken(options.rbac.updateAction ?? 'update', 'updateAction'), resource, scopeType);\n const create = rbacDirective(rbacToken(options.rbac.createAction ?? 'create', 'createAction'), resource, scopeType);\n\n const extendTypes = [...new Set(options.extendTypes ?? [])];\n for (const typeName of extendTypes) {\n if (!TYPE_NAME_PATTERN.test(typeName)) {\n throw new EntityTagsError('CONFIGURATION_ERROR', `Cannot extend \"${typeName}\": not a valid type name`, {\n typeName,\n });\n }\n }\n\n const blocks: string[] = [];\n const emitType = (role: keyof EntityTagsTypeNames, sdl: string): void => {\n if (!external.has(role)) blocks.push(sdl);\n };\n\n if (options.includeUniversalTagStub) blocks.push(UNIVERSAL_TAG_STUB_SDL.trim());\n\n emitType(\n 'getEntityTagsInput',\n `input ${types.getEntityTagsInput} {\n entityType: String!\n entityId: ID!\n}`\n );\n emitType(\n 'tagEntityInput',\n `input ${types.tagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n \"AssignmentSource (MANUAL, AUTOMATIC, IMPORTED, ...). Defaults to the service default.\"\n source: String\n metadata: JSON\n}`\n );\n emitType(\n 'untagEntityInput',\n `input ${types.untagEntityInput} {\n entityType: String!\n entityId: ID!\n tagId: ID!\n}`\n );\n emitType(\n 'replaceEntityTagsInput',\n `input ${types.replaceEntityTagsInput} {\n entityType: String!\n entityId: ID!\n tagIds: [ID!]!\n}`\n );\n emitType(\n 'createTagInput',\n `input ${types.createTagInput} {\n \"Optional. When omitted the tag goes to the workspace's default ${label} vocabulary (created on first use).\"\n vocabularyId: ID\n label: String!\n color: String\n}`\n );\n emitType(\n 'tagInfo',\n `\"Inline (non-federated) tag projection, so clients render labels without a federated round-trip.\"\ntype ${types.tagInfo} {\n id: ID!\n key: String\n label: String\n color: String\n}`\n );\n emitType(\n 'tagAssignment',\n `\"A tag assigned to a ${label} entity.\"\ntype ${types.tagAssignment} {\n id: ID!\n tagId: ID!\n \"Federated UniversalTag reference (owned by wspace-tags-svc). Prefer tagInfo for label/colour.\"\n tag: UniversalTag\n \"Inline projection of the tag (key/label/colour).\"\n tagInfo: ${types.tagInfo}\n entityType: String!\n entityId: ID!\n source: String!\n assignedBy: ID\n assignedAt: DateTime\n validFrom: DateTime\n validTo: DateTime\n metadata: JSON\n}`\n );\n emitType(\n 'availableTag',\n `\"An assignable workspace tag.\"\ntype ${types.availableTag} {\n id: ID!\n key: String!\n label: String!\n color: String\n}`\n );\n\n if (options.includeEntitiesByTags) {\n emitType(\n 'entitiesByTagsInput',\n `input ${types.entitiesByTagsInput} {\n entityType: String!\n tagIds: [ID!]!\n \"true = entity must carry every tag; false (default) = any of them.\"\n matchAll: Boolean\n limit: Int\n cursor: String\n}`\n );\n emitType(\n 'taggedEntityPage',\n `\"Ids of entities carrying the requested tags.\"\ntype ${types.taggedEntityPage} {\n entityIds: [ID!]!\n total: Int!\n hasMore: Boolean!\n nextCursor: String\n}`\n );\n }\n\n const queryFields = [\n ` \"Tags currently assigned to a ${label} entity\"\n ${fields.entityTags}(input: ${types.getEntityTagsInput}!): [${types.tagAssignment}!]! ${read}`,\n ` \"Search assignable tags in the workspace\"\n ${fields.searchTags}(query: String!, limit: Int): [${types.availableTag}!]! ${read}`,\n ` \"List assignable tags in the workspace\"\n ${fields.availableTags}(limit: Int): [${types.availableTag}!]! ${read}`,\n ];\n if (options.includeEntitiesByTags) {\n queryFields.push(` \"Ids of ${label} entities carrying the given tags (filter-by-tag)\"\n ${fields.entitiesByTags}(input: ${types.entitiesByTagsInput}!): ${types.taggedEntityPage}! ${read}`);\n }\n blocks.push(`extend type Query {\\n${queryFields.join('\\n\\n')}\\n}`);\n\n blocks.push(`extend type Mutation {\n \"Assign a tag to a ${label} entity\"\n ${fields.tagEntity}(input: ${types.tagEntityInput}!): ${types.tagAssignment}! ${update}\n\n \"Remove a tag from a ${label} entity\"\n ${fields.untagEntity}(input: ${types.untagEntityInput}!): Boolean! ${update}\n\n \"Replace the full tag set on a ${label} entity\"\n ${fields.replaceEntityTags}(input: ${types.replaceEntityTagsInput}!): [${types.tagAssignment}!]! ${update}\n\n \"Create a new assignable tag (inline creation from a picker)\"\n ${fields.createTag}(input: ${types.createTagInput}!): ${types.availableTag}! ${create}\n}`);\n\n for (const typeName of extendTypes) {\n blocks.push(`extend type ${typeName} {\n \"Structured tag assignments (wspace-tags-svc).\"\n tagAssignments: [${types.tagAssignment}!]!\n}`);\n }\n\n return `${blocks.join('\\n\\n')}\\n`;\n}\n","/**\n * Entity tags — resolver factory.\n *\n * Builds the Query / Mutation / `tagAssignments` resolvers that match the SDL\n * from {@link buildEntityTagsSdl} for the same `prefix` (both derive names from\n * `./naming.ts`). The service supplies only what differs: how to read the actor\n * off its context, which GraphQL types map to which entity types, how to map\n * errors onto its i18n errors, and optional ownership/audit hooks.\n *\n * @example\n * ```ts\n * import { buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const { Query, Mutation, types } = createEntityTagResolvers({\n * prefix: 'Fluidgrids',\n * adapter: entityTags,\n * entities: {\n * WorkflowDefinition: { entityType: 'FLUIDGRIDS_WORKFLOW', entityId: (p) => String(p.workflowKey ?? '') },\n * WorkflowRun: { entityType: 'FLUIDGRIDS_RUN' },\n * },\n * mapError: (error, ctx) => workflowError(`tags.errors.${error.code}`, error.graphqlCode, ctx, error.details),\n * });\n * ```\n */\nimport { GraphQLError } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { TagsGatewayAdapter } from './adapter.js';\nimport { EntityTagsError, isEntityTagsError } from './errors.js';\nimport { entityTagsFieldNames } from './naming.js';\nimport type { AvailableTag, EntityTagAssignment, TagActor, TagActorType, TaggedEntityPage } from './types.js';\nimport { TAG_ACTOR_TYPES } from './types.js';\n\n/** Maps a GraphQL object type onto the entity type and id its tags are stored under. */\nexport interface EntityTagBinding {\n entityType: string;\n /**\n * Entity id for a parent object. Defaults to `parent.id`. Use a stable logical id\n * when rows are versioned (FluidGrids tags `workflowKey`, not the per-version row id).\n */\n entityId?: (parent: Record<string, unknown>) => string | null | undefined;\n}\n\nexport type EntityTagOperation = 'tag' | 'untag' | 'replace' | 'createTag';\n\n/** Emitted after a successful write, for audit/activity logging. */\nexport interface EntityTagMutationEvent {\n operation: EntityTagOperation;\n /** Root field name, e.g. `tagFluidgridsEntity`. */\n fieldName: string;\n actor: TagActor;\n entityType?: string;\n entityId?: string;\n tagId?: string;\n tagIds?: string[];\n source?: string;\n /** For `createTag`. */\n tag?: AvailableTag;\n vocabularyId?: string;\n}\n\n/** Passed to `authorizeEntity` before any entity-addressed operation. */\nexport interface EntityTagAccessCheck {\n entityType: string;\n entityId: string;\n access: 'read' | 'write';\n actor: TagActor;\n}\n\nexport interface CreateEntityTagResolversOptions<TContext> {\n /** Same prefix as passed to `buildEntityTagsSdl`. */\n prefix: string;\n adapter: TagsGatewayAdapter;\n /** GraphQL type name → binding, for the `tagAssignments` field on each extended type. */\n entities?: Readonly<Record<string, EntityTagBinding>>;\n /**\n * Reads the caller off the request context. Default: be-sdk server context\n * (`context.actor.{id,type}`, `context.workspace.id`), falling back to flat\n * `context.actorId` / `context.workspaceId`.\n */\n getActor?: (context: TContext) => TagActor;\n /**\n * Ownership check for entity-addressed operations (throw to deny). Use it to\n * confirm the entity exists in the caller's workspace before tags are read or\n * written for an arbitrary `entityId`; throw NOT_FOUND, never FORBIDDEN.\n */\n authorizeEntity?: (check: EntityTagAccessCheck, context: TContext) => void | Promise<void>;\n /** Called after each successful write. Failures are logged, never surfaced. */\n onMutation?: (event: EntityTagMutationEvent, context: TContext) => void | Promise<void>;\n /** Map an adapter error onto the service's own (i18n) GraphQL error. */\n mapError?: (error: EntityTagsError, context: TContext) => Error;\n /** Must match `includeEntitiesByTags` on the SDL. Default `false`. */\n includeEntitiesByTags?: boolean;\n}\n\ntype Resolver<TArgs, TResult, TContext> = (parent: unknown, args: TArgs, context: TContext) => Promise<TResult>;\n\ntype TagAssignmentsResolver<TContext> = (\n parent: Record<string, unknown>,\n args: unknown,\n context: TContext\n) => Promise<EntityTagAssignment[]>;\n\ninterface EntityRefInput {\n entityType: string;\n entityId: string;\n}\n\nexport interface EntityTagResolvers<TContext> {\n Query: Record<string, Resolver<never, unknown, TContext>>;\n Mutation: Record<string, Resolver<never, unknown, TContext>>;\n /** `{ [GraphQLTypeName]: { tagAssignments } }`, ready to spread into the resolver map. */\n types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }>;\n}\n\nfunction readRecord(value: unknown, key: string): unknown {\n if (value === null || typeof value !== 'object') return undefined;\n return (value as Record<string, unknown>)[key];\n}\n\nfunction readString(value: unknown): string {\n return typeof value === 'string' ? value : '';\n}\n\nfunction toActorType(value: unknown): TagActorType {\n return TAG_ACTOR_TYPES.find((candidate) => candidate === value) ?? 'user';\n}\n\n/** Default actor reader for the be-sdk server context shape. */\nexport function defaultTagActor(context: unknown): TagActor {\n const actor = readRecord(context, 'actor');\n const workspace = readRecord(context, 'workspace');\n return {\n actorId: readString(readRecord(actor, 'id')) || readString(readRecord(context, 'actorId')),\n actorType: toActorType(readRecord(actor, 'type') ?? readRecord(context, 'actorType')),\n workspaceId: readString(readRecord(workspace, 'id')) || readString(readRecord(context, 'workspaceId')),\n };\n}\n\nfunction defaultMapError(error: EntityTagsError): Error {\n if (error.code === 'UPSTREAM_ERROR' || error.code === 'CONFIGURATION_ERROR') {\n // Upstream payloads can carry internal detail; log it, return a generic message.\n logger.error('[be-sdk/tags] Tag operation failed', { code: error.code, message: error.message });\n return new GraphQLError('Tag operation failed', { extensions: { code: error.graphqlCode } });\n }\n return new GraphQLError(error.message, { extensions: { code: error.graphqlCode, reason: error.code } });\n}\n\nexport function createEntityTagResolvers<TContext>(\n options: CreateEntityTagResolversOptions<TContext>\n): EntityTagResolvers<TContext> {\n const { adapter } = options;\n const fields = entityTagsFieldNames(options.prefix);\n const getActor = options.getActor ?? ((context: TContext) => defaultTagActor(context));\n const mapError = options.mapError ?? ((error: EntityTagsError) => defaultMapError(error));\n\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n if (!adapter.isValidEntityType(binding.entityType)) {\n throw new EntityTagsError(\n 'CONFIGURATION_ERROR',\n `${typeName} is bound to entity type \"${binding.entityType}\", which the adapter does not register`,\n { typeName, entityType: binding.entityType }\n );\n }\n }\n\n const guard = async <T>(context: TContext, run: () => Promise<T>): Promise<T> => {\n try {\n return await run();\n } catch (error) {\n if (isEntityTagsError(error)) throw mapError(error, context);\n throw error;\n }\n };\n\n const authorize = async (\n input: EntityRefInput,\n access: EntityTagAccessCheck['access'],\n actor: TagActor,\n context: TContext\n ): Promise<void> => {\n adapter.assertEntityType(input.entityType);\n if (!input.entityId?.trim()) {\n throw new EntityTagsError('INVALID_INPUT', 'entityId is required', { field: 'entityId' });\n }\n if (options.authorizeEntity) {\n await options.authorizeEntity({ entityType: input.entityType, entityId: input.entityId, access, actor }, context);\n }\n };\n\n const notify = async (event: EntityTagMutationEvent, context: TContext): Promise<void> => {\n if (!options.onMutation) return;\n try {\n await options.onMutation(event, context);\n } catch (error) {\n logger.warn('[be-sdk/tags] onMutation hook failed', {\n fieldName: event.fieldName,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n };\n\n const Query: Record<string, Resolver<never, unknown, TContext>> = {};\n const Mutation: Record<string, Resolver<never, unknown, TContext>> = {};\n\n const entityTags: Resolver<{ input: EntityRefInput }, EntityTagAssignment[], TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'read', actor, context);\n return adapter.getEntityTags(input.entityType, input.entityId, actor);\n });\n Query[fields.entityTags] = entityTags;\n\n const searchTags: Resolver<{ query: string; limit?: number | null }, AvailableTag[], TContext> = (\n _parent,\n { query, limit },\n context\n ) => guard(context, () => adapter.searchTags(query, getActor(context), limit));\n Query[fields.searchTags] = searchTags;\n\n const availableTags: Resolver<{ limit?: number | null }, AvailableTag[], TContext> = (_parent, { limit }, context) =>\n guard(context, () => adapter.getAvailableTags(getActor(context), limit));\n Query[fields.availableTags] = availableTags;\n\n if (options.includeEntitiesByTags) {\n const entitiesByTags: Resolver<\n {\n input: {\n entityType: string;\n tagIds: string[];\n matchAll?: boolean | null;\n limit?: number | null;\n cursor?: string | null;\n };\n },\n TaggedEntityPage,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, () =>\n adapter.findEntityIdsByTags(input.entityType, input.tagIds, getActor(context), {\n matchAll: input.matchAll ?? false,\n limit: input.limit,\n cursor: input.cursor,\n })\n );\n Query[fields.entitiesByTags] = entitiesByTags;\n }\n\n const tagEntity: Resolver<\n { input: EntityRefInput & { tagId: string; source?: string | null; metadata?: Record<string, unknown> | null } },\n EntityTagAssignment,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignment = await adapter.tagEntity(\n input.entityType,\n input.entityId,\n { tagId: input.tagId, source: input.source, metadata: input.metadata },\n actor\n );\n await notify(\n {\n operation: 'tag',\n fieldName: fields.tagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n source: assignment.source,\n },\n context\n );\n return assignment;\n });\n Mutation[fields.tagEntity] = tagEntity;\n\n const untagEntity: Resolver<{ input: EntityRefInput & { tagId: string } }, boolean, TContext> = (\n _parent,\n { input },\n context\n ) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const removed = await adapter.untagEntity(input.entityType, input.entityId, input.tagId, actor);\n if (removed) {\n await notify(\n {\n operation: 'untag',\n fieldName: fields.untagEntity,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagId: input.tagId,\n },\n context\n );\n }\n return removed;\n });\n Mutation[fields.untagEntity] = untagEntity;\n\n const replaceEntityTags: Resolver<\n { input: EntityRefInput & { tagIds: string[] } },\n EntityTagAssignment[],\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n await authorize(input, 'write', actor, context);\n const assignments = await adapter.replaceEntityTags(input.entityType, input.entityId, input.tagIds, actor);\n await notify(\n {\n operation: 'replace',\n fieldName: fields.replaceEntityTags,\n actor,\n entityType: input.entityType,\n entityId: input.entityId,\n tagIds: [...new Set(input.tagIds)],\n },\n context\n );\n return assignments;\n });\n Mutation[fields.replaceEntityTags] = replaceEntityTags;\n\n const createTag: Resolver<\n { input: { vocabularyId?: string | null; label: string; color?: string | null } },\n AvailableTag,\n TContext\n > = (_parent, { input }, context) =>\n guard(context, async () => {\n const actor = getActor(context);\n const vocabularyId =\n input.vocabularyId !== undefined && input.vocabularyId !== null\n ? input.vocabularyId\n : await adapter.ensureWorkspaceVocabulary(actor);\n const tag = await adapter.createTag({ label: input.label, color: input.color, vocabularyId }, actor);\n await notify({ operation: 'createTag', fieldName: fields.createTag, actor, tag, vocabularyId }, context);\n return tag;\n });\n Mutation[fields.createTag] = createTag;\n\n const types: Record<string, { tagAssignments: TagAssignmentsResolver<TContext> }> = {};\n for (const [typeName, binding] of Object.entries(options.entities ?? {})) {\n const selectId = binding.entityId ?? ((parent: Record<string, unknown>) => readString(parent['id']));\n types[typeName] = {\n tagAssignments: async (parent, _args, context) => {\n const entityId = selectId(parent);\n if (!entityId) return [];\n try {\n return await adapter.getEntityTags(binding.entityType, entityId, getActor(context));\n } catch (error) {\n // The field is non-nullable decoration: a tags-svc outage must never fail\n // the parent query (a workflow list, a run page, …).\n logger.warn('[be-sdk/tags] Failed to resolve tagAssignments', {\n typeName,\n entityType: binding.entityType,\n entityId,\n error: error instanceof Error ? error.message : String(error),\n });\n return [];\n }\n },\n };\n }\n\n return { Query, Mutation, types };\n}\n","/**\n * @burdenoff/be-sdk/tags\n *\n * Shared \"tag my entities\" surface for product services, backed by\n * wspace-tags-svc through the internal workspace gateway:\n *\n * - {@link TagsGatewayAdapter} — the configurable adapter (entity types, default\n * vocabulary, default source) that replaces the per-service EntityTagAdapter copies.\n * - {@link buildEntityTagsSdl} — the per-service, prefixed SDL (unique type names so\n * subgraphs never collide in composition; static `@rbac` on every root field).\n * - {@link createEntityTagResolvers} — the matching Query / Mutation /\n * `tagAssignments` resolvers, with ownership, audit and error-mapping hooks.\n *\n * @example\n * ```ts\n * import { TagsGatewayAdapter, buildEntityTagsSdl, createEntityTagResolvers } from '@burdenoff/be-sdk/tags';\n *\n * const adapter = new TagsGatewayAdapter({\n * serviceName: 'wspace-workflow-svc',\n * entityTypes: ['FLUIDGRIDS_WORKFLOW', 'FLUIDGRIDS_RUN'],\n * vocabulary: { key: 'fluidgrids-tags', name: 'FluidGrids Tags' },\n * });\n * export const typeDefs = buildEntityTagsSdl({\n * prefix: 'Fluidgrids',\n * productLabel: 'FluidGrids',\n * rbac: { resource: 'workflow' },\n * extendTypes: ['WorkflowDefinition', 'WorkflowRun'],\n * });\n * export const resolvers = createEntityTagResolvers({ prefix: 'Fluidgrids', adapter, entities: { … } });\n * ```\n */\n\nexport {\n TAG_ACTOR_TYPES,\n TAG_ASSIGNMENT_SOURCES,\n type AvailableTag,\n type CreateTagOptions,\n type EntityTagAssignment,\n type EntityTagInfo,\n type FindEntitiesByTagsOptions,\n type RawTagAssignment,\n type TagActor,\n type TagActorType,\n type TagAssignmentSource,\n type TagEntityOptions,\n type TaggedEntityPage,\n type TagsGatewayClient,\n type TagVocabularyConfig,\n type TagVocabularyRef,\n} from './types.js';\n\nexport { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, isEntityTagsError, type EntityTagsErrorCode } from './errors.js';\n\nexport {\n assertTagPrefix,\n entityTagsFieldNames,\n entityTagsTypeNames,\n type EntityTagsFieldNames,\n type EntityTagsTypeNames,\n} from './naming.js';\n\nexport { TagsGatewayAdapter, mapTagAssignment, slugifyTagKey, type TagsGatewayAdapterOptions } from './adapter.js';\n\nexport {\n UNIVERSAL_TAG_STUB_SDL,\n buildEntityTagsSdl,\n type EntityTagsRbacOptions,\n type EntityTagsSdlOptions,\n} from './sdl.js';\n\nexport {\n createEntityTagResolvers,\n defaultTagActor,\n type CreateEntityTagResolversOptions,\n type EntityTagAccessCheck,\n type EntityTagBinding,\n type EntityTagMutationEvent,\n type EntityTagOperation,\n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D;KACA,YAAY,QAAQ;KACpB;KACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IAC9D,CAAC;IACD,OAAO,CAAC;GACV;EACF,EACF;CACF;CAEA,OAAO;EAAE;EAAO;EAAU;CAAM;AAClC"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as Logger } from "../index-
|
|
2
|
-
import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-
|
|
1
|
+
import { r as Logger } from "../index-Cot73bdh.js";
|
|
2
|
+
import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-B2LCaK0R.js";
|
|
3
3
|
interface TelemetryIdGenerator {
|
|
4
4
|
generateTraceId(): string;
|
|
5
5
|
generateSpanId(): string;
|
package/dist/tracker/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as ActorOrigin, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution } from "../assistant-session-DA5ZKJOr.js";
|
|
2
2
|
import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
|
|
3
|
-
import {
|
|
4
|
-
import { p as
|
|
3
|
+
import { p as UsageMetricType } from "../index-CVCyKzhB.js";
|
|
4
|
+
import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-zd_NPGJo.js";
|
|
5
5
|
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, type ActivityTrackingOptions, type ActorOrigin, type AgentActivityAction, type AgentActivityOptions, type AssistantSessionAttribution, type ProductTracker, type RbacCheckOptions, TrackOptions, TrackResult, type TrackedActorType, TrackerModule, type TrackingEvent, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, type UnifiedTrackingOptions, UsageMetricType, type UsageTrackingOptions, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
|