@burdenoff/be-sdk 2026.1110.3 → 2026.1111.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/dist/activity/index.d.ts +165 -0
  2. package/dist/activity/index.js +389 -0
  3. package/dist/activity/index.js.map +1 -0
  4. package/dist/ai-credits/index.js +1 -1
  5. package/dist/{ai-credits-Ca-NNcVx.js → ai-credits-xxfwGpHS.js} +2 -2
  6. package/dist/{ai-credits-Ca-NNcVx.js.map → ai-credits-xxfwGpHS.js.map} +1 -1
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{auth-CEuBEBQN.js → auth-C5ctwSLp.js} +2 -2
  10. package/dist/{auth-CEuBEBQN.js.map → auth-C5ctwSLp.js.map} +1 -1
  11. package/dist/bootstrap/index.d.ts +74 -0
  12. package/dist/bootstrap/index.js +282 -0
  13. package/dist/bootstrap/index.js.map +1 -0
  14. package/dist/{client-DcZ3iGES.js → client-sAJTrb4i.js} +2 -2
  15. package/dist/{client-DcZ3iGES.js.map → client-sAJTrb4i.js.map} +1 -1
  16. package/dist/context/index.d.ts +35 -0
  17. package/dist/{context-CZnXf2yb.js → context/index.js} +38 -2
  18. package/dist/context/index.js.map +1 -0
  19. package/dist/database/index.js +1 -1
  20. package/dist/event-queue/index.d.ts +1 -1
  21. package/dist/explicit-activity-scope-DikJ7NAE.js +57 -0
  22. package/dist/explicit-activity-scope-DikJ7NAE.js.map +1 -0
  23. package/dist/export/index.js +1 -1
  24. package/dist/{export-B6fphx8a.js → export-DJXE3Osa.js} +3 -3
  25. package/dist/{export-B6fphx8a.js.map → export-DJXE3Osa.js.map} +1 -1
  26. package/dist/feature-flags/index.js +1 -1
  27. package/dist/{feature-flags-71oDkrUe.js → feature-flags-CP1KRgwD.js} +2 -2
  28. package/dist/{feature-flags-71oDkrUe.js.map → feature-flags-CP1KRgwD.js.map} +1 -1
  29. package/dist/files/index.js +1 -1
  30. package/dist/{files-DjH0099H.js → files-h5U-D2AF.js} +2 -2
  31. package/dist/{files-DjH0099H.js.map → files-h5U-D2AF.js.map} +1 -1
  32. package/dist/gateway/index.js +2 -2
  33. package/dist/{gateway-DBFmxWks.js → gateway-ByVo-n37.js} +2 -2
  34. package/dist/{gateway-DBFmxWks.js.map → gateway-ByVo-n37.js.map} +1 -1
  35. package/dist/graph/index.d.ts +1 -1
  36. package/dist/graph/index.js +1 -1
  37. package/dist/{graph-DDYgIryR.js → graph-CR7u4lpl.js} +2 -2
  38. package/dist/{graph-DDYgIryR.js.map → graph-CR7u4lpl.js.map} +1 -1
  39. package/dist/{graphql-DNkMkGBZ.d.ts → graphql-CUDyhibV.d.ts} +1 -1
  40. package/dist/{index-bZKZUvBu.d.ts → index-ADmsX0BI.d.ts} +3 -3
  41. package/dist/{index-BqYfCQSP.d.ts → index-B2LCaK0R.d.ts} +1 -1
  42. package/dist/{index-D6UeLAye.d.ts → index-CHwMhK6v.d.ts} +2 -2
  43. package/dist/{index-BQDsNAMR.d.ts → index-CTTwo9av.d.ts} +22 -1
  44. package/dist/{index-DZC-2o9R.d.ts → index-CVCyKzhB.d.ts} +2 -2
  45. package/dist/{index-CkT2aUr3.d.ts → index-C_GXXF32.d.ts} +2 -2
  46. package/dist/{index-BKwHQtHQ.d.ts → index-Cot73bdh.d.ts} +1 -1
  47. package/dist/{index-CnzbJZP7.d.ts → index-FRRaa6h2.d.ts} +2 -2
  48. package/dist/{index-N-huORcj.d.ts → index-U_tu3zUl.d.ts} +2 -2
  49. package/dist/index-cmR9k9ga.d.ts +26 -0
  50. package/dist/{index-CZTnQIRU.d.ts → index-zd_NPGJo.d.ts} +6 -141
  51. package/dist/index.d.ts +19 -479
  52. package/dist/index.js +22 -1492
  53. package/dist/index.js.map +1 -1
  54. package/dist/init/index.js +1 -1
  55. package/dist/{init-Dy3KhT6Y.js → init-CQPFmOOe.js} +3 -3
  56. package/dist/{init-Dy3KhT6Y.js.map → init-CQPFmOOe.js.map} +1 -1
  57. package/dist/instrumentation/index.d.ts +2 -2
  58. package/dist/logger/index.d.ts +1 -1
  59. package/dist/notifications/index.d.ts +1 -1
  60. package/dist/notifications/index.js +1 -1
  61. package/dist/{notifications-CdETrtFK.js → notifications-DY_i37WN.js} +2 -2
  62. package/dist/{notifications-CdETrtFK.js.map → notifications-DY_i37WN.js.map} +1 -1
  63. package/dist/payments/index.d.ts +144 -0
  64. package/dist/payments/index.js +404 -0
  65. package/dist/payments/index.js.map +1 -0
  66. package/dist/rate-limit-CBrK_U5H.js +142 -0
  67. package/dist/rate-limit-CBrK_U5H.js.map +1 -0
  68. package/dist/rbac/index.d.ts +1 -1
  69. package/dist/rbac/index.js +1 -1
  70. package/dist/{rbac-BB9l9Xph.js → rbac-Dvz0YzEt.js} +2 -2
  71. package/dist/{rbac-BB9l9Xph.js.map → rbac-Dvz0YzEt.js.map} +1 -1
  72. package/dist/resource-caps/index.d.ts +1 -1
  73. package/dist/{sdk-Dju9o-sq.js → sdk-B62itAH1.js} +11 -10
  74. package/dist/sdk-B62itAH1.js.map +1 -0
  75. package/dist/search/index.d.ts +112 -0
  76. package/dist/search/index.js +266 -0
  77. package/dist/search/index.js.map +1 -0
  78. package/dist/security/index.d.ts +2 -0
  79. package/dist/security/index.js +4 -0
  80. package/dist/security/index.js.map +1 -0
  81. package/dist/security/rate-limit/index.d.ts +2 -0
  82. package/dist/security/rate-limit/index.js +4 -0
  83. package/dist/security/rate-limit/index.js.map +1 -0
  84. package/dist/server/index.js +3 -2
  85. package/dist/server/index.js.map +1 -1
  86. package/dist/{stub-BqwKn4eh.js → stub-BUnfMiAS.js} +3 -56
  87. package/dist/stub-BUnfMiAS.js.map +1 -0
  88. package/dist/tags/index.js +1 -1
  89. package/dist/{tags-B5xpbgsk.js → tags-CbijgoqR.js} +2 -2
  90. package/dist/{tags-B5xpbgsk.js.map → tags-CbijgoqR.js.map} +1 -1
  91. package/dist/telemetry/index.d.ts +6 -3
  92. package/dist/telemetry/index.js +3 -2
  93. package/dist/telemetry/index.js.map +1 -1
  94. package/dist/tracker/index.d.ts +2 -2
  95. package/dist/tracker/index.js +5 -3
  96. package/dist/{tracker-BQVoEFUo.js → tracker-PQztSlhJ.js} +9 -390
  97. package/dist/tracker-PQztSlhJ.js.map +1 -0
  98. package/dist/translation/index.d.ts +120 -0
  99. package/dist/translation/index.js +573 -0
  100. package/dist/translation/index.js.map +1 -0
  101. package/dist/types/index.d.ts +3 -0
  102. package/dist/{types-Cj2RWXbz.js → types/index.js} +3 -3
  103. package/dist/types/index.js.map +1 -0
  104. package/dist/usage/index.d.ts +1 -1
  105. package/dist/usage/index.js +1 -1
  106. package/dist/{usage-BKFZiWQn.js → usage-BRqVP3CJ.js} +4 -4
  107. package/dist/{usage-BKFZiWQn.js.map → usage-BRqVP3CJ.js.map} +1 -1
  108. package/package.json +1 -1
  109. package/dist/context-CZnXf2yb.js.map +0 -1
  110. package/dist/sdk-Dju9o-sq.js.map +0 -1
  111. package/dist/stub-BqwKn4eh.js.map +0 -1
  112. package/dist/tracker-BQVoEFUo.js.map +0 -1
  113. package/dist/types-Cj2RWXbz.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/context/index.ts"],"sourcesContent":["/**\n * Context Module\n * Manages request-scoped context using AsyncLocalStorage\n * Thread-safe context propagation for async operations\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport type { SDKContext } from '../types/index.js';\n\nconst asyncLocalStorage = new AsyncLocalStorage<SDKContext>();\n\n/**\n * Module-level fallback for the Cloudflare Access service token.\n *\n * WHY THIS EXISTS — read before \"simplifying\" it away:\n * `asyncLocalStorage.enterWith()` (used by `setContext`) does NOT reliably\n * propagate across every async boundary under Bun + GraphQL Yoga — the same\n * limitation documented for the Prisma workspace context store\n * (see `src/prisma/workspace-extension.ts`). On top of that, the `createServer`\n * request path (`src/server/context.ts` `buildContext`) populates the *Prisma*\n * workspace store, not this `ContextManager` ALS at all. So a resolver-initiated\n * cross-layer call would otherwise read an empty context and attach no CF creds,\n * making the propagation a silent no-op on alpha.\n *\n * Unlike workspaceId/actorId (which differ per request and would race in a\n * module-level singleton), the CF Access service token is effectively\n * CONSTANT per environment — it's a single service-token pair fronting the\n * gateway. So caching it module-side is race-safe: concurrent requests all\n * carry the same value. It is only ever set when a request actually presents\n * the headers (gated upstream on `cf-ray`), and stays unset in dev/prod where\n * no CF Access sits in front of the gateways.\n */\nlet cfAccessFallback: { clientId: string; clientSecret: string } | undefined;\n\n/**\n * Module-level fallback for the CF Access USER-SSO cookie (`CF_Authorization`),\n * mirroring `cfAccessFallback` for the same Bun+Yoga ALS-unreliability reason.\n * Unlike the service-token pair this is per-USER and ~1h TTL — but for passing\n * the CF edge any valid member cookie suffices (app-layer identity travels in\n * `x-actor-*`). Refreshed by every inbound CF request, so an active fleet keeps\n * a live value. See BOFF-2929.\n */\nlet cfAuthorizationFallback: string | undefined;\n\n/**\n * Context Manager for handling request-scoped context\n */\nexport class ContextManager {\n /**\n * Get current context from async local storage\n */\n public static getContext(): SDKContext | undefined {\n return asyncLocalStorage.getStore();\n }\n\n /**\n * Set context for current async scope\n * Merges with existing context if present\n */\n public static setContext(context: SDKContext): void {\n const currentContext = this.getContext() || {};\n asyncLocalStorage.enterWith({ ...currentContext, ...context });\n // Mirror CF creds to the module-level fallback so cross-layer calls can\n // recover them even when enterWith() doesn't reach the resolver chain.\n if ((context.cfAccessClientId && context.cfAccessClientSecret) || context.cfAuthorization) {\n this.setCfAccessContext(context.cfAccessClientId, context.cfAccessClientSecret, context.cfAuthorization);\n }\n }\n\n /**\n * Record the Cloudflare Access service token for the current process.\n *\n * Call this from every request-context builder that may receive CF headers\n * (the SDK `createServer` `buildContext` and the bootstrap HTTP middleware\n * both do). Stored in a module-level fallback because `enterWith()` is not a\n * reliable carrier under Bun + Yoga — see the `cfAccessFallback` note above.\n *\n * Deliberately a NO-OP when either cred is absent: `buildContext` runs on\n * every request, so clearing here on a tokenless request could wipe the value\n * a concurrent CF request just stored. The token is constant per environment,\n * so \"remember, never clear on absence\" is both safe and correct. Use\n * `clearContext()` to reset (shutdown / tests).\n */\n public static setCfAccessContext(clientId?: string, clientSecret?: string, cfAuthorization?: string): void {\n if (clientId && clientSecret) {\n cfAccessFallback = { clientId, clientSecret };\n }\n // CF Access user-SSO cookie — remember, never clear on absence (same policy\n // as the service token). Present on real alpha user requests; kept live by\n // ongoing traffic. See BOFF-2929.\n if (cfAuthorization) {\n cfAuthorizationFallback = cfAuthorization;\n }\n }\n\n /**\n * Run function with specific context\n * Context is isolated to this execution and its children\n */\n public static async withContext<T>(context: SDKContext, fn: () => Promise<T>): Promise<T> {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Run synchronous function with specific context\n */\n public static withContextSync<T>(context: SDKContext, fn: () => T): T {\n return asyncLocalStorage.run(context, fn);\n }\n\n /**\n * Clear current context (including the module-level CF Access fallback).\n */\n public static clearContext(): void {\n asyncLocalStorage.disable();\n cfAccessFallback = undefined;\n cfAuthorizationFallback = undefined;\n }\n\n /**\n * Get actor ID from context\n */\n public static getActorId(): string | undefined {\n return this.getContext()?.actorId;\n }\n\n /**\n * Get legacy user ID from context.\n */\n public static getUser(): string | undefined {\n const context = this.getContext();\n const userId = context?.['userId'];\n return typeof userId === 'string' ? userId : context?.actorId;\n }\n\n /**\n * Get workspace ID from context\n */\n public static getWorkspace(): string | undefined {\n return this.getContext()?.workspaceId;\n }\n\n /**\n * Get tenant ID from context\n */\n public static getTenant(): string | undefined {\n return this.getContext()?.tenantId;\n }\n\n /**\n * Get legacy organization ID from context.\n */\n public static getOrganization(): string | undefined {\n const organizationId = this.getContext()?.['organizationId'];\n return typeof organizationId === 'string' ? organizationId : undefined;\n }\n\n /**\n * Get project ID from context\n */\n public static getProject(): string | undefined {\n return this.getContext()?.projectId;\n }\n\n /**\n * Get app ID from context\n */\n public static getApp(): string | undefined {\n return this.getContext()?.appId;\n }\n\n /**\n * Get JWT token from context\n */\n public static getToken(): string | undefined {\n return this.getContext()?.token;\n }\n\n /**\n * Get product ID from context\n */\n public static getProduct(): string | undefined {\n return this.getContext()?.productId;\n }\n\n /**\n * Get the Cloudflare Access service-token client id (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientId(): string | undefined {\n return this.getContext()?.cfAccessClientId ?? cfAccessFallback?.clientId;\n }\n\n /**\n * Get the Cloudflare Access service-token client secret (ALS first, then the\n * module-level fallback — see `cfAccessFallback`).\n */\n public static getCfAccessClientSecret(): string | undefined {\n return this.getContext()?.cfAccessClientSecret ?? cfAccessFallback?.clientSecret;\n }\n\n /**\n * Get the Cloudflare Access user-SSO cookie value (`CF_Authorization`) — ALS\n * first, then the module-level fallback (see `cfAuthorizationFallback`).\n */\n public static getCfAuthorization(): string | undefined {\n return this.getContext()?.cfAuthorization ?? cfAuthorizationFallback;\n }\n\n /**\n * Build the Cloudflare Access credentials to re-present on a\n * cross-layer outbound call.\n *\n * Cross-layer calls (wspace ↔ global) traverse the peer layer's PUBLIC\n * gateway, which on alpha sits behind Cloudflare Access. Without the CF\n * service token the request is rejected at the CF edge before reaching the\n * gateway. We reuse the *inbound* request's CF creds (propagated by the\n * public gateway into request-scoped context) so the cross-layer leg passes.\n *\n * Inbound-only: sourced from the request context (AsyncLocalStorage first,\n * module-level fallback second — see `cfAccessFallback`). Returns `{}` unless\n * BOTH creds are present — so it is a no-op in environments without CF in\n * front of the gateways (local dev, and production, which is not\n * CF-Access-gated and has no CF service token).\n */\n public static getCfAccessHeaders(): Record<string, string> {\n const headers: Record<string, string> = {};\n\n // Service-token pair (machine callers). Present only when a service token\n // fronted the inbound call — not on browser user requests.\n const clientId = this.getCfAccessClientId();\n const clientSecret = this.getCfAccessClientSecret();\n if (clientId && clientSecret) {\n headers['cf-access-client-id'] = clientId;\n headers['cf-access-client-secret'] = clientSecret;\n }\n\n // User-SSO cookie. On alpha a real user request carries the CF_Authorization\n // cookie rather than the service-token pair; re-present it as the cookie so\n // the peer layer's CF Access (same app / shared AUD) admits the cross-layer\n // call. See BOFF-2929.\n const cfAuthorization = this.getCfAuthorization();\n if (cfAuthorization) {\n headers['cookie'] = `CF_Authorization=${cfAuthorization}`;\n }\n\n return headers;\n }\n\n /**\n * Update specific context fields\n */\n public static updateContext(updates: Partial<SDKContext>): void {\n const current = this.getContext();\n if (current) {\n this.setContext({ ...current, ...updates });\n } else {\n this.setContext(updates);\n }\n }\n\n /**\n * Check if context exists\n */\n public static hasContext(): boolean {\n return this.getContext() !== undefined;\n }\n\n /**\n * Get custom field from context\n */\n public static getCustomField(key: string): unknown {\n return this.getContext()?.[key];\n }\n\n /**\n * Set custom field in context\n */\n public static setCustomField(key: string, value: unknown): void {\n const current = this.getContext() || {};\n this.setContext({ ...current, [key]: value });\n }\n}\n\n/**\n * Default export for convenience\n */\nexport const contextManager = ContextManager;\n\n/**\n * Helper function to extract context from HTTP request\n */\nexport function extractContextFromRequest(req: {\n headers: Record<string, string | string[] | undefined>;\n user?: { user_id?: string; workspace_id?: string; tenant_endpoint?: string };\n}): SDKContext {\n const context: SDKContext = {};\n\n // Extract from user object (if JWT already verified)\n if (req.user) {\n context.actorId = req.user.user_id;\n context.workspaceId = req.user.workspace_id;\n context.tenantId = req.user.tenant_endpoint;\n }\n\n // Extract from headers\n const getHeader = (key: string): string | undefined => {\n const value = req.headers[key.toLowerCase()];\n return Array.isArray(value) ? value[0] : value;\n };\n\n const authHeader = getHeader('authorization');\n if (authHeader) {\n context.token = authHeader.replace('Bearer ', '');\n }\n\n const workspaceId = getHeader('x-workspace-id');\n if (workspaceId && !context.workspaceId) {\n context.workspaceId = workspaceId;\n }\n\n const productId = getHeader('x-product-id');\n if (productId) {\n context.productId = productId;\n }\n\n const projectId = getHeader('x-project-id');\n if (projectId) {\n context.projectId = projectId;\n }\n\n const appId = getHeader('x-app-id');\n if (appId) {\n context.appId = appId;\n }\n\n // Cloudflare Access service token. Forwarded to subgraphs by the public\n // gateways only when the request actually transited CF (cf-ray present), so\n // we can capture whatever arrives here. Re-presented on cross-layer outbound\n // calls — see ContextManager.getCfAccessHeaders.\n const cfAccessClientId = getHeader('cf-access-client-id');\n if (cfAccessClientId) {\n context.cfAccessClientId = cfAccessClientId;\n }\n\n const cfAccessClientSecret = getHeader('cf-access-client-secret');\n if (cfAccessClientSecret) {\n context.cfAccessClientSecret = cfAccessClientSecret;\n }\n\n // CF Access user-SSO cookie, forwarded by the public gateway as\n // x-cf-authorization. Re-presented as the CF_Authorization cookie on\n // cross-layer calls (see getCfAccessHeaders). See BOFF-2929.\n const cfAuthorization = getHeader('x-cf-authorization');\n if (cfAuthorization) {\n context.cfAuthorization = cfAuthorization;\n }\n\n return context;\n}\n"],"mappings":";;;;;;;;AASA,MAAM,oBAAoB,IAAI,kBAA8B;;;;;;;;;;;;;;;;;;;;;;AAuB5D,IAAI;;;;;;;;;AAUJ,IAAI;;;;AAKJ,IAAa,iBAAb,MAA4B;;;;CAI1B,OAAc,aAAqC;EACjD,OAAO,kBAAkB,SAAS;CACpC;;;;;CAMA,OAAc,WAAW,SAA2B;EAClD,MAAM,iBAAiB,KAAK,WAAW,KAAK,CAAC;EAC7C,kBAAkB,UAAU;GAAE,GAAG;GAAgB,GAAG;EAAQ,CAAC;EAG7D,IAAK,QAAQ,oBAAoB,QAAQ,wBAAyB,QAAQ,iBACxE,KAAK,mBAAmB,QAAQ,kBAAkB,QAAQ,sBAAsB,QAAQ,eAAe;CAE3G;;;;;;;;;;;;;;;CAgBA,OAAc,mBAAmB,UAAmB,cAAuB,iBAAgC;EACzG,IAAI,YAAY,cACd,mBAAmB;GAAE;GAAU;EAAa;EAK9C,IAAI,iBACF,0BAA0B;CAE9B;;;;;CAMA,aAAoB,YAAe,SAAqB,IAAkC;EACxF,OAAO,kBAAkB,IAAI,SAAS,EAAE;CAC1C;;;;CAKA,OAAc,gBAAmB,SAAqB,IAAgB;EACpE,OAAO,kBAAkB,IAAI,SAAS,EAAE;CAC1C;;;;CAKA,OAAc,eA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AOlB,MAAM,mBAAmB,UAAU,qBAAqB;CACxD,IAAI,kBACF,QAAQ,mBAAmB;CAG7B,MAAM,uBAAuB,UAAU,yBAAyB;CAChE,IAAI,sBACF,QAAQ,uBAAuB;CAMjC,MAAM,kBAAkB,UAAU,oBAAoB;CACtD,IAAI,iBACF,QAAQ,kBAAkB;CAG5B,OAAO;AACT"}
@@ -1,5 +1,5 @@
1
1
  import { a as logger } from "../logger-B6rCpb7D.js";
2
- import { c as ValidationError } from "../types-Cj2RWXbz.js";
2
+ import { ValidationError } from "../types/index.js";
3
3
 
4
4
  // src/database/connections/clickhouse.ts
5
5
  /**
@@ -1,2 +1,2 @@
1
- import { $ as WorkspaceMemberRemovedPayload, $t as IEventQueue, A as OrganizationDeletedPayload, At as EntityEventType, B as TaxonomyPublishMetadata, Bt as createGraphEventEmitter$1, C as EventsManagerSubscribeOptions, Ct as SubscribeOptions, D as EventSpec, Dt as ModuleEventsService, E as EVENT_TAXONOMY_BRAND, Et as ModuleEventsConfig, F as TaxonomyEventKind, Ft as resetGraphEventEmitter, G as VibecontrolsSessionStartedPayload, Gt as RedisStreamsEventConsumer, H as VibecontrolsAgentConnectedPayload, Ht as createMemoryPublisher, I as TaxonomyEventLayer, It as MemoryEventBus, J as WorkflowRunFailedPayload, Jt as EventQueueFactory, K as WSPACE_GRAPH_EVENTS_STREAM, Kt as RedisStreamsEventPublisher, L as TaxonomyEventPii, Lt as MemoryEventConsumer, M as PublishableEventName, Mt as GraphEventEmitterImpl, N as REFERENCE_PRODUCT_EVENT_TAXONOMY, Nt as createGraphEventEmitter, O as EventTaxonomy, Ot as createModuleEventsService, P as SubscriptionChangedPayload, Pt as getGraphEventEmitter, Q as WorkspaceMemberAddedPayload, Qt as PublishOptions, R as TaxonomyEventStatus, Rt as MemoryEventPublisher, S as EventsManagerStreamRoute, St as StreamInfo, T as DefinedEventTaxonomy, Tt as ModuleEventPayload, U as VibecontrolsAgentDisconnectedPayload, Ut as dlqKey, V as UserDeletedPayload, Vt as createMemoryConsumer, W as VibecontrolsSessionEndedPayload, Wt as streamKey, X as WorkspaceCreatedPayload, Xt as ISubscription, Y as WorkflowRunStartedPayload, Yt as IEventConsumer, Z as WorkspaceDeletedPayload, Zt as IEventPublisher, _ as EventsManager, _t as EventMessage$1, a as LifecycleEventContext, an as QueueType, at as publishTaxonomyEvent, b as EventsManagerOptions, bt as PublishEventOptions, c as OrganizationDeletedFact, cn as EventHandler, ct as EVENT_STREAMS_URL_ENV_KEYS, d as buildConsumerGroupName, dn as StreamConfig, dt as resolveEventStreamsUrl, en as BaseQueueConfig, et as WorkspaceMemberRoleUpdatedPayload, f as createLifecycleConsumer, fn as SubscriptionOptions, ft as resolveEventStreamsUrlSource, g as parseWorkspaceMemberRemoved, gt as createPublisher, h as parseWorkspaceDeletedStream, ht as createConsumer, i as LifecycleConsumerOptions, in as QueueStatistics, it as mergeEventTaxonomies, j as PLATFORM_EVENT_TAXONOMY, jt as GraphEventEmitter, k as GraphEntityEventPayload, kt as EntityEventRbacMetadata, l as WorkspaceDeletedFact, ln as EventMessage, lt as GRAPH_EVENTS_URL_ENV_KEYS, m as parseWorkspaceDeletedGraph, mt as resolveGraphEventsUrlSource, n as LIFECYCLE_SUBJECTS, nn as EventQueueHealthCheckResult, nt as eventSpec, o as LifecycleEventSource, on as AcknowledgeableEvent, ot as taxonomyEventNames, p as parseOrganizationDeleted, pt as resolveGraphEventsUrl, q as WorkflowRunCompletedPayload, qt as RedisStreamsConnection, r as LifecycleConsumer, rn as PublisherConfig, rt as isDefinedEventTaxonomy, s as LifecycleHandlers, sn as ConsumerOptions, st as taxonomyNameViolation, tn as ConsumerConfig, tt as defineEventTaxonomy, u as WorkspaceMemberRemovedFact, un as EventMetadata, ut as eventKeyScopeForUrl, v as EventsManagerHandler, vt as EventPriority, w as createEventsManagerSingleton, wt as BulkEventPayload, x as EventsManagerSingleton, xt as PublishResult, y as EventsManagerMessage, yt as EventsModule, z as TaxonomyPayload, zt as MemoryEventQueue } from "../index-CnzbJZP7.js";
1
+ import { $ as WorkspaceMemberRemovedPayload, $t as IEventQueue, A as OrganizationDeletedPayload, At as EntityEventType, B as TaxonomyPublishMetadata, Bt as createGraphEventEmitter$1, C as EventsManagerSubscribeOptions, Ct as SubscribeOptions, D as EventSpec, Dt as ModuleEventsService, E as EVENT_TAXONOMY_BRAND, Et as ModuleEventsConfig, F as TaxonomyEventKind, Ft as resetGraphEventEmitter, G as VibecontrolsSessionStartedPayload, Gt as RedisStreamsEventConsumer, H as VibecontrolsAgentConnectedPayload, Ht as createMemoryPublisher, I as TaxonomyEventLayer, It as MemoryEventBus, J as WorkflowRunFailedPayload, Jt as EventQueueFactory, K as WSPACE_GRAPH_EVENTS_STREAM, Kt as RedisStreamsEventPublisher, L as TaxonomyEventPii, Lt as MemoryEventConsumer, M as PublishableEventName, Mt as GraphEventEmitterImpl, N as REFERENCE_PRODUCT_EVENT_TAXONOMY, Nt as createGraphEventEmitter, O as EventTaxonomy, Ot as createModuleEventsService, P as SubscriptionChangedPayload, Pt as getGraphEventEmitter, Q as WorkspaceMemberAddedPayload, Qt as PublishOptions, R as TaxonomyEventStatus, Rt as MemoryEventPublisher, S as EventsManagerStreamRoute, St as StreamInfo, T as DefinedEventTaxonomy, Tt as ModuleEventPayload, U as VibecontrolsAgentDisconnectedPayload, Ut as dlqKey, V as UserDeletedPayload, Vt as createMemoryConsumer, W as VibecontrolsSessionEndedPayload, Wt as streamKey, X as WorkspaceCreatedPayload, Xt as ISubscription, Y as WorkflowRunStartedPayload, Yt as IEventConsumer, Z as WorkspaceDeletedPayload, Zt as IEventPublisher, _ as EventsManager, _t as EventMessage$1, a as LifecycleEventContext, an as QueueType, at as publishTaxonomyEvent, b as EventsManagerOptions, bt as PublishEventOptions, c as OrganizationDeletedFact, cn as EventHandler, ct as EVENT_STREAMS_URL_ENV_KEYS, d as buildConsumerGroupName, dn as StreamConfig, dt as resolveEventStreamsUrl, en as BaseQueueConfig, et as WorkspaceMemberRoleUpdatedPayload, f as createLifecycleConsumer, fn as SubscriptionOptions, ft as resolveEventStreamsUrlSource, g as parseWorkspaceMemberRemoved, gt as createPublisher, h as parseWorkspaceDeletedStream, ht as createConsumer, i as LifecycleConsumerOptions, in as QueueStatistics, it as mergeEventTaxonomies, j as PLATFORM_EVENT_TAXONOMY, jt as GraphEventEmitter, k as GraphEntityEventPayload, kt as EntityEventRbacMetadata, l as WorkspaceDeletedFact, ln as EventMessage, lt as GRAPH_EVENTS_URL_ENV_KEYS, m as parseWorkspaceDeletedGraph, mt as resolveGraphEventsUrlSource, n as LIFECYCLE_SUBJECTS, nn as EventQueueHealthCheckResult, nt as eventSpec, o as LifecycleEventSource, on as AcknowledgeableEvent, ot as taxonomyEventNames, p as parseOrganizationDeleted, pt as resolveGraphEventsUrl, q as WorkflowRunCompletedPayload, qt as RedisStreamsConnection, r as LifecycleConsumer, rn as PublisherConfig, rt as isDefinedEventTaxonomy, s as LifecycleHandlers, sn as ConsumerOptions, st as taxonomyNameViolation, tn as ConsumerConfig, tt as defineEventTaxonomy, u as WorkspaceMemberRemovedFact, un as EventMetadata, ut as eventKeyScopeForUrl, v as EventsManagerHandler, vt as EventPriority, w as createEventsManagerSingleton, wt as BulkEventPayload, x as EventsManagerSingleton, xt as PublishResult, y as EventsManagerMessage, yt as EventsModule, z as TaxonomyPayload, zt as MemoryEventQueue } from "../index-FRRaa6h2.js";
2
2
  export { type AcknowledgeableEvent, type BaseQueueConfig, type BulkEventPayload, type ConsumerConfig, type ConsumerOptions, type DefinedEventTaxonomy, EVENT_STREAMS_URL_ENV_KEYS, EVENT_TAXONOMY_BRAND, type EntityEventRbacMetadata, type EntityEventType, type EventHandler, type EventMessage, type EventMetadata, EventPriority, EventQueueFactory, type EventQueueHealthCheckResult, type EventQueueHealthCheckResult as HealthCheckResult, type EventSpec, type EventTaxonomy, EventsManager, type EventsManagerHandler, type EventsManagerMessage, type EventsManagerOptions, type EventsManagerSingleton, type EventsManagerStreamRoute, type EventsManagerSubscribeOptions, EventsModule, GRAPH_EVENTS_URL_ENV_KEYS, type GraphEntityEventPayload, type GraphEventEmitter, GraphEventEmitterImpl, type EventMessage$1 as GraphQLEventMessage, type IEventConsumer, type IEventPublisher, type IEventQueue, type ISubscription, LIFECYCLE_SUBJECTS, type LifecycleConsumer, type LifecycleConsumerOptions, type LifecycleEventContext, type LifecycleEventSource, type LifecycleHandlers, MemoryEventBus, MemoryEventConsumer, MemoryEventPublisher, MemoryEventQueue, type ModuleEventPayload, type ModuleEventsConfig, ModuleEventsService, type OrganizationDeletedFact, type OrganizationDeletedPayload, PLATFORM_EVENT_TAXONOMY, type PublishEventOptions, type PublishOptions, type PublishResult, type PublishableEventName, type PublisherConfig, type QueueStatistics, QueueType, REFERENCE_PRODUCT_EVENT_TAXONOMY, RedisStreamsConnection, RedisStreamsEventConsumer, RedisStreamsEventPublisher, type StreamConfig, type StreamInfo, type SubscribeOptions, type SubscriptionChangedPayload, type SubscriptionOptions, type TaxonomyEventKind, type TaxonomyEventLayer, type TaxonomyEventPii, type TaxonomyEventStatus, type TaxonomyPayload, type TaxonomyPublishMetadata, type UserDeletedPayload, type VibecontrolsAgentConnectedPayload, type VibecontrolsAgentDisconnectedPayload, type VibecontrolsSessionEndedPayload, type VibecontrolsSessionStartedPayload, WSPACE_GRAPH_EVENTS_STREAM, type WorkflowRunCompletedPayload, type WorkflowRunFailedPayload, type WorkflowRunStartedPayload, type WorkspaceCreatedPayload, type WorkspaceDeletedFact, type WorkspaceDeletedPayload, type WorkspaceMemberAddedPayload, type WorkspaceMemberRemovedFact, type WorkspaceMemberRemovedPayload, type WorkspaceMemberRoleUpdatedPayload, buildConsumerGroupName, createConsumer, createEventsManagerSingleton, createGraphEventEmitter, createLifecycleConsumer, createMemoryConsumer, createGraphEventEmitter$1 as createMemoryGraphEventEmitter, createMemoryPublisher, createModuleEventsService, createPublisher, defineEventTaxonomy, eventKeyScopeForUrl, eventSpec, getGraphEventEmitter, isDefinedEventTaxonomy, mergeEventTaxonomies, parseOrganizationDeleted, parseWorkspaceDeletedGraph, parseWorkspaceDeletedStream, parseWorkspaceMemberRemoved, publishTaxonomyEvent, dlqKey as redisDlqKey, streamKey as redisStreamKey, resetGraphEventEmitter, resolveEventStreamsUrl, resolveEventStreamsUrlSource, resolveGraphEventsUrl, resolveGraphEventsUrlSource, taxonomyEventNames, taxonomyNameViolation };
@@ -0,0 +1,57 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ // src/activity/explicit-activity-scope.ts
4
+ /**
5
+ * Explicit-activity scope
6
+ *
7
+ * Lets the mutation-audit backstop (`createMutationAuditPlugin` in
8
+ * `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an
9
+ * activity row through an explicit call (`trackOperation`, `trackerStub.track`,
10
+ * `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it
11
+ * did, the backstop skips its generic `graphql.mutation` row so the activity feed
12
+ * never carries two rows for one mutation.
13
+ *
14
+ * The scope is entered with `AsyncLocalStorage.run()` around the operation's
15
+ * execute function. `run()` (unlike `enterWith()`) propagates through every
16
+ * promise continuation started inside it, including fire-and-forget calls made
17
+ * by resolvers, so concurrent requests never see each other's marks.
18
+ *
19
+ * Outside a scope (background jobs, event consumers, REST handlers) every
20
+ * function here is a no-op.
21
+ */
22
+ const scopeStorage = new AsyncLocalStorage();
23
+ /** Create a fresh, unmarked scope. */
24
+ function createExplicitActivityScope() {
25
+ return {
26
+ explicitCount: 0,
27
+ suppressed: false
28
+ };
29
+ }
30
+ /** Run `fn` with `scope` as the active explicit-activity scope. */
31
+ function runInExplicitActivityScope(scope, fn) {
32
+ return scopeStorage.run(scope, fn);
33
+ }
34
+ /**
35
+ * Record that an explicit activity write happened in the current operation.
36
+ * Called by the SDK's own activity writers; services never need to call it.
37
+ */
38
+ function markExplicitActivity() {
39
+ const scope = scopeStorage.getStore();
40
+ if (scope) scope.explicitCount += 1;
41
+ }
42
+ /**
43
+ * Tell the mutation-audit backstop not to write its generic row for the current
44
+ * operation.
45
+ *
46
+ * Use it in a resolver whose audit trail goes through a path the SDK cannot see
47
+ * (for example a direct call to the activity subgraph), or for a mutation that
48
+ * must deliberately leave no activity row. Has no effect outside an operation
49
+ * that mounts the backstop.
50
+ */
51
+ function suppressMutationAudit() {
52
+ const scope = scopeStorage.getStore();
53
+ if (scope) scope.suppressed = true;
54
+ }
55
+
56
+ export { suppressMutationAudit as i, markExplicitActivity as n, runInExplicitActivityScope as r, createExplicitActivityScope as t };
57
+ //# sourceMappingURL=explicit-activity-scope-DikJ7NAE.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"explicit-activity-scope-DikJ7NAE.js","names":[],"sources":["../src/activity/explicit-activity-scope.ts"],"sourcesContent":["/**\n * Explicit-activity scope\n *\n * Lets the mutation-audit backstop (`createMutationAuditPlugin` in\n * `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an\n * activity row through an explicit call (`trackOperation`, `trackerStub.track`,\n * `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it\n * did, the backstop skips its generic `graphql.mutation` row so the activity feed\n * never carries two rows for one mutation.\n *\n * The scope is entered with `AsyncLocalStorage.run()` around the operation's\n * execute function. `run()` (unlike `enterWith()`) propagates through every\n * promise continuation started inside it, including fire-and-forget calls made\n * by resolvers, so concurrent requests never see each other's marks.\n *\n * Outside a scope (background jobs, event consumers, REST handlers) every\n * function here is a no-op.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/** Per-operation record of explicit activity writes. */\nexport interface ExplicitActivityScope {\n /** Number of explicit activity writes made while the operation executed. */\n explicitCount: number;\n /** True once `suppressMutationAudit()` was called for this operation. */\n suppressed: boolean;\n}\n\nconst scopeStorage = new AsyncLocalStorage<ExplicitActivityScope>();\n\n/** Create a fresh, unmarked scope. */\nexport function createExplicitActivityScope(): ExplicitActivityScope {\n return { explicitCount: 0, suppressed: false };\n}\n\n/** Run `fn` with `scope` as the active explicit-activity scope. */\nexport function runInExplicitActivityScope<T>(scope: ExplicitActivityScope, fn: () => T): T {\n return scopeStorage.run(scope, fn);\n}\n\n/** The active scope, or undefined outside a GraphQL operation that mounts the backstop. */\nexport function getExplicitActivityScope(): ExplicitActivityScope | undefined {\n return scopeStorage.getStore();\n}\n\n/**\n * Record that an explicit activity write happened in the current operation.\n * Called by the SDK's own activity writers; services never need to call it.\n */\nexport function markExplicitActivity(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.explicitCount += 1;\n}\n\n/**\n * Tell the mutation-audit backstop not to write its generic row for the current\n * operation.\n *\n * Use it in a resolver whose audit trail goes through a path the SDK cannot see\n * (for example a direct call to the activity subgraph), or for a mutation that\n * must deliberately leave no activity row. Has no effect outside an operation\n * that mounts the backstop.\n */\nexport function suppressMutationAudit(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.suppressed = true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,eAAe,IAAI,kBAAyC;;AAGlE,SAAgB,8BAAqD;CACnE,OAAO;EAAE,eAAe;EAAG,YAAY;CAAM;AAC/C;;AAGA,SAAgB,2BAA8B,OAA8B,IAAgB;CAC1F,OAAO,aAAa,IAAI,OAAO,EAAE;AACnC;;;;;AAWA,SAAgB,uBAA6B;CAC3C,MAAM,QAAQ,aAAa,SAAS;CACpC,IAAI,OAAO,MAAM,iBAAiB;AACpC;;;;;;;;;;AAWA,SAAgB,wBAA8B;CAC5C,MAAM,QAAQ,aAAa,SAAS;CACpC,IAAI,OAAO,MAAM,aAAa;AAChC"}
@@ -1,4 +1,4 @@
1
- import { a as estimateCSVSize, c as PaginationService, i as csvToJSON, l as BaseModuleExporter, n as triggerExportJob, o as getCSVHeaders, r as convertToCSV, s as parseCSV } from "../export-B6fphx8a.js";
1
+ import { a as estimateCSVSize, c as PaginationService, i as csvToJSON, l as BaseModuleExporter, n as triggerExportJob, o as getCSVHeaders, r as convertToCSV, s as parseCSV } from "../export-DJXE3Osa.js";
2
2
 
3
3
  export { BaseModuleExporter, PaginationService, convertToCSV, csvToJSON, estimateCSVSize, getCSVHeaders, parseCSV, triggerExportJob };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
- import { t as GatewayClient } from "./client-DcZ3iGES.js";
3
- import "./gateway-DBFmxWks.js";
2
+ import { t as GatewayClient } from "./client-sAJTrb4i.js";
3
+ import "./gateway-ByVo-n37.js";
4
4
 
5
5
  // src/export/base-exporter.ts
6
6
  /**
@@ -639,4 +639,4 @@ var export_exports = /* @__PURE__ */ __exportAll({
639
639
  });
640
640
 
641
641
  export { estimateCSVSize as a, PaginationService as c, csvToJSON as i, BaseModuleExporter as l, triggerExportJob as n, getCSVHeaders as o, convertToCSV as r, parseCSV as s, export_exports as t };
642
- //# sourceMappingURL=export-B6fphx8a.js.map
642
+ //# sourceMappingURL=export-DJXE3Osa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"export-B6fphx8a.js","names":[],"sources":["../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts","../src/export/index.ts"],"sourcesContent":["/**\n * Base Module Exporter\n *\n * Abstract base class for module exporters across all Burdenoff microservices.\n * Provides common functionality for exporting data from different modules.\n *\n * @module export/base-exporter\n *\n * @example\n * ```typescript\n * import { BaseModuleExporter } from '@burdenoff/be-sdk/export';\n *\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n * description = 'Export user data';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * // Implementation\n * }\n * }\n * ```\n */\n\nimport type { ExportOptions, ExportResult, PaginateQueryFn, PaginateResult } from './types.js';\n\n/**\n * Abstract base class for module exporters\n *\n * Provides common functionality that all module exporters can inherit:\n * - Field filtering\n * - Pagination helpers\n * - Module metadata\n *\n * @typeParam T - The type of entity this exporter handles\n */\nexport abstract class BaseModuleExporter<T = unknown> {\n /** Unique key identifying this module (e.g., 'users', 'tags', 'orders') */\n moduleKey?: string;\n\n /** Human-readable display name for the module */\n displayName?: string;\n\n /** Description of what this module exports */\n description?: string;\n\n /** Default fields to exclude from export (e.g., sensitive data) */\n defaultExcludeFields?: string[];\n\n /** List of product IDs this exporter supports */\n supportedProducts?: string[];\n\n /** Model name for database operations */\n protected modelName?: string;\n\n /**\n * Export data from this module\n *\n * Subclasses should implement this method to perform the actual export.\n * The method is optional to allow for gradual implementation.\n *\n * @param options - Export options including format, filters, and pagination\n * @returns Export result with data or download URL\n */\n export?(options: ExportOptions): Promise<ExportResult>;\n\n /**\n * Filter fields from an entity based on exclude list\n *\n * Use this to remove sensitive or unnecessary fields from exported data.\n *\n * @param entity - Entity to filter\n * @param excludeFields - Fields to exclude (uses defaultExcludeFields if not provided)\n * @returns Filtered entity as a plain object\n *\n * @example\n * ```typescript\n * const user = { id: '1', name: 'John', password: 'secret', ssn: '123' };\n * const filtered = this.filterFields(user, ['password', 'ssn']);\n * // Result: { id: '1', name: 'John' }\n * ```\n */\n protected filterFields(entity: T | Record<string, unknown>, excludeFields?: string[]): Record<string, unknown> {\n const fieldsToExclude = excludeFields || this.defaultExcludeFields || [];\n\n if (fieldsToExclude.length === 0) {\n return entity as Record<string, unknown>;\n }\n\n const filtered: Record<string, unknown> = {};\n const record = entity as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(record)) {\n if (!fieldsToExclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n return filtered;\n }\n\n /**\n * Filter multiple entities\n *\n * @param entities - Array of entities to filter\n * @param excludeFields - Fields to exclude\n * @returns Array of filtered entities\n */\n protected filterFieldsMany(\n entities: (T | Record<string, unknown>)[],\n excludeFields?: string[]\n ): Record<string, unknown>[] {\n return entities.map((entity) => this.filterFields(entity, excludeFields));\n }\n\n /**\n * Paginate helper for database queries\n *\n * Use this to implement paginated data fetching in your export method.\n *\n * @param queryFn - Function that executes the paginated query\n * @param page - Page number (1-indexed)\n * @param pageSize - Number of items per page\n * @returns Paginated result with data and metadata\n *\n * @example\n * ```typescript\n * const result = await this.paginate(\n * async ({ skip, take }) => {\n * const items = await db.user.findMany({ skip, take });\n * const total = await db.user.count();\n * return { items, total };\n * },\n * 1,\n * 100\n * );\n * ```\n */\n protected async paginate(\n queryFn: PaginateQueryFn<T>,\n page: number = 1,\n pageSize: number = 100\n ): Promise<PaginateResult<T>> {\n const skip = (page - 1) * pageSize;\n const take = pageSize;\n\n const { items, total } = await queryFn({ skip, take });\n\n return {\n data: items,\n total,\n hasMore: skip + items.length < total,\n nextCursor: items.length > 0 && skip + items.length < total ? String(page + 1) : undefined,\n };\n }\n\n /**\n * Fetch all data using cursor-based pagination\n *\n * Use this for exporting large datasets efficiently.\n *\n * @param fetchBatch - Function to fetch a batch of data\n * @param batchSize - Number of items per batch\n * @returns All fetched items\n *\n * @example\n * ```typescript\n * const allUsers = await this.fetchAll(\n * async (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n * ```\n */\n protected async fetchAll(\n fetchBatch: (cursor?: string) => Promise<(T & { id: string })[]>,\n batchSize: number = 100\n ): Promise<T[]> {\n const allItems: T[] = [];\n let cursor: string | undefined;\n\n while (true) {\n const batch = await fetchBatch(cursor);\n\n if (batch.length === 0) {\n break;\n }\n\n allItems.push(...batch);\n\n // Get cursor from last item\n const lastItem = batch[batch.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than batch size, we're done\n if (batch.length < batchSize) {\n break;\n }\n }\n\n return allItems;\n }\n\n /**\n * Transform entity for export\n *\n * Override this method to customize how entities are transformed before export.\n * Default implementation returns the entity as-is after field filtering.\n *\n * @param entity - Entity to transform\n * @param excludeFields - Fields to exclude\n * @returns Transformed entity\n */\n protected transformForExport(entity: T, excludeFields?: string[]): Record<string, unknown> {\n return this.filterFields(entity, excludeFields);\n }\n\n /**\n * Validate export options\n *\n * Override this to add custom validation for export options.\n *\n * @param options - Export options to validate\n * @throws Error if options are invalid\n */\n protected validateOptions(options: ExportOptions): void {\n const validFormats = ['csv', 'json', 'xlsx'];\n if (!validFormats.includes(options.format)) {\n throw new Error(`Invalid export format: ${options.format}. Valid formats: ${validFormats.join(', ')}`);\n }\n }\n\n /**\n * Get supported export formats\n *\n * @returns Array of supported format strings\n */\n getSupportedFormats(): string[] {\n return ['csv', 'json', 'xlsx'];\n }\n\n /**\n * Get module metadata\n *\n * @returns Module metadata object\n */\n getMetadata(): {\n moduleKey?: string;\n displayName?: string;\n description?: string;\n supportedProducts?: string[];\n supportedFormats: string[];\n } {\n return {\n moduleKey: this.moduleKey,\n displayName: this.displayName,\n description: this.description,\n supportedProducts: this.supportedProducts,\n supportedFormats: this.getSupportedFormats(),\n };\n }\n}\n","/**\n * Pagination Service\n *\n * Provides pagination utilities for export operations across all Burdenoff microservices.\n * Supports both offset-based and cursor-based pagination strategies.\n *\n * @module export/pagination\n *\n * @example\n * ```typescript\n * import { PaginationService } from '@burdenoff/be-sdk/export';\n *\n * // Offset-based pagination\n * const result = PaginationService.paginate(items, { page: 2, pageSize: 20 });\n *\n * // Cursor-based pagination with async generator\n * for await (const item of PaginationService.paginatedQuery(fetchFn, { limit: 100 })) {\n * console.log(item);\n * }\n * ```\n */\n\nimport type { PaginatedQueryOptions, PaginatedResult, PaginationParams } from './types.js';\n\n/**\n * Service providing pagination utilities for export and data fetching operations\n */\nexport class PaginationService {\n /**\n * Paginate an array of items using offset-based pagination\n *\n * @param items - Array of items to paginate\n * @param params - Pagination parameters\n * @returns Paginated result with items and metadata\n *\n * @example\n * ```typescript\n * const allUsers = await db.user.findMany();\n * const page = PaginationService.paginate(allUsers, { page: 1, pageSize: 10 });\n * console.log(page.items); // First 10 users\n * console.log(page.pageInfo.hasNextPage); // true if more pages exist\n * ```\n */\n static paginate<T>(items: T[], params: PaginationParams): PaginatedResult<T> {\n const page = params.page ?? 1;\n const pageSize = params.pageSize ?? 20;\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n const paginatedItems = items.slice(start, end);\n\n return {\n items: paginatedItems,\n totalCount: items.length,\n pageInfo: {\n hasNextPage: end < items.length,\n hasPreviousPage: page > 1,\n startCursor: paginatedItems.length > 0 ? String(start) : undefined,\n endCursor: paginatedItems.length > 0 ? String(Math.min(end, items.length) - 1) : undefined,\n },\n };\n }\n\n /**\n * Calculate pagination metadata without slicing data\n *\n * @param totalCount - Total number of items\n * @param page - Current page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Pagination metadata\n *\n * @example\n * ```typescript\n * const meta = PaginationService.calculatePagination(150, 3, 20);\n * // meta.hasNextPage = true (page 4 exists)\n * // meta.hasPreviousPage = true (page 2 exists)\n * // meta.totalPages = 8\n * ```\n */\n static calculatePagination(\n totalCount: number,\n page: number,\n pageSize: number\n ): {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n totalPages: number;\n currentPage: number;\n pageSize: number;\n startIndex: number;\n endIndex: number;\n } {\n const totalPages = Math.ceil(totalCount / pageSize);\n const startIndex = (page - 1) * pageSize;\n const endIndex = Math.min(startIndex + pageSize - 1, totalCount - 1);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1,\n totalPages,\n currentPage: page,\n pageSize,\n startIndex,\n endIndex,\n };\n }\n\n /**\n * Async generator for paginated database queries using cursor-based pagination\n *\n * This is ideal for processing large datasets without loading everything into memory.\n * The generator yields items one at a time, fetching new batches as needed.\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Async generator of items\n *\n * @example\n * ```typescript\n * // Define fetch function that queries the database\n * const fetchUsers = async (cursor?: string) => {\n * return db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * });\n * };\n *\n * // Process all users without loading all into memory\n * for await (const user of PaginationService.paginatedQuery(fetchUsers)) {\n * await processUser(user);\n * }\n * ```\n */\n static async *paginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): AsyncGenerator<T, void, unknown> {\n const { limit, initialCursor } = options;\n let cursor = initialCursor;\n let hasMore = true;\n let totalYielded = 0;\n\n while (hasMore) {\n const items = await fetchFn(cursor);\n\n if (items.length === 0) {\n break;\n }\n\n for (const item of items) {\n yield item;\n totalYielded++;\n\n if (limit && totalYielded >= limit) {\n return;\n }\n }\n\n // Get next cursor from last item\n const lastItem = items[items.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than expected batch size, we're done\n // Note: This assumes fetchFn respects a consistent batch size internally\n hasMore = items.length > 0;\n }\n }\n\n /**\n * Collect all items from a paginated query into an array\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Array of all items\n *\n * @example\n * ```typescript\n * const allUsers = await PaginationService.collectPaginatedQuery(fetchUsers, { limit: 1000 });\n * ```\n */\n static async collectPaginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): Promise<T[]> {\n const items: T[] = [];\n\n for await (const item of PaginationService.paginatedQuery(fetchFn, options)) {\n items.push(item);\n }\n\n return items;\n }\n\n /**\n * Create a cursor-based paginated fetch function from a Prisma-style query\n *\n * @param queryFn - Prisma-style query function\n * @param batchSize - Number of items to fetch per batch\n * @returns Fetch function compatible with paginatedQuery\n *\n * @example\n * ```typescript\n * const fetchFn = PaginationService.createPrismaFetchFn(\n * (cursor) => db.user.findMany({\n * where: { isActive: true, ...(cursor ? { id: { gt: cursor } } : {}) },\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n *\n * for await (const user of PaginationService.paginatedQuery(fetchFn)) {\n * console.log(user);\n * }\n * ```\n */\n static createPrismaFetchFn<T extends { id: string }>(\n queryFn: (cursor?: string) => Promise<T[]>,\n _batchSize: number = 100\n ): (cursor?: string) => Promise<T[]> {\n return queryFn;\n }\n\n /**\n * Calculate offset for skip-based pagination\n *\n * @param page - Page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Offset value for skip\n */\n static calculateOffset(page: number, pageSize: number): number {\n return (Math.max(1, page) - 1) * pageSize;\n }\n\n /**\n * Parse cursor string to extract pagination state\n *\n * @param cursor - Base64-encoded cursor string\n * @returns Decoded cursor data or null if invalid\n */\n static parseCursor<T = Record<string, unknown>>(cursor: string): T | null {\n try {\n const decoded = Buffer.from(cursor, 'base64').toString('utf-8');\n return JSON.parse(decoded) as T;\n } catch {\n return null;\n }\n }\n\n /**\n * Create cursor string from pagination state\n *\n * @param data - Data to encode in cursor\n * @returns Base64-encoded cursor string\n */\n static createCursor(data: Record<string, unknown>): string {\n return Buffer.from(JSON.stringify(data)).toString('base64');\n }\n}\n","/**\n * CSV Utilities\n *\n * Utilities for converting data to CSV format for export operations.\n *\n * @module export/csv\n *\n * @example\n * ```typescript\n * import { convertToCSV, parseCSV } from '@burdenoff/be-sdk/export';\n *\n * const csv = convertToCSV(users, { includeHeaders: true });\n * console.log(csv);\n * ```\n */\n\nimport type { CSVConversionOptions } from './types.js';\n\nconst FORMULA_PREFIX_RE = /^[=+\\-@]/;\n\nexport function sanitizeCSVCell(value: string): string {\n return FORMULA_PREFIX_RE.test(value) ? `'${value}` : value;\n}\n\n/**\n * Convert an array of objects to CSV format\n *\n * Handles nested objects by flattening them with dot notation.\n * Arrays are JSON stringified.\n * Dates are converted to ISO strings.\n *\n * @param data - Array of objects to convert\n * @param options - CSV conversion options\n * @returns CSV string\n *\n * @example\n * ```typescript\n * const users = [\n * { id: 1, name: 'John', address: { city: 'NYC' } },\n * { id: 2, name: 'Jane', address: { city: 'LA' } },\n * ];\n *\n * const csv = convertToCSV(users);\n * // Output:\n * // id,name,address.city\n * // 1,John,NYC\n * // 2,Jane,LA\n * ```\n */\nexport function convertToCSV(data: unknown[], options: CSVConversionOptions = {}): string {\n const { delimiter = ',', includeHeaders = true, flattenFields = true, maxFlattenDepth = 3 } = options;\n\n if (data.length === 0) {\n return '';\n }\n\n // Flatten objects and get all keys\n const flattenObject = (obj: unknown, prefix = '', depth = 0): Record<string, string> => {\n const result: Record<string, string> = {};\n\n if (obj === null || obj === undefined) {\n return result;\n }\n\n if (typeof obj !== 'object') {\n return { [prefix || 'value']: String(obj) };\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n result[newKey] = '';\n } else if (value instanceof Date) {\n result[newKey] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object' && flattenFields && depth < maxFlattenDepth) {\n Object.assign(result, flattenObject(value, newKey, depth + 1));\n } else if (typeof value === 'object') {\n result[newKey] = JSON.stringify(value);\n } else {\n result[newKey] = String(value);\n }\n }\n\n return result;\n };\n\n // Flatten all records and collect all keys\n const flattenedRecords = data.map((item) => flattenObject(item));\n const allKeys = new Set<string>();\n for (const record of flattenedRecords) {\n for (const key of Object.keys(record)) {\n allKeys.add(key);\n }\n }\n\n const headers = Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n\n // Escape CSV values\n const escapeCSV = (value: string): string => {\n const sanitizedValue = sanitizeCSVCell(value);\n\n if (\n sanitizedValue.includes(delimiter) ||\n sanitizedValue.includes('\"') ||\n sanitizedValue.includes('\\n') ||\n sanitizedValue.includes('\\r')\n ) {\n return `\"${sanitizedValue.replace(/\"/g, '\"\"')}\"`;\n }\n return sanitizedValue;\n };\n\n // Build CSV\n const lines: string[] = [];\n\n if (includeHeaders) {\n lines.push(headers.map(escapeCSV).join(delimiter));\n }\n\n for (const record of flattenedRecords) {\n const row = headers.map((header) => escapeCSV(record[header] || ''));\n lines.push(row.join(delimiter));\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Parse a CSV string into an array of objects\n *\n * @param csv - CSV string to parse\n * @param options - Parse options\n * @returns Array of parsed objects\n *\n * @example\n * ```typescript\n * const csv = 'id,name\\n1,John\\n2,Jane';\n * const data = parseCSV(csv);\n * // [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }]\n * ```\n */\nexport function parseCSV(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean } = {}\n): Record<string, string>[] {\n const { delimiter = ',', hasHeaders = true } = options;\n\n const lines = csv.split(/\\r?\\n/).filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n // Parse a single CSV line, handling quoted values\n const parseLine = (line: string): string[] => {\n const values: string[] = [];\n let current = '';\n let inQuotes = false;\n\n let i = 0;\n while (i < line.length) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n if (char === '\"' && inQuotes && nextChar === '\"') {\n current += '\"';\n i += 2; // Skip next quote\n } else if (char === '\"') {\n inQuotes = !inQuotes;\n i++;\n } else if (char === delimiter && !inQuotes) {\n values.push(current);\n current = '';\n i++;\n } else {\n current += char;\n i++;\n }\n }\n\n values.push(current);\n return values;\n };\n\n let headers: string[];\n let dataLines: string[];\n\n // We've already checked that lines.length > 0, so lines[0] is guaranteed to exist\n const firstLine = lines[0] as string;\n\n if (hasHeaders) {\n headers = parseLine(firstLine);\n dataLines = lines.slice(1);\n } else {\n // Generate numeric headers if no header row\n const firstRow = parseLine(firstLine);\n headers = firstRow.map((_, i) => `col${i}`);\n dataLines = lines;\n }\n\n return dataLines.map((line) => {\n const values = parseLine(line);\n const obj: Record<string, string> = {};\n\n headers.forEach((header, i) => {\n obj[header] = values[i] || '';\n });\n\n return obj;\n });\n}\n\n/**\n * Convert CSV to JSON string\n *\n * @param csv - CSV string\n * @param options - Parse options\n * @returns JSON string\n */\nexport function csvToJSON(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean; pretty?: boolean } = {}\n): string {\n const { pretty = false, ...parseOptions } = options;\n const data = parseCSV(csv, parseOptions);\n return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n}\n\n/**\n * Get CSV headers from data\n *\n * @param data - Array of objects\n * @param flattenFields - Whether to flatten nested objects\n * @returns Array of header strings\n */\nexport function getCSVHeaders(data: unknown[], flattenFields: boolean = true): string[] {\n if (data.length === 0) {\n return [];\n }\n\n const collectKeys = (obj: unknown, prefix = '', depth = 0): string[] => {\n const keys: string[] = [];\n\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return prefix ? [prefix] : [];\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n flattenFields &&\n depth < 3\n ) {\n keys.push(...collectKeys(value, fullKey, depth + 1));\n } else {\n keys.push(fullKey);\n }\n }\n\n return keys;\n };\n\n const allKeys = new Set<string>();\n for (const item of data) {\n for (const key of collectKeys(item)) {\n allKeys.add(key);\n }\n }\n\n return Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n}\n\n/**\n * Estimate CSV file size for a dataset\n *\n * @param data - Array of objects\n * @param sampleSize - Number of records to sample for estimation\n * @returns Estimated size in bytes\n */\nexport function estimateCSVSize(data: unknown[], sampleSize: number = 100): number {\n if (data.length === 0) {\n return 0;\n }\n\n // Take a sample to estimate average row size\n const sample = data.slice(0, Math.min(sampleSize, data.length));\n const sampleCSV = convertToCSV(sample);\n const averageRowSize = sampleCSV.length / sample.length;\n\n // Estimate total size (headers + data rows)\n const headers = getCSVHeaders(data);\n const headerSize = headers.join(',').length + 1; // +1 for newline\n\n return Math.ceil(headerSize + averageRowSize * data.length);\n}\n","/**\n * Export Gateway Helper\n *\n * Centralised wrapper around the workspace internal gateway's\n * `createExportJob` mutation, used by per-svc convenience resolvers\n * (e.g. `createTagsExportJob`, `createGroupsExportJob`).\n *\n * Replaces the duplicated `src/clients/export-gateway.ts` files that\n * existed in 19+ workspace svcs.\n *\n * @module export/gateway-client\n *\n * @example\n * ```typescript\n * import { triggerExportJob } from '@burdenoff/be-sdk/export';\n *\n * const result = await triggerExportJob({\n * serviceName: 'wspace-tags-svc',\n * workspaceId: ctx.workspaceId,\n * name: input.name,\n * entityTypes: ['tags', 'vocabularies'],\n * format: input.format,\n * actorId: ctx.actorId,\n * actorType: ctx.actorType,\n * });\n * ```\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\n\nconst CREATE_EXPORT_JOB_MUTATION = `mutation CreateExportJob($input: CreateExportJobInput!) {\n createExportJob(input: $input) {\n id\n status\n workspaceId\n entityTypes\n format\n createdAt\n }\n}`;\n\nexport type ExportActorType = 'user' | 'app' | 'service' | 'super_admin';\nexport type ExportFormatGql = 'JSON' | 'CSV';\n\nexport interface TriggerExportJobParams {\n /** Caller service name, used by gateway client telemetry/auth */\n serviceName: string;\n /** Layer for the gateway. Defaults to `wspace`. */\n layer?: ServiceLayer;\n /** Workspace context (required for wspace exports). Sent as the `x-workspace-id` header, never in the input. */\n workspaceId: string;\n /** Human-readable name for the export job. */\n name: string;\n /** Entity types registered in `wspace-export-svc` to include. */\n entityTypes: string[];\n /** Output format. */\n format: ExportFormatGql;\n /** Actor making the request (forwarded to RBAC). */\n actorId: string;\n actorType: ExportActorType;\n /** Whether to include extended metadata in the export ZIP. */\n includeMetadata?: boolean;\n /** Optional ISO date-range bounds. */\n dateRangeStart?: string;\n dateRangeEnd?: string;\n}\n\nexport interface ExportJobResult {\n id: string;\n status: string;\n workspaceId: string;\n entityTypes: string[];\n format: string;\n createdAt: string;\n}\n\ninterface CreateExportJobResponse {\n createExportJob?: ExportJobResult;\n}\n\n/**\n * Submit a `createExportJob` mutation to the workspace internal gateway.\n *\n * The caller is expected to map the returned `ExportJobResult` to its\n * own GraphQL output type (the per-svc `ExportJobResponse`).\n */\nexport async function triggerExportJob(params: TriggerExportJobParams): Promise<ExportJobResult> {\n const {\n serviceName,\n layer = 'wspace',\n actorId,\n actorType,\n workspaceId,\n name,\n entityTypes,\n format,\n includeMetadata,\n dateRangeStart,\n dateRangeEnd,\n } = params;\n\n const client = new GatewayClient({ layer, serviceName });\n\n // `CreateExportJobInput` carries no `workspaceId`: wspace-export-svc takes\n // the workspace from the `x-workspace-id` header so a caller can never\n // export another tenant's data. Sending the field makes GraphQL reject the\n // whole variable (\"Field \\\"workspaceId\\\" is not defined by type\n // \\\"CreateExportJobInput\\\"\"), so the workspace travels in the header only.\n const input = {\n name,\n entityTypes,\n format,\n ...(includeMetadata !== undefined ? { includeMetadata } : {}),\n ...(dateRangeStart !== undefined ? { dateRangeStart } : {}),\n ...(dateRangeEnd !== undefined ? { dateRangeEnd } : {}),\n };\n\n const response = await client.internalQuery<CreateExportJobResponse>({\n query: CREATE_EXPORT_JOB_MUTATION,\n variables: { input },\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType,\n 'x-workspace-id': workspaceId,\n },\n });\n\n const job = response.data?.createExportJob;\n if (!job) {\n throw new Error('Export service did not return a job');\n }\n return job;\n}\n","/**\n * Export Module\n *\n * Provides common utilities for data export operations across all Burdenoff microservices.\n * Includes pagination services, base exporter classes, CSV utilities, and type definitions.\n *\n * @module export\n *\n * @example\n * ```typescript\n * // Import from the export module\n * import {\n * BaseModuleExporter,\n * PaginationService,\n * convertToCSV,\n * } from '@burdenoff/be-sdk/export';\n *\n * // Create a custom exporter\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * const data = await this.fetchAll(\n * (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : {},\n * take: 100,\n * })\n * );\n *\n * const csv = convertToCSV(data);\n * return { data, format: 'csv' };\n * }\n * }\n *\n * // Use pagination utilities\n * const result = PaginationService.paginate(items, { page: 1, pageSize: 20 });\n * ```\n */\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type {\n // Export format types\n ExportFormat,\n ExportFormatEnum,\n\n // Configuration types\n ExportConfig,\n ExportOptions,\n\n // Job types\n ExportJobStatus,\n ExportJob,\n ExportProgress,\n ExportResult,\n\n // Fetch types\n ExportFetchOptions,\n ExportFetchResult,\n\n // Pagination types\n PaginationParams,\n PaginatedResult,\n PaginatedQueryOptions,\n PaginateResult,\n PaginateQueryFn,\n\n // Module interface\n ExportableModule,\n\n // CSV types\n CSVConversionOptions,\n} from './types.js';\n\n// ============================================================================\n// Class Exports\n// ============================================================================\n\nexport { BaseModuleExporter } from './base-exporter.js';\nexport { PaginationService } from './pagination.js';\n\n// ============================================================================\n// Function Exports\n// ============================================================================\n\nexport { convertToCSV, parseCSV, csvToJSON, getCSVHeaders, estimateCSVSize } from './csv.js';\n\n// ============================================================================\n// Gateway Helper Exports\n// ============================================================================\n\nexport { triggerExportJob } from './gateway-client.js';\nexport type { TriggerExportJobParams, ExportJobResult, ExportActorType, ExportFormatGql } from './gateway-client.js';\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,IAAsB,qBAAtB,MAAsD;;CAEpD;;CAGA;;CAGA;;CAGA;;CAGA;;CAGA,AAAU;;;;;;;;;;;;;;;;;CA6BV,AAAU,aAAa,QAAqC,eAAmD;EAC7G,MAAM,kBAAkB,iBAAiB,KAAK,wBAAwB,CAAC;EAEvE,IAAI,gBAAgB,WAAW,GAC7B,OAAO;EAGT,MAAM,WAAoC,CAAC;EAC3C,MAAM,SAAS;EAEf,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,CAAC,gBAAgB,SAAS,GAAG,GAC/B,SAAS,OAAO;EAIpB,OAAO;CACT;;;;;;;;CASA,AAAU,iBACR,UACA,eAC2B;EAC3B,OAAO,SAAS,KAAK,WAAW,KAAK,aAAa,QAAQ,aAAa,CAAC;CAC1E;;;;;;;;;;;;;;;;;;;;;;;;CAyBA,MAAgB,SACd,SACA,OAAe,GACf,WAAmB,KACS;EAC5B,MAAM,QAAQ,OAAO,KAAK;EAG1B,MAAM,EAAE,OAAO,UAAU,MAAM,QAAQ;GAAE;GAAM;EAAK,CAAC;EAErD,OAAO;GACL,MAAM;GACN;GACA,SAAS,OAAO,MAAM,SAAS;GAC/B,YAAY,MA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D,GAAI,mBAAmB,SAAY,EAAE,eAAe,IAAI,CAAC;EACzD,GAAI,iBAAiB,SAAY,EAAE,aAAa,IAAI,CAAC;CACvD;CAYA,MAAM,OAAM,MAVW,OAAO,cAAuC;EACnE,OAAO;EACP,WAAW,EAAE,MAAM;EACnB,SAAS;GACP,cAAc;GACd,gBAAgB;GAChB,kBAAkB;EACpB;CACF,CAAC,EAEmB,CAAC,MAAM;CAC3B,IAAI,CAAC,KACH,MAAM,IAAI,MAAM,qCAAqC;CAEvD,OAAO;AACT"}
1
+ {"version":3,"file":"export-DJXE3Osa.js","names":[],"sources":["../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts","../src/export/index.ts"],"sourcesContent":["/**\n * Base Module Exporter\n *\n * Abstract base class for module exporters across all Burdenoff microservices.\n * Provides common functionality for exporting data from different modules.\n *\n * @module export/base-exporter\n *\n * @example\n * ```typescript\n * import { BaseModuleExporter } from '@burdenoff/be-sdk/export';\n *\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n * description = 'Export user data';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * // Implementation\n * }\n * }\n * ```\n */\n\nimport type { ExportOptions, ExportResult, PaginateQueryFn, PaginateResult } from './types.js';\n\n/**\n * Abstract base class for module exporters\n *\n * Provides common functionality that all module exporters can inherit:\n * - Field filtering\n * - Pagination helpers\n * - Module metadata\n *\n * @typeParam T - The type of entity this exporter handles\n */\nexport abstract class BaseModuleExporter<T = unknown> {\n /** Unique key identifying this module (e.g., 'users', 'tags', 'orders') */\n moduleKey?: string;\n\n /** Human-readable display name for the module */\n displayName?: string;\n\n /** Description of what this module exports */\n description?: string;\n\n /** Default fields to exclude from export (e.g., sensitive data) */\n defaultExcludeFields?: string[];\n\n /** List of product IDs this exporter supports */\n supportedProducts?: string[];\n\n /** Model name for database operations */\n protected modelName?: string;\n\n /**\n * Export data from this module\n *\n * Subclasses should implement this method to perform the actual export.\n * The method is optional to allow for gradual implementation.\n *\n * @param options - Export options including format, filters, and pagination\n * @returns Export result with data or download URL\n */\n export?(options: ExportOptions): Promise<ExportResult>;\n\n /**\n * Filter fields from an entity based on exclude list\n *\n * Use this to remove sensitive or unnecessary fields from exported data.\n *\n * @param entity - Entity to filter\n * @param excludeFields - Fields to exclude (uses defaultExcludeFields if not provided)\n * @returns Filtered entity as a plain object\n *\n * @example\n * ```typescript\n * const user = { id: '1', name: 'John', password: 'secret', ssn: '123' };\n * const filtered = this.filterFields(user, ['password', 'ssn']);\n * // Result: { id: '1', name: 'John' }\n * ```\n */\n protected filterFields(entity: T | Record<string, unknown>, excludeFields?: string[]): Record<string, unknown> {\n const fieldsToExclude = excludeFields || this.defaultExcludeFields || [];\n\n if (fieldsToExclude.length === 0) {\n return entity as Record<string, unknown>;\n }\n\n const filtered: Record<string, unknown> = {};\n const record = entity as Record<string, unknown>;\n\n for (const [key, value] of Object.entries(record)) {\n if (!fieldsToExclude.includes(key)) {\n filtered[key] = value;\n }\n }\n\n return filtered;\n }\n\n /**\n * Filter multiple entities\n *\n * @param entities - Array of entities to filter\n * @param excludeFields - Fields to exclude\n * @returns Array of filtered entities\n */\n protected filterFieldsMany(\n entities: (T | Record<string, unknown>)[],\n excludeFields?: string[]\n ): Record<string, unknown>[] {\n return entities.map((entity) => this.filterFields(entity, excludeFields));\n }\n\n /**\n * Paginate helper for database queries\n *\n * Use this to implement paginated data fetching in your export method.\n *\n * @param queryFn - Function that executes the paginated query\n * @param page - Page number (1-indexed)\n * @param pageSize - Number of items per page\n * @returns Paginated result with data and metadata\n *\n * @example\n * ```typescript\n * const result = await this.paginate(\n * async ({ skip, take }) => {\n * const items = await db.user.findMany({ skip, take });\n * const total = await db.user.count();\n * return { items, total };\n * },\n * 1,\n * 100\n * );\n * ```\n */\n protected async paginate(\n queryFn: PaginateQueryFn<T>,\n page: number = 1,\n pageSize: number = 100\n ): Promise<PaginateResult<T>> {\n const skip = (page - 1) * pageSize;\n const take = pageSize;\n\n const { items, total } = await queryFn({ skip, take });\n\n return {\n data: items,\n total,\n hasMore: skip + items.length < total,\n nextCursor: items.length > 0 && skip + items.length < total ? String(page + 1) : undefined,\n };\n }\n\n /**\n * Fetch all data using cursor-based pagination\n *\n * Use this for exporting large datasets efficiently.\n *\n * @param fetchBatch - Function to fetch a batch of data\n * @param batchSize - Number of items per batch\n * @returns All fetched items\n *\n * @example\n * ```typescript\n * const allUsers = await this.fetchAll(\n * async (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n * ```\n */\n protected async fetchAll(\n fetchBatch: (cursor?: string) => Promise<(T & { id: string })[]>,\n batchSize: number = 100\n ): Promise<T[]> {\n const allItems: T[] = [];\n let cursor: string | undefined;\n\n while (true) {\n const batch = await fetchBatch(cursor);\n\n if (batch.length === 0) {\n break;\n }\n\n allItems.push(...batch);\n\n // Get cursor from last item\n const lastItem = batch[batch.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than batch size, we're done\n if (batch.length < batchSize) {\n break;\n }\n }\n\n return allItems;\n }\n\n /**\n * Transform entity for export\n *\n * Override this method to customize how entities are transformed before export.\n * Default implementation returns the entity as-is after field filtering.\n *\n * @param entity - Entity to transform\n * @param excludeFields - Fields to exclude\n * @returns Transformed entity\n */\n protected transformForExport(entity: T, excludeFields?: string[]): Record<string, unknown> {\n return this.filterFields(entity, excludeFields);\n }\n\n /**\n * Validate export options\n *\n * Override this to add custom validation for export options.\n *\n * @param options - Export options to validate\n * @throws Error if options are invalid\n */\n protected validateOptions(options: ExportOptions): void {\n const validFormats = ['csv', 'json', 'xlsx'];\n if (!validFormats.includes(options.format)) {\n throw new Error(`Invalid export format: ${options.format}. Valid formats: ${validFormats.join(', ')}`);\n }\n }\n\n /**\n * Get supported export formats\n *\n * @returns Array of supported format strings\n */\n getSupportedFormats(): string[] {\n return ['csv', 'json', 'xlsx'];\n }\n\n /**\n * Get module metadata\n *\n * @returns Module metadata object\n */\n getMetadata(): {\n moduleKey?: string;\n displayName?: string;\n description?: string;\n supportedProducts?: string[];\n supportedFormats: string[];\n } {\n return {\n moduleKey: this.moduleKey,\n displayName: this.displayName,\n description: this.description,\n supportedProducts: this.supportedProducts,\n supportedFormats: this.getSupportedFormats(),\n };\n }\n}\n","/**\n * Pagination Service\n *\n * Provides pagination utilities for export operations across all Burdenoff microservices.\n * Supports both offset-based and cursor-based pagination strategies.\n *\n * @module export/pagination\n *\n * @example\n * ```typescript\n * import { PaginationService } from '@burdenoff/be-sdk/export';\n *\n * // Offset-based pagination\n * const result = PaginationService.paginate(items, { page: 2, pageSize: 20 });\n *\n * // Cursor-based pagination with async generator\n * for await (const item of PaginationService.paginatedQuery(fetchFn, { limit: 100 })) {\n * console.log(item);\n * }\n * ```\n */\n\nimport type { PaginatedQueryOptions, PaginatedResult, PaginationParams } from './types.js';\n\n/**\n * Service providing pagination utilities for export and data fetching operations\n */\nexport class PaginationService {\n /**\n * Paginate an array of items using offset-based pagination\n *\n * @param items - Array of items to paginate\n * @param params - Pagination parameters\n * @returns Paginated result with items and metadata\n *\n * @example\n * ```typescript\n * const allUsers = await db.user.findMany();\n * const page = PaginationService.paginate(allUsers, { page: 1, pageSize: 10 });\n * console.log(page.items); // First 10 users\n * console.log(page.pageInfo.hasNextPage); // true if more pages exist\n * ```\n */\n static paginate<T>(items: T[], params: PaginationParams): PaginatedResult<T> {\n const page = params.page ?? 1;\n const pageSize = params.pageSize ?? 20;\n const start = (page - 1) * pageSize;\n const end = start + pageSize;\n\n const paginatedItems = items.slice(start, end);\n\n return {\n items: paginatedItems,\n totalCount: items.length,\n pageInfo: {\n hasNextPage: end < items.length,\n hasPreviousPage: page > 1,\n startCursor: paginatedItems.length > 0 ? String(start) : undefined,\n endCursor: paginatedItems.length > 0 ? String(Math.min(end, items.length) - 1) : undefined,\n },\n };\n }\n\n /**\n * Calculate pagination metadata without slicing data\n *\n * @param totalCount - Total number of items\n * @param page - Current page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Pagination metadata\n *\n * @example\n * ```typescript\n * const meta = PaginationService.calculatePagination(150, 3, 20);\n * // meta.hasNextPage = true (page 4 exists)\n * // meta.hasPreviousPage = true (page 2 exists)\n * // meta.totalPages = 8\n * ```\n */\n static calculatePagination(\n totalCount: number,\n page: number,\n pageSize: number\n ): {\n hasNextPage: boolean;\n hasPreviousPage: boolean;\n totalPages: number;\n currentPage: number;\n pageSize: number;\n startIndex: number;\n endIndex: number;\n } {\n const totalPages = Math.ceil(totalCount / pageSize);\n const startIndex = (page - 1) * pageSize;\n const endIndex = Math.min(startIndex + pageSize - 1, totalCount - 1);\n\n return {\n hasNextPage: page < totalPages,\n hasPreviousPage: page > 1,\n totalPages,\n currentPage: page,\n pageSize,\n startIndex,\n endIndex,\n };\n }\n\n /**\n * Async generator for paginated database queries using cursor-based pagination\n *\n * This is ideal for processing large datasets without loading everything into memory.\n * The generator yields items one at a time, fetching new batches as needed.\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Async generator of items\n *\n * @example\n * ```typescript\n * // Define fetch function that queries the database\n * const fetchUsers = async (cursor?: string) => {\n * return db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : undefined,\n * orderBy: { id: 'asc' },\n * take: 100,\n * });\n * };\n *\n * // Process all users without loading all into memory\n * for await (const user of PaginationService.paginatedQuery(fetchUsers)) {\n * await processUser(user);\n * }\n * ```\n */\n static async *paginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): AsyncGenerator<T, void, unknown> {\n const { limit, initialCursor } = options;\n let cursor = initialCursor;\n let hasMore = true;\n let totalYielded = 0;\n\n while (hasMore) {\n const items = await fetchFn(cursor);\n\n if (items.length === 0) {\n break;\n }\n\n for (const item of items) {\n yield item;\n totalYielded++;\n\n if (limit && totalYielded >= limit) {\n return;\n }\n }\n\n // Get next cursor from last item\n const lastItem = items[items.length - 1];\n if (lastItem) {\n cursor = lastItem.id;\n }\n\n // If we got fewer items than expected batch size, we're done\n // Note: This assumes fetchFn respects a consistent batch size internally\n hasMore = items.length > 0;\n }\n }\n\n /**\n * Collect all items from a paginated query into an array\n *\n * @param fetchFn - Function to fetch data given a cursor\n * @param options - Pagination options\n * @returns Array of all items\n *\n * @example\n * ```typescript\n * const allUsers = await PaginationService.collectPaginatedQuery(fetchUsers, { limit: 1000 });\n * ```\n */\n static async collectPaginatedQuery<T extends { id: string }>(\n fetchFn: (cursor?: string) => Promise<T[]>,\n options: PaginatedQueryOptions = {}\n ): Promise<T[]> {\n const items: T[] = [];\n\n for await (const item of PaginationService.paginatedQuery(fetchFn, options)) {\n items.push(item);\n }\n\n return items;\n }\n\n /**\n * Create a cursor-based paginated fetch function from a Prisma-style query\n *\n * @param queryFn - Prisma-style query function\n * @param batchSize - Number of items to fetch per batch\n * @returns Fetch function compatible with paginatedQuery\n *\n * @example\n * ```typescript\n * const fetchFn = PaginationService.createPrismaFetchFn(\n * (cursor) => db.user.findMany({\n * where: { isActive: true, ...(cursor ? { id: { gt: cursor } } : {}) },\n * orderBy: { id: 'asc' },\n * take: 100,\n * }),\n * 100\n * );\n *\n * for await (const user of PaginationService.paginatedQuery(fetchFn)) {\n * console.log(user);\n * }\n * ```\n */\n static createPrismaFetchFn<T extends { id: string }>(\n queryFn: (cursor?: string) => Promise<T[]>,\n _batchSize: number = 100\n ): (cursor?: string) => Promise<T[]> {\n return queryFn;\n }\n\n /**\n * Calculate offset for skip-based pagination\n *\n * @param page - Page number (1-indexed)\n * @param pageSize - Items per page\n * @returns Offset value for skip\n */\n static calculateOffset(page: number, pageSize: number): number {\n return (Math.max(1, page) - 1) * pageSize;\n }\n\n /**\n * Parse cursor string to extract pagination state\n *\n * @param cursor - Base64-encoded cursor string\n * @returns Decoded cursor data or null if invalid\n */\n static parseCursor<T = Record<string, unknown>>(cursor: string): T | null {\n try {\n const decoded = Buffer.from(cursor, 'base64').toString('utf-8');\n return JSON.parse(decoded) as T;\n } catch {\n return null;\n }\n }\n\n /**\n * Create cursor string from pagination state\n *\n * @param data - Data to encode in cursor\n * @returns Base64-encoded cursor string\n */\n static createCursor(data: Record<string, unknown>): string {\n return Buffer.from(JSON.stringify(data)).toString('base64');\n }\n}\n","/**\n * CSV Utilities\n *\n * Utilities for converting data to CSV format for export operations.\n *\n * @module export/csv\n *\n * @example\n * ```typescript\n * import { convertToCSV, parseCSV } from '@burdenoff/be-sdk/export';\n *\n * const csv = convertToCSV(users, { includeHeaders: true });\n * console.log(csv);\n * ```\n */\n\nimport type { CSVConversionOptions } from './types.js';\n\nconst FORMULA_PREFIX_RE = /^[=+\\-@]/;\n\nexport function sanitizeCSVCell(value: string): string {\n return FORMULA_PREFIX_RE.test(value) ? `'${value}` : value;\n}\n\n/**\n * Convert an array of objects to CSV format\n *\n * Handles nested objects by flattening them with dot notation.\n * Arrays are JSON stringified.\n * Dates are converted to ISO strings.\n *\n * @param data - Array of objects to convert\n * @param options - CSV conversion options\n * @returns CSV string\n *\n * @example\n * ```typescript\n * const users = [\n * { id: 1, name: 'John', address: { city: 'NYC' } },\n * { id: 2, name: 'Jane', address: { city: 'LA' } },\n * ];\n *\n * const csv = convertToCSV(users);\n * // Output:\n * // id,name,address.city\n * // 1,John,NYC\n * // 2,Jane,LA\n * ```\n */\nexport function convertToCSV(data: unknown[], options: CSVConversionOptions = {}): string {\n const { delimiter = ',', includeHeaders = true, flattenFields = true, maxFlattenDepth = 3 } = options;\n\n if (data.length === 0) {\n return '';\n }\n\n // Flatten objects and get all keys\n const flattenObject = (obj: unknown, prefix = '', depth = 0): Record<string, string> => {\n const result: Record<string, string> = {};\n\n if (obj === null || obj === undefined) {\n return result;\n }\n\n if (typeof obj !== 'object') {\n return { [prefix || 'value']: String(obj) };\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value === null || value === undefined) {\n result[newKey] = '';\n } else if (value instanceof Date) {\n result[newKey] = value.toISOString();\n } else if (Array.isArray(value)) {\n result[newKey] = JSON.stringify(value);\n } else if (typeof value === 'object' && flattenFields && depth < maxFlattenDepth) {\n Object.assign(result, flattenObject(value, newKey, depth + 1));\n } else if (typeof value === 'object') {\n result[newKey] = JSON.stringify(value);\n } else {\n result[newKey] = String(value);\n }\n }\n\n return result;\n };\n\n // Flatten all records and collect all keys\n const flattenedRecords = data.map((item) => flattenObject(item));\n const allKeys = new Set<string>();\n for (const record of flattenedRecords) {\n for (const key of Object.keys(record)) {\n allKeys.add(key);\n }\n }\n\n const headers = Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n\n // Escape CSV values\n const escapeCSV = (value: string): string => {\n const sanitizedValue = sanitizeCSVCell(value);\n\n if (\n sanitizedValue.includes(delimiter) ||\n sanitizedValue.includes('\"') ||\n sanitizedValue.includes('\\n') ||\n sanitizedValue.includes('\\r')\n ) {\n return `\"${sanitizedValue.replace(/\"/g, '\"\"')}\"`;\n }\n return sanitizedValue;\n };\n\n // Build CSV\n const lines: string[] = [];\n\n if (includeHeaders) {\n lines.push(headers.map(escapeCSV).join(delimiter));\n }\n\n for (const record of flattenedRecords) {\n const row = headers.map((header) => escapeCSV(record[header] || ''));\n lines.push(row.join(delimiter));\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Parse a CSV string into an array of objects\n *\n * @param csv - CSV string to parse\n * @param options - Parse options\n * @returns Array of parsed objects\n *\n * @example\n * ```typescript\n * const csv = 'id,name\\n1,John\\n2,Jane';\n * const data = parseCSV(csv);\n * // [{ id: '1', name: 'John' }, { id: '2', name: 'Jane' }]\n * ```\n */\nexport function parseCSV(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean } = {}\n): Record<string, string>[] {\n const { delimiter = ',', hasHeaders = true } = options;\n\n const lines = csv.split(/\\r?\\n/).filter((line) => line.trim());\n\n if (lines.length === 0) {\n return [];\n }\n\n // Parse a single CSV line, handling quoted values\n const parseLine = (line: string): string[] => {\n const values: string[] = [];\n let current = '';\n let inQuotes = false;\n\n let i = 0;\n while (i < line.length) {\n const char = line[i];\n const nextChar = line[i + 1];\n\n if (char === '\"' && inQuotes && nextChar === '\"') {\n current += '\"';\n i += 2; // Skip next quote\n } else if (char === '\"') {\n inQuotes = !inQuotes;\n i++;\n } else if (char === delimiter && !inQuotes) {\n values.push(current);\n current = '';\n i++;\n } else {\n current += char;\n i++;\n }\n }\n\n values.push(current);\n return values;\n };\n\n let headers: string[];\n let dataLines: string[];\n\n // We've already checked that lines.length > 0, so lines[0] is guaranteed to exist\n const firstLine = lines[0] as string;\n\n if (hasHeaders) {\n headers = parseLine(firstLine);\n dataLines = lines.slice(1);\n } else {\n // Generate numeric headers if no header row\n const firstRow = parseLine(firstLine);\n headers = firstRow.map((_, i) => `col${i}`);\n dataLines = lines;\n }\n\n return dataLines.map((line) => {\n const values = parseLine(line);\n const obj: Record<string, string> = {};\n\n headers.forEach((header, i) => {\n obj[header] = values[i] || '';\n });\n\n return obj;\n });\n}\n\n/**\n * Convert CSV to JSON string\n *\n * @param csv - CSV string\n * @param options - Parse options\n * @returns JSON string\n */\nexport function csvToJSON(\n csv: string,\n options: { delimiter?: string; hasHeaders?: boolean; pretty?: boolean } = {}\n): string {\n const { pretty = false, ...parseOptions } = options;\n const data = parseCSV(csv, parseOptions);\n return pretty ? JSON.stringify(data, null, 2) : JSON.stringify(data);\n}\n\n/**\n * Get CSV headers from data\n *\n * @param data - Array of objects\n * @param flattenFields - Whether to flatten nested objects\n * @returns Array of header strings\n */\nexport function getCSVHeaders(data: unknown[], flattenFields: boolean = true): string[] {\n if (data.length === 0) {\n return [];\n }\n\n const collectKeys = (obj: unknown, prefix = '', depth = 0): string[] => {\n const keys: string[] = [];\n\n if (obj === null || obj === undefined || typeof obj !== 'object') {\n return prefix ? [prefix] : [];\n }\n\n for (const [key, value] of Object.entries(obj as Record<string, unknown>)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date) &&\n flattenFields &&\n depth < 3\n ) {\n keys.push(...collectKeys(value, fullKey, depth + 1));\n } else {\n keys.push(fullKey);\n }\n }\n\n return keys;\n };\n\n const allKeys = new Set<string>();\n for (const item of data) {\n for (const key of collectKeys(item)) {\n allKeys.add(key);\n }\n }\n\n return Array.from(allKeys).sort((a, b) => a.localeCompare(b));\n}\n\n/**\n * Estimate CSV file size for a dataset\n *\n * @param data - Array of objects\n * @param sampleSize - Number of records to sample for estimation\n * @returns Estimated size in bytes\n */\nexport function estimateCSVSize(data: unknown[], sampleSize: number = 100): number {\n if (data.length === 0) {\n return 0;\n }\n\n // Take a sample to estimate average row size\n const sample = data.slice(0, Math.min(sampleSize, data.length));\n const sampleCSV = convertToCSV(sample);\n const averageRowSize = sampleCSV.length / sample.length;\n\n // Estimate total size (headers + data rows)\n const headers = getCSVHeaders(data);\n const headerSize = headers.join(',').length + 1; // +1 for newline\n\n return Math.ceil(headerSize + averageRowSize * data.length);\n}\n","/**\n * Export Gateway Helper\n *\n * Centralised wrapper around the workspace internal gateway's\n * `createExportJob` mutation, used by per-svc convenience resolvers\n * (e.g. `createTagsExportJob`, `createGroupsExportJob`).\n *\n * Replaces the duplicated `src/clients/export-gateway.ts` files that\n * existed in 19+ workspace svcs.\n *\n * @module export/gateway-client\n *\n * @example\n * ```typescript\n * import { triggerExportJob } from '@burdenoff/be-sdk/export';\n *\n * const result = await triggerExportJob({\n * serviceName: 'wspace-tags-svc',\n * workspaceId: ctx.workspaceId,\n * name: input.name,\n * entityTypes: ['tags', 'vocabularies'],\n * format: input.format,\n * actorId: ctx.actorId,\n * actorType: ctx.actorType,\n * });\n * ```\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport type { ServiceLayer } from '../types/layer.js';\n\nconst CREATE_EXPORT_JOB_MUTATION = `mutation CreateExportJob($input: CreateExportJobInput!) {\n createExportJob(input: $input) {\n id\n status\n workspaceId\n entityTypes\n format\n createdAt\n }\n}`;\n\nexport type ExportActorType = 'user' | 'app' | 'service' | 'super_admin';\nexport type ExportFormatGql = 'JSON' | 'CSV';\n\nexport interface TriggerExportJobParams {\n /** Caller service name, used by gateway client telemetry/auth */\n serviceName: string;\n /** Layer for the gateway. Defaults to `wspace`. */\n layer?: ServiceLayer;\n /** Workspace context (required for wspace exports). Sent as the `x-workspace-id` header, never in the input. */\n workspaceId: string;\n /** Human-readable name for the export job. */\n name: string;\n /** Entity types registered in `wspace-export-svc` to include. */\n entityTypes: string[];\n /** Output format. */\n format: ExportFormatGql;\n /** Actor making the request (forwarded to RBAC). */\n actorId: string;\n actorType: ExportActorType;\n /** Whether to include extended metadata in the export ZIP. */\n includeMetadata?: boolean;\n /** Optional ISO date-range bounds. */\n dateRangeStart?: string;\n dateRangeEnd?: string;\n}\n\nexport interface ExportJobResult {\n id: string;\n status: string;\n workspaceId: string;\n entityTypes: string[];\n format: string;\n createdAt: string;\n}\n\ninterface CreateExportJobResponse {\n createExportJob?: ExportJobResult;\n}\n\n/**\n * Submit a `createExportJob` mutation to the workspace internal gateway.\n *\n * The caller is expected to map the returned `ExportJobResult` to its\n * own GraphQL output type (the per-svc `ExportJobResponse`).\n */\nexport async function triggerExportJob(params: TriggerExportJobParams): Promise<ExportJobResult> {\n const {\n serviceName,\n layer = 'wspace',\n actorId,\n actorType,\n workspaceId,\n name,\n entityTypes,\n format,\n includeMetadata,\n dateRangeStart,\n dateRangeEnd,\n } = params;\n\n const client = new GatewayClient({ layer, serviceName });\n\n // `CreateExportJobInput` carries no `workspaceId`: wspace-export-svc takes\n // the workspace from the `x-workspace-id` header so a caller can never\n // export another tenant's data. Sending the field makes GraphQL reject the\n // whole variable (\"Field \\\"workspaceId\\\" is not defined by type\n // \\\"CreateExportJobInput\\\"\"), so the workspace travels in the header only.\n const input = {\n name,\n entityTypes,\n format,\n ...(includeMetadata !== undefined ? { includeMetadata } : {}),\n ...(dateRangeStart !== undefined ? { dateRangeStart } : {}),\n ...(dateRangeEnd !== undefined ? { dateRangeEnd } : {}),\n };\n\n const response = await client.internalQuery<CreateExportJobResponse>({\n query: CREATE_EXPORT_JOB_MUTATION,\n variables: { input },\n headers: {\n 'x-actor-id': actorId,\n 'x-actor-type': actorType,\n 'x-workspace-id': workspaceId,\n },\n });\n\n const job = response.data?.createExportJob;\n if (!job) {\n throw new Error('Export service did not return a job');\n }\n return job;\n}\n","/**\n * Export Module\n *\n * Provides common utilities for data export operations across all Burdenoff microservices.\n * Includes pagination services, base exporter classes, CSV utilities, and type definitions.\n *\n * @module export\n *\n * @example\n * ```typescript\n * // Import from the export module\n * import {\n * BaseModuleExporter,\n * PaginationService,\n * convertToCSV,\n * } from '@burdenoff/be-sdk/export';\n *\n * // Create a custom exporter\n * class UserExporter extends BaseModuleExporter<User> {\n * moduleKey = 'users';\n * displayName = 'Users';\n *\n * async export(options: ExportOptions): Promise<ExportResult> {\n * const data = await this.fetchAll(\n * (cursor) => db.user.findMany({\n * where: cursor ? { id: { gt: cursor } } : {},\n * take: 100,\n * })\n * );\n *\n * const csv = convertToCSV(data);\n * return { data, format: 'csv' };\n * }\n * }\n *\n * // Use pagination utilities\n * const result = PaginationService.paginate(items, { page: 1, pageSize: 20 });\n * ```\n */\n\n// ============================================================================\n// Type Exports\n// ============================================================================\n\nexport type {\n // Export format types\n ExportFormat,\n ExportFormatEnum,\n\n // Configuration types\n ExportConfig,\n ExportOptions,\n\n // Job types\n ExportJobStatus,\n ExportJob,\n ExportProgress,\n ExportResult,\n\n // Fetch types\n ExportFetchOptions,\n ExportFetchResult,\n\n // Pagination types\n PaginationParams,\n PaginatedResult,\n PaginatedQueryOptions,\n PaginateResult,\n PaginateQueryFn,\n\n // Module interface\n ExportableModule,\n\n // CSV types\n CSVConversionOptions,\n} from './types.js';\n\n// ============================================================================\n// Class Exports\n// ============================================================================\n\nexport { BaseModuleExporter } from './base-exporter.js';\nexport { PaginationService } from './pagination.js';\n\n// ============================================================================\n// Function Exports\n// ============================================================================\n\nexport { convertToCSV, parseCSV, csvToJSON, getCSVHeaders, estimateCSVSize } from './csv.js';\n\n// ============================================================================\n// Gateway Helper Exports\n// ============================================================================\n\nexport { triggerExportJob } from './gateway-client.js';\nexport type { TriggerExportJobParams, ExportJobResult, ExportActorType, ExportFormatGql } from './gateway-client.js';\n"],"mappings":";;;;;;;;;;;;;;;AAoCA,IAAsB,qBAAtB,MAAsD;;CAEpD;;CAGA;;CAGA;;CAGA;;CAGA;;CAGA,AAAU;;;;;;;;;;;;;;;;;CA6BV,AAAU,aAAa,QAAqC,eAAmD;EAC7G,MAAM,kBAAkB,iBAAiB,KAAK,wBAAwB,CAAC;EAEvE,IAAI,gBAAgB,WAAW,GAC7B,OAAO;EAGT,MAAM,WAAoC,CAAC;EAC3C,MAAM,SAAS;EAEf,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,MAAM,GAC9C,IAAI,CAAC,gBAAgB,SAAS,GAAG,GAC/B,SAAS,OAAO;EAIpB,OAAO;CACT;;;;;;;;CASA,AAAU,iBACR,UACA,eAC2B;EAC3B,OAAO,SAAS,KAAK,WAAW,KAAK,aAAa,QAAQ,aAAa,CAAC;CAC1E;;;;;;;;;;;;;;;;;;;;;;;;CAyBA,MAAgB,SACd,SACA,OAAe,GACf,WAAmB,KACS;EAC5B,MAAM,QAAQ,OAAO,KAAK;EAG1B,MAAM,EAAE,OAAO,UAAU,MAAM,QAAQ;GAAE;GAAM;EAAK,CAAC;EAErD,OAAO;GACL,MAAM;GACN;GACA,SAAS,OAAO,MAAM,SAAS;GAC/B,YAAY,MAAM,SAAS,KAAK,OAAO,MAAM,SAAS,QAAQ,OAAO,OAAO,CAAC,IAAI;EACnF;CACF;;;;;;;;;;;;;;;;;;;;;;CAuBA,MAAgB,SACd,YACA,YAAoB,KACN;EACd,MAAM,WAAgB,CAAC;EACvB,IAAI;EAEJ,OAAO,MAAM;GACX,MAAM,QAAQ,MAAM,WAAW,MAAM;GA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;CACF,CAAC,EAEmB,CAAC,MAAM;CAC3B,IAAI,CAAC,KACH,MAAM,IAAI,MAAM,qCAAqC;CAEvD,OAAO;AACT"}
@@ -1,4 +1,4 @@
1
- import { n as createOperationsFlagGatePlugin, r as FeatureFlagProvider } from "../feature-flags-71oDkrUe.js";
1
+ import { n as createOperationsFlagGatePlugin, r as FeatureFlagProvider } from "../feature-flags-CP1KRgwD.js";
2
2
 
3
3
  export { FeatureFlagProvider, createOperationsFlagGatePlugin };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,5 +1,5 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-ad2WFvuA.js";
2
- import { t as ContextManager } from "./context-CZnXf2yb.js";
2
+ import { ContextManager } from "./context/index.js";
3
3
  import { t as signServiceJwt } from "./service-jwt-Bu-WNA_-.js";
4
4
  import { a as logger } from "./logger-B6rCpb7D.js";
5
5
  import { GraphQLError, Kind } from "graphql";
@@ -419,4 +419,4 @@ var feature_flags_exports = /* @__PURE__ */ __exportAll({
419
419
  });
420
420
 
421
421
  export { createOperationsFlagGatePlugin as n, FeatureFlagProvider as r, feature_flags_exports as t };
422
- //# sourceMappingURL=feature-flags-71oDkrUe.js.map
422
+ //# sourceMappingURL=feature-flags-CP1KRgwD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"feature-flags-71oDkrUe.js","names":[],"sources":["../src/feature-flags/provider.ts","../src/feature-flags/operations-flag-gate.ts","../src/feature-flags/index.ts"],"sourcesContent":["/**\n * Burdenoff Feature Flags Server Provider\n *\n * Server-side feature flag provider for backend services.\n * Evaluates flags via the global-tenant-svc GraphQL API through the internal gateway.\n * Supports in-memory caching with configurable TTL.\n *\n * @module feature-flags/provider\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * const isEnabled = await provider.resolveBoolean('calendar.recurring-events', false, {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n *\n * console.log(isEnabled.value); // true or false\n * console.log(isEnabled.reason); // 'TARGETING_MATCH', 'DEFAULT', etc.\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\nimport type { EvaluationContext, FeatureFlagProviderConfig, FlagEvaluation, ResolutionDetails } from './types.js';\n\ninterface CacheEntry {\n evaluations: Map<string, FlagEvaluation>;\n expiresAt: number;\n}\n\nconst EVALUATE_QUERY = `\n query EvaluateFeatureFlags($input: EvaluateFeatureFlagsInput!) {\n evaluateFeatureFlags(input: $input) {\n evaluations {\n key\n value\n variant\n reason\n flagType\n errorCode\n }\n }\n }\n`;\n\n/**\n * Burdenoff Feature Flag Server Provider\n *\n * Evaluates feature flags by querying the global-tenant-svc through\n * the internal gateway. Results are cached in-memory per workspace+actor\n * combination with a configurable TTL.\n */\nfunction readPositiveIntEnv(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nexport class FeatureFlagProvider {\n private readonly gatewayUrl: string;\n private readonly cacheTtlMs: number;\n private readonly failureTtlMs: number;\n private readonly requestTimeoutMs: number;\n private readonly serviceToken?: string;\n private readonly serviceName: string;\n private readonly defaultActorType: string;\n\n /** In-memory cache keyed by `${workspaceId}:${actorId}` */\n private readonly cache = new Map<string, CacheEntry>();\n\n constructor(config: FeatureFlagProviderConfig) {\n this.gatewayUrl = config.gatewayUrl;\n this.cacheTtlMs = (config.cacheTtlSeconds ?? 60) * 1000;\n // Hard per-request ceiling. Without it an unreachable gateway (NSG\n // silent-drop on the cross-environment path) left the fetch hanging for\n // the kernel's ~130s TCP connect timeout — stalling every flag-gated\n // request, and killing services that await a flag at BOOT (their ACA\n // startup probe expired → ActivationFailed).\n this.requestTimeoutMs = config.requestTimeoutMs ?? readPositiveIntEnv('FEATURE_FLAG_REQUEST_TIMEOUT_MS', 3000);\n // Negative cache so a broken gateway costs at most one timeout per\n // window instead of one per evaluation.\n this.failureTtlMs = (config.failureTtlSeconds ?? readPositiveIntEnv('FEATURE_FLAG_FAILURE_TTL_SECONDS', 15)) * 1000;\n this.serviceToken = config.serviceToken;\n this.serviceName = config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk';\n this.defaultActorType = config.defaultActorType ?? 'service';\n }\n\n // =========================================================================\n // Public Resolution Methods (OpenFeature-compatible interface)\n // =========================================================================\n\n /**\n * Resolve a boolean feature flag\n *\n * @param flagKey - The flag key (e.g. \"calendar.recurring-events\")\n * @param defaultValue - Default value if resolution fails\n * @param context - Evaluation context with actor and workspace info\n * @returns Resolution details with the resolved boolean value\n */\n async resolveBoolean(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext\n ): Promise<ResolutionDetails<boolean>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'BOOLEAN',\n };\n }\n\n return {\n value: Boolean(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a string feature flag\n */\n async resolveString(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext\n ): Promise<ResolutionDetails<string>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'STRING',\n };\n }\n\n return {\n value: String(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a number feature flag\n */\n async resolveNumber(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext\n ): Promise<ResolutionDetails<number>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'NUMBER',\n };\n }\n\n return {\n value: Number(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve an object (JSON) feature flag\n */\n async resolveObject<T extends Record<string, unknown>>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext\n ): Promise<ResolutionDetails<T>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'JSON',\n };\n }\n\n return {\n value: evaluation.value as T,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n // =========================================================================\n // Convenience Methods\n // =========================================================================\n\n /**\n * Quick boolean check — returns just the value.\n * Defaults to `true` (default-allow philosophy) if the flag is not found.\n *\n * @example\n * ```typescript\n * if (await provider.isEnabled('calendar.recurring-events', ctx)) {\n * // Feature is enabled\n * }\n * ```\n */\n async isEnabled(flagKey: string, context?: EvaluationContext): Promise<boolean> {\n const result = await this.resolveBoolean(\n flagKey,\n true,\n context ?? { workspaceId: 'system', actorType: 'service', actorId: 'boot' }\n );\n return result.value;\n }\n\n /**\n * Bulk evaluate multiple flags at once.\n * Returns a map of key -> ResolutionDetails.\n */\n async evaluateAll(context: EvaluationContext, keys?: string[]): Promise<Map<string, ResolutionDetails<unknown>>> {\n const evaluations = await this.fetchEvaluations(context, keys);\n const result = new Map<string, ResolutionDetails<unknown>>();\n\n for (const [key, evaluation] of evaluations) {\n result.set(key, {\n value: evaluation.value,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n });\n }\n\n return result;\n }\n\n /**\n * Invalidate the cache for a specific workspace+actor combination,\n * or all cache entries if no context is provided.\n */\n invalidateCache(context?: EvaluationContext): void {\n if (context) {\n const cacheKey = this.buildCacheKey(context);\n this.cache.delete(cacheKey);\n } else {\n this.cache.clear();\n }\n }\n\n // =========================================================================\n // Private Methods\n // =========================================================================\n\n /**\n * Get a single flag evaluation, fetching from cache or API\n */\n private async getEvaluation(flagKey: string, context: EvaluationContext | undefined): Promise<FlagEvaluation | null> {\n try {\n const evaluations = await this.fetchEvaluations(context);\n return evaluations.get(flagKey) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch flag evaluations — uses cache if available, otherwise calls the API\n */\n private async fetchEvaluations(\n context: EvaluationContext | undefined,\n keys?: string[]\n ): Promise<Map<string, FlagEvaluation>> {\n const cacheKey = this.buildCacheKey(context);\n const cached = this.cache.get(cacheKey);\n\n if (cached && cached.expiresAt > Date.now()) {\n return cached.evaluations;\n }\n\n // Without a workspace context there's nothing the backend can evaluate\n // against — fall through to caller defaults instead of hitting the API.\n if (!context?.workspaceId) {\n return new Map();\n }\n\n // Cross-layer flag evaluation transits the global PUBLIC gateway, which\n // strips raw actor headers unless the request carries a valid JWT. Use an\n // explicit serviceToken if provided, otherwise mint a short-lived `service`\n // actor JWT (no-op when SERVICE_JWT_SECRET is unset → falls back to header\n // context for same-env/internal-gateway evaluation).\n const bearerToken = this.serviceToken ?? (await signServiceJwt(this.serviceName)) ?? undefined;\n\n // Fetch from API\n try {\n const response = await fetch(this.gatewayUrl, {\n method: 'POST',\n // Bounded: an unreachable gateway must cost milliseconds-to-seconds,\n // never the kernel's TCP connect timeout. On abort the catch below\n // negative-caches and callers fall back to their defaults.\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n headers: {\n 'Content-Type': 'application/json',\n ...(context.actorId && { 'x-actor-id': context.actorId }),\n 'x-actor-type': context.actorType ?? this.defaultActorType,\n 'x-workspace-id': context.workspaceId,\n ...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),\n // Re-present the inbound CF Access service token when the flag check\n // runs against a CF-Access-gated public gateway (alpha). No-op when\n // request context carries no CF creds (local dev, production).\n ...ContextManager.getCfAccessHeaders(),\n },\n body: JSON.stringify({\n query: EVALUATE_QUERY,\n variables: {\n input: {\n workspaceId: context.workspaceId,\n keys: keys ?? null,\n },\n },\n }),\n });\n\n if (!response.ok) {\n // Return empty map on error — default-allow handled by callers\n return this.rememberFailure(cacheKey);\n }\n\n const json = (await response.json()) as {\n data?: {\n evaluateFeatureFlags?: {\n evaluations?: FlagEvaluation[];\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (json.errors || !json.data?.evaluateFeatureFlags?.evaluations) {\n return this.rememberFailure(cacheKey);\n }\n\n const evaluations = new Map<string, FlagEvaluation>();\n for (const evaluation of json.data.evaluateFeatureFlags.evaluations) {\n evaluations.set(evaluation.key, evaluation);\n }\n\n // Cache the results\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.cacheTtlMs,\n });\n\n return evaluations;\n } catch {\n // On network error/timeout, return empty map (default-allow handled by\n // callers) and negative-cache so the next evaluations in the window\n // skip the doomed request entirely.\n return this.rememberFailure(cacheKey);\n }\n }\n\n /**\n * Negative-cache a failed fetch: remember an empty evaluation set for\n * `failureTtlMs` so a broken/unreachable gateway costs at most one request\n * timeout per window instead of one per flag evaluation.\n */\n private rememberFailure(cacheKey: string): Map<string, FlagEvaluation> {\n const evaluations = new Map<string, FlagEvaluation>();\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.failureTtlMs,\n });\n return evaluations;\n }\n\n /**\n * Build a cache key from the evaluation context.\n *\n * Safe against undefined/null context — callers like isEnabled() may\n * pass no context during service boot (e.g. checking a default-allow\n * feature flag at startup before the first request builds a real\n * actor context). Without the guard, isEnabled(flag) used to throw\n * \"undefined is not an object (evaluating 'context.workspaceId')\"\n * and crash the svc at startServer().\n */\n private buildCacheKey(context: EvaluationContext | undefined): string {\n const ctx = context ?? ({} as EvaluationContext);\n return `${ctx.workspaceId ?? 'system'}:${ctx.actorId ?? 'anonymous'}:${ctx.actorType ?? 'user'}`;\n }\n}\n","/**\n * Operations Feature-Flag Gate Plugin\n *\n * GraphQL-Yoga/envelop plugin factory that short-circuits GraphQL operations\n * when a product's operations feature flag is OFF, returning a clean typed\n * `FEATURE_DISABLED` (HTTP 403) error before any resolver runs.\n *\n * This is the shared, fleet-wide replacement for the per-service inline\n * `operations-feature-flag` / `feature-flag-gate` plugins (movethewheels,\n * manufacturedops, …). By default it gates MUTATIONS only; queries and\n * subscriptions pass through.\n *\n * Default-allow philosophy (matches {@link FeatureFlagProvider.isEnabled}): if\n * there is no workspace context, or the flag service is unreachable / the flag\n * is unknown, the operation is ALLOWED. A flag must be explicitly disabled for\n * the workspace to block traffic.\n *\n * @module feature-flags/operations-flag-gate\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { createOperationsFlagGatePlugin } from '@burdenoff/be-sdk/feature-flags';\n *\n * yogaPlugins: [\n * createOperationsFlagGatePlugin({\n * flagKey: 'movethewheels.operations',\n * productId: 'movethewheels',\n * }),\n * useGraphQLModules(application),\n * ];\n * ```\n */\n\nimport { type DocumentNode, GraphQLError, Kind, type OperationDefinitionNode } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { YogaPlugin } from '../server/index.js';\nimport { FeatureFlagProvider } from './provider.js';\nimport type { EvaluationContext } from './types.js';\n\n/** GraphQL operation types that a gate can be configured to short-circuit. */\nexport type GatedOperationType = 'query' | 'mutation' | 'subscription';\n\nexport interface OperationsFlagGatePluginOptions {\n /** Feature flag key that gates the operations (e.g. `'movethewheels.operations'`). */\n flagKey: string;\n /** Product identifier this gate protects. Surfaced in the error extensions + logs. */\n productId: string;\n /**\n * Provider used to evaluate the flag. When omitted, a {@link FeatureFlagProvider}\n * is lazily built from `gatewayUrl` (or `GLOBAL_PUBLIC_GATEWAY_URL` /\n * `GLOBAL_INT_GATEWAY_URL`).\n */\n provider?: FeatureFlagProvider;\n /** Gateway URL for the lazily-built default provider. Ignored when `provider` is set. */\n gatewayUrl?: string;\n /** Cache TTL (seconds) for the lazily-built default provider. Default: 60. */\n cacheTtlSeconds?: number;\n /** Which operation types to gate. Default: `['mutation']`. */\n gatedOperations?: readonly GatedOperationType[];\n /** Override the user-facing error message shown when the flag is disabled. */\n userMessage?: string;\n}\n\n/** Actor/workspace fields the gate reads off the GraphQL context (either shape). */\ninterface GateContextShape {\n workspace?: { id?: string | null } | null;\n actor?: { id?: string | null; type?: string | null } | null;\n workspaceId?: string | null;\n actorId?: string | null;\n actorType?: string | null;\n}\n\nconst ACTOR_TYPES: readonly string[] = ['user', 'app', 'service', 'super_admin'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isDocumentNode(value: unknown): value is DocumentNode {\n return isRecord(value) && Array.isArray((value as { definitions?: unknown }).definitions);\n}\n\n/** Find the operation that will actually execute for this request. */\nfunction findExecutedOperation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | null {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n\n if (operationName) {\n return operations.find((operation) => operation.name?.value === operationName) ?? null;\n }\n // Unnamed / single-operation request executes the first (only) operation.\n return operations[0] ?? null;\n}\n\nfunction coerceActorType(value: string | null | undefined): EvaluationContext['actorType'] {\n // Cast is sound: only reached after `ACTOR_TYPES.includes(value)` proves the\n // string is one of the known actor-type literals.\n return value && ACTOR_TYPES.includes(value) ? (value as EvaluationContext['actorType']) : undefined;\n}\n\n/**\n * Build the flag {@link EvaluationContext} from the GraphQL context, tolerating\n * both the nested (`workspace.id` / `actor.id`) and flat (`workspaceId` /\n * `actorId`) shapes. Returns `null` when no workspace can be resolved.\n */\nfunction resolveEvaluationContext(contextValue: unknown): EvaluationContext | null {\n // Cast to the fully-optional GateContextShape after the record guard; every\n // field is read defensively with optional chaining below.\n const ctx = (isRecord(contextValue) ? contextValue : {}) as GateContextShape;\n const workspaceId = ctx.workspace?.id ?? ctx.workspaceId ?? undefined;\n if (!workspaceId) {\n return null;\n }\n const actorId = ctx.actor?.id ?? ctx.actorId ?? undefined;\n const actorType = coerceActorType(ctx.actor?.type ?? ctx.actorType);\n return {\n workspaceId,\n ...(actorId ? { actorId } : {}),\n ...(actorType ? { actorType } : {}),\n };\n}\n\n/**\n * Create a GraphQL-Yoga/envelop plugin that gates operations behind a product\n * feature flag. Returns a {@link YogaPlugin} ready to drop into a service's\n * `yogaPlugins` array.\n */\nexport function createOperationsFlagGatePlugin(options: OperationsFlagGatePluginOptions): YogaPlugin {\n const { flagKey, productId } = options;\n const gatedOperations = new Set<string>(options.gatedOperations ?? ['mutation']);\n const userMessage = options.userMessage ?? 'This operation is currently unavailable.';\n\n let provider = options.provider ?? null;\n const getProvider = (): FeatureFlagProvider => {\n if (!provider) {\n provider = new FeatureFlagProvider({\n gatewayUrl:\n options.gatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL'] ?? process.env['GLOBAL_INT_GATEWAY_URL'] ?? '',\n cacheTtlSeconds: options.cacheTtlSeconds ?? 60,\n defaultActorType: 'service',\n });\n }\n return provider;\n };\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }): Promise<void> {\n if (!isDocumentNode(args.document)) {\n return;\n }\n\n const operation = findExecutedOperation(args.document, args.operationName);\n if (!operation || !gatedOperations.has(operation.operation)) {\n return; // Not a gated operation type — allow.\n }\n\n const evaluationContext = resolveEvaluationContext(args.contextValue);\n if (!evaluationContext) {\n // No workspace context to evaluate against → default-allow.\n logger.warn('[OperationsFlagGate] no workspace context — allowing operation', { flagKey, productId });\n return;\n }\n\n let enabled = true;\n try {\n enabled = await getProvider().isEnabled(flagKey, evaluationContext);\n } catch (error) {\n // Never let a flag-service failure block traffic (default-allow).\n logger.warn('[OperationsFlagGate] flag evaluation failed — allowing operation', {\n flagKey,\n productId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n if (!enabled) {\n logger.warn('[OperationsFlagGate] flag disabled — blocking operation', {\n flagKey,\n productId,\n workspaceId: evaluationContext.workspaceId,\n });\n throw new GraphQLError(userMessage, {\n extensions: {\n code: 'FEATURE_DISABLED',\n flagKey,\n productId,\n http: { status: 403 },\n },\n });\n }\n },\n };\n}\n","/**\n * Feature Flags Module\n *\n * In-house feature flag evaluation for Burdenoff backend services.\n * Compatible with OpenFeature specification concepts.\n *\n * @module feature-flags\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * // Create provider (typically done once at service startup)\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: process.env.GLOBAL_INT_GATEWAY_URL || 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * // Check a boolean flag\n * const ctx = { actorId: 'user-123', actorType: 'user' as const, workspaceId: 'ws-456' };\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', ctx);\n *\n * // Resolve with full details\n * const details = await provider.resolveBoolean('calendar.recurring-events', true, ctx);\n * console.log(details.value); // true\n * console.log(details.reason); // 'TARGETING_MATCH'\n * console.log(details.variant); // 'user-opted-in'\n * ```\n */\n\nexport { FeatureFlagProvider } from './provider.js';\nexport type {\n EvaluationContext,\n FeatureFlagProviderConfig,\n FlagEvaluation,\n FlagType,\n ResolutionDetails,\n} from './types.js';\n\nexport { createOperationsFlagGatePlugin } from './operations-flag-gate.js';\nexport type { OperationsFlagGatePluginOptions, GatedOperationType } from './operations-flag-gate.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;AAsBvB,SAAS,mBAAmB,MAAc,UAA0B;CAClE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,SAAS,SAAS,KAAK,EAAE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provider.ts","../src/feature-flags/operations-flag-gate.ts","../src/feature-flags/index.ts"],"sourcesContent":["/**\n * Burdenoff Feature Flags Server Provider\n *\n * Server-side feature flag provider for backend services.\n * Evaluates flags via the global-tenant-svc GraphQL API through the internal gateway.\n * Supports in-memory caching with configurable TTL.\n *\n * @module feature-flags/provider\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * const isEnabled = await provider.resolveBoolean('calendar.recurring-events', false, {\n * actorId: 'user-123',\n * actorType: 'user',\n * workspaceId: 'ws-456',\n * });\n *\n * console.log(isEnabled.value); // true or false\n * console.log(isEnabled.reason); // 'TARGETING_MATCH', 'DEFAULT', etc.\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\nimport type { EvaluationContext, FeatureFlagProviderConfig, FlagEvaluation, ResolutionDetails } from './types.js';\n\ninterface CacheEntry {\n evaluations: Map<string, FlagEvaluation>;\n expiresAt: number;\n}\n\nconst EVALUATE_QUERY = `\n query EvaluateFeatureFlags($input: EvaluateFeatureFlagsInput!) {\n evaluateFeatureFlags(input: $input) {\n evaluations {\n key\n value\n variant\n reason\n flagType\n errorCode\n }\n }\n }\n`;\n\n/**\n * Burdenoff Feature Flag Server Provider\n *\n * Evaluates feature flags by querying the global-tenant-svc through\n * the internal gateway. Results are cached in-memory per workspace+actor\n * combination with a configurable TTL.\n */\nfunction readPositiveIntEnv(name: string, fallback: number): number {\n const raw = process.env[name];\n if (!raw) return fallback;\n const parsed = parseInt(raw, 10);\n return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;\n}\n\nexport class FeatureFlagProvider {\n private readonly gatewayUrl: string;\n private readonly cacheTtlMs: number;\n private readonly failureTtlMs: number;\n private readonly requestTimeoutMs: number;\n private readonly serviceToken?: string;\n private readonly serviceName: string;\n private readonly defaultActorType: string;\n\n /** In-memory cache keyed by `${workspaceId}:${actorId}` */\n private readonly cache = new Map<string, CacheEntry>();\n\n constructor(config: FeatureFlagProviderConfig) {\n this.gatewayUrl = config.gatewayUrl;\n this.cacheTtlMs = (config.cacheTtlSeconds ?? 60) * 1000;\n // Hard per-request ceiling. Without it an unreachable gateway (NSG\n // silent-drop on the cross-environment path) left the fetch hanging for\n // the kernel's ~130s TCP connect timeout — stalling every flag-gated\n // request, and killing services that await a flag at BOOT (their ACA\n // startup probe expired → ActivationFailed).\n this.requestTimeoutMs = config.requestTimeoutMs ?? readPositiveIntEnv('FEATURE_FLAG_REQUEST_TIMEOUT_MS', 3000);\n // Negative cache so a broken gateway costs at most one timeout per\n // window instead of one per evaluation.\n this.failureTtlMs = (config.failureTtlSeconds ?? readPositiveIntEnv('FEATURE_FLAG_FAILURE_TTL_SECONDS', 15)) * 1000;\n this.serviceToken = config.serviceToken;\n this.serviceName = config.serviceName ?? process.env['SERVICE_NAME'] ?? 'burdenoff-be-sdk';\n this.defaultActorType = config.defaultActorType ?? 'service';\n }\n\n // =========================================================================\n // Public Resolution Methods (OpenFeature-compatible interface)\n // =========================================================================\n\n /**\n * Resolve a boolean feature flag\n *\n * @param flagKey - The flag key (e.g. \"calendar.recurring-events\")\n * @param defaultValue - Default value if resolution fails\n * @param context - Evaluation context with actor and workspace info\n * @returns Resolution details with the resolved boolean value\n */\n async resolveBoolean(\n flagKey: string,\n defaultValue: boolean,\n context: EvaluationContext\n ): Promise<ResolutionDetails<boolean>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'BOOLEAN',\n };\n }\n\n return {\n value: Boolean(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a string feature flag\n */\n async resolveString(\n flagKey: string,\n defaultValue: string,\n context: EvaluationContext\n ): Promise<ResolutionDetails<string>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'STRING',\n };\n }\n\n return {\n value: String(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve a number feature flag\n */\n async resolveNumber(\n flagKey: string,\n defaultValue: number,\n context: EvaluationContext\n ): Promise<ResolutionDetails<number>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'NUMBER',\n };\n }\n\n return {\n value: Number(evaluation.value),\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n /**\n * Resolve an object (JSON) feature flag\n */\n async resolveObject<T extends Record<string, unknown>>(\n flagKey: string,\n defaultValue: T,\n context: EvaluationContext\n ): Promise<ResolutionDetails<T>> {\n const evaluation = await this.getEvaluation(flagKey, context);\n if (!evaluation) {\n return {\n value: defaultValue,\n reason: 'DEFAULT',\n flagType: 'JSON',\n };\n }\n\n return {\n value: evaluation.value as T,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n };\n }\n\n // =========================================================================\n // Convenience Methods\n // =========================================================================\n\n /**\n * Quick boolean check — returns just the value.\n * Defaults to `true` (default-allow philosophy) if the flag is not found.\n *\n * @example\n * ```typescript\n * if (await provider.isEnabled('calendar.recurring-events', ctx)) {\n * // Feature is enabled\n * }\n * ```\n */\n async isEnabled(flagKey: string, context?: EvaluationContext): Promise<boolean> {\n const result = await this.resolveBoolean(\n flagKey,\n true,\n context ?? { workspaceId: 'system', actorType: 'service', actorId: 'boot' }\n );\n return result.value;\n }\n\n /**\n * Bulk evaluate multiple flags at once.\n * Returns a map of key -> ResolutionDetails.\n */\n async evaluateAll(context: EvaluationContext, keys?: string[]): Promise<Map<string, ResolutionDetails<unknown>>> {\n const evaluations = await this.fetchEvaluations(context, keys);\n const result = new Map<string, ResolutionDetails<unknown>>();\n\n for (const [key, evaluation] of evaluations) {\n result.set(key, {\n value: evaluation.value,\n variant: evaluation.variant ?? undefined,\n reason: evaluation.reason,\n flagType: evaluation.flagType,\n errorCode: evaluation.errorCode ?? undefined,\n });\n }\n\n return result;\n }\n\n /**\n * Invalidate the cache for a specific workspace+actor combination,\n * or all cache entries if no context is provided.\n */\n invalidateCache(context?: EvaluationContext): void {\n if (context) {\n const cacheKey = this.buildCacheKey(context);\n this.cache.delete(cacheKey);\n } else {\n this.cache.clear();\n }\n }\n\n // =========================================================================\n // Private Methods\n // =========================================================================\n\n /**\n * Get a single flag evaluation, fetching from cache or API\n */\n private async getEvaluation(flagKey: string, context: EvaluationContext | undefined): Promise<FlagEvaluation | null> {\n try {\n const evaluations = await this.fetchEvaluations(context);\n return evaluations.get(flagKey) ?? null;\n } catch {\n return null;\n }\n }\n\n /**\n * Fetch flag evaluations — uses cache if available, otherwise calls the API\n */\n private async fetchEvaluations(\n context: EvaluationContext | undefined,\n keys?: string[]\n ): Promise<Map<string, FlagEvaluation>> {\n const cacheKey = this.buildCacheKey(context);\n const cached = this.cache.get(cacheKey);\n\n if (cached && cached.expiresAt > Date.now()) {\n return cached.evaluations;\n }\n\n // Without a workspace context there's nothing the backend can evaluate\n // against — fall through to caller defaults instead of hitting the API.\n if (!context?.workspaceId) {\n return new Map();\n }\n\n // Cross-layer flag evaluation transits the global PUBLIC gateway, which\n // strips raw actor headers unless the request carries a valid JWT. Use an\n // explicit serviceToken if provided, otherwise mint a short-lived `service`\n // actor JWT (no-op when SERVICE_JWT_SECRET is unset → falls back to header\n // context for same-env/internal-gateway evaluation).\n const bearerToken = this.serviceToken ?? (await signServiceJwt(this.serviceName)) ?? undefined;\n\n // Fetch from API\n try {\n const response = await fetch(this.gatewayUrl, {\n method: 'POST',\n // Bounded: an unreachable gateway must cost milliseconds-to-seconds,\n // never the kernel's TCP connect timeout. On abort the catch below\n // negative-caches and callers fall back to their defaults.\n signal: AbortSignal.timeout(this.requestTimeoutMs),\n headers: {\n 'Content-Type': 'application/json',\n ...(context.actorId && { 'x-actor-id': context.actorId }),\n 'x-actor-type': context.actorType ?? this.defaultActorType,\n 'x-workspace-id': context.workspaceId,\n ...(bearerToken && { Authorization: `Bearer ${bearerToken}` }),\n // Re-present the inbound CF Access service token when the flag check\n // runs against a CF-Access-gated public gateway (alpha). No-op when\n // request context carries no CF creds (local dev, production).\n ...ContextManager.getCfAccessHeaders(),\n },\n body: JSON.stringify({\n query: EVALUATE_QUERY,\n variables: {\n input: {\n workspaceId: context.workspaceId,\n keys: keys ?? null,\n },\n },\n }),\n });\n\n if (!response.ok) {\n // Return empty map on error — default-allow handled by callers\n return this.rememberFailure(cacheKey);\n }\n\n const json = (await response.json()) as {\n data?: {\n evaluateFeatureFlags?: {\n evaluations?: FlagEvaluation[];\n };\n };\n errors?: Array<{ message: string }>;\n };\n\n if (json.errors || !json.data?.evaluateFeatureFlags?.evaluations) {\n return this.rememberFailure(cacheKey);\n }\n\n const evaluations = new Map<string, FlagEvaluation>();\n for (const evaluation of json.data.evaluateFeatureFlags.evaluations) {\n evaluations.set(evaluation.key, evaluation);\n }\n\n // Cache the results\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.cacheTtlMs,\n });\n\n return evaluations;\n } catch {\n // On network error/timeout, return empty map (default-allow handled by\n // callers) and negative-cache so the next evaluations in the window\n // skip the doomed request entirely.\n return this.rememberFailure(cacheKey);\n }\n }\n\n /**\n * Negative-cache a failed fetch: remember an empty evaluation set for\n * `failureTtlMs` so a broken/unreachable gateway costs at most one request\n * timeout per window instead of one per flag evaluation.\n */\n private rememberFailure(cacheKey: string): Map<string, FlagEvaluation> {\n const evaluations = new Map<string, FlagEvaluation>();\n this.cache.set(cacheKey, {\n evaluations,\n expiresAt: Date.now() + this.failureTtlMs,\n });\n return evaluations;\n }\n\n /**\n * Build a cache key from the evaluation context.\n *\n * Safe against undefined/null context — callers like isEnabled() may\n * pass no context during service boot (e.g. checking a default-allow\n * feature flag at startup before the first request builds a real\n * actor context). Without the guard, isEnabled(flag) used to throw\n * \"undefined is not an object (evaluating 'context.workspaceId')\"\n * and crash the svc at startServer().\n */\n private buildCacheKey(context: EvaluationContext | undefined): string {\n const ctx = context ?? ({} as EvaluationContext);\n return `${ctx.workspaceId ?? 'system'}:${ctx.actorId ?? 'anonymous'}:${ctx.actorType ?? 'user'}`;\n }\n}\n","/**\n * Operations Feature-Flag Gate Plugin\n *\n * GraphQL-Yoga/envelop plugin factory that short-circuits GraphQL operations\n * when a product's operations feature flag is OFF, returning a clean typed\n * `FEATURE_DISABLED` (HTTP 403) error before any resolver runs.\n *\n * This is the shared, fleet-wide replacement for the per-service inline\n * `operations-feature-flag` / `feature-flag-gate` plugins (movethewheels,\n * manufacturedops, …). By default it gates MUTATIONS only; queries and\n * subscriptions pass through.\n *\n * Default-allow philosophy (matches {@link FeatureFlagProvider.isEnabled}): if\n * there is no workspace context, or the flag service is unreachable / the flag\n * is unknown, the operation is ALLOWED. A flag must be explicitly disabled for\n * the workspace to block traffic.\n *\n * @module feature-flags/operations-flag-gate\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { createOperationsFlagGatePlugin } from '@burdenoff/be-sdk/feature-flags';\n *\n * yogaPlugins: [\n * createOperationsFlagGatePlugin({\n * flagKey: 'movethewheels.operations',\n * productId: 'movethewheels',\n * }),\n * useGraphQLModules(application),\n * ];\n * ```\n */\n\nimport { type DocumentNode, GraphQLError, Kind, type OperationDefinitionNode } from 'graphql';\n\nimport { logger } from '../logger/index.js';\nimport type { YogaPlugin } from '../server/index.js';\nimport { FeatureFlagProvider } from './provider.js';\nimport type { EvaluationContext } from './types.js';\n\n/** GraphQL operation types that a gate can be configured to short-circuit. */\nexport type GatedOperationType = 'query' | 'mutation' | 'subscription';\n\nexport interface OperationsFlagGatePluginOptions {\n /** Feature flag key that gates the operations (e.g. `'movethewheels.operations'`). */\n flagKey: string;\n /** Product identifier this gate protects. Surfaced in the error extensions + logs. */\n productId: string;\n /**\n * Provider used to evaluate the flag. When omitted, a {@link FeatureFlagProvider}\n * is lazily built from `gatewayUrl` (or `GLOBAL_PUBLIC_GATEWAY_URL` /\n * `GLOBAL_INT_GATEWAY_URL`).\n */\n provider?: FeatureFlagProvider;\n /** Gateway URL for the lazily-built default provider. Ignored when `provider` is set. */\n gatewayUrl?: string;\n /** Cache TTL (seconds) for the lazily-built default provider. Default: 60. */\n cacheTtlSeconds?: number;\n /** Which operation types to gate. Default: `['mutation']`. */\n gatedOperations?: readonly GatedOperationType[];\n /** Override the user-facing error message shown when the flag is disabled. */\n userMessage?: string;\n}\n\n/** Actor/workspace fields the gate reads off the GraphQL context (either shape). */\ninterface GateContextShape {\n workspace?: { id?: string | null } | null;\n actor?: { id?: string | null; type?: string | null } | null;\n workspaceId?: string | null;\n actorId?: string | null;\n actorType?: string | null;\n}\n\nconst ACTOR_TYPES: readonly string[] = ['user', 'app', 'service', 'super_admin'];\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null;\n}\n\nfunction isDocumentNode(value: unknown): value is DocumentNode {\n return isRecord(value) && Array.isArray((value as { definitions?: unknown }).definitions);\n}\n\n/** Find the operation that will actually execute for this request. */\nfunction findExecutedOperation(document: DocumentNode, operationName?: string | null): OperationDefinitionNode | null {\n const operations = document.definitions.filter(\n (definition): definition is OperationDefinitionNode => definition.kind === Kind.OPERATION_DEFINITION\n );\n\n if (operationName) {\n return operations.find((operation) => operation.name?.value === operationName) ?? null;\n }\n // Unnamed / single-operation request executes the first (only) operation.\n return operations[0] ?? null;\n}\n\nfunction coerceActorType(value: string | null | undefined): EvaluationContext['actorType'] {\n // Cast is sound: only reached after `ACTOR_TYPES.includes(value)` proves the\n // string is one of the known actor-type literals.\n return value && ACTOR_TYPES.includes(value) ? (value as EvaluationContext['actorType']) : undefined;\n}\n\n/**\n * Build the flag {@link EvaluationContext} from the GraphQL context, tolerating\n * both the nested (`workspace.id` / `actor.id`) and flat (`workspaceId` /\n * `actorId`) shapes. Returns `null` when no workspace can be resolved.\n */\nfunction resolveEvaluationContext(contextValue: unknown): EvaluationContext | null {\n // Cast to the fully-optional GateContextShape after the record guard; every\n // field is read defensively with optional chaining below.\n const ctx = (isRecord(contextValue) ? contextValue : {}) as GateContextShape;\n const workspaceId = ctx.workspace?.id ?? ctx.workspaceId ?? undefined;\n if (!workspaceId) {\n return null;\n }\n const actorId = ctx.actor?.id ?? ctx.actorId ?? undefined;\n const actorType = coerceActorType(ctx.actor?.type ?? ctx.actorType);\n return {\n workspaceId,\n ...(actorId ? { actorId } : {}),\n ...(actorType ? { actorType } : {}),\n };\n}\n\n/**\n * Create a GraphQL-Yoga/envelop plugin that gates operations behind a product\n * feature flag. Returns a {@link YogaPlugin} ready to drop into a service's\n * `yogaPlugins` array.\n */\nexport function createOperationsFlagGatePlugin(options: OperationsFlagGatePluginOptions): YogaPlugin {\n const { flagKey, productId } = options;\n const gatedOperations = new Set<string>(options.gatedOperations ?? ['mutation']);\n const userMessage = options.userMessage ?? 'This operation is currently unavailable.';\n\n let provider = options.provider ?? null;\n const getProvider = (): FeatureFlagProvider => {\n if (!provider) {\n provider = new FeatureFlagProvider({\n gatewayUrl:\n options.gatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL'] ?? process.env['GLOBAL_INT_GATEWAY_URL'] ?? '',\n cacheTtlSeconds: options.cacheTtlSeconds ?? 60,\n defaultActorType: 'service',\n });\n }\n return provider;\n };\n\n return {\n async onExecute({\n args,\n }: {\n args: {\n document?: unknown;\n operationName?: string | null;\n variableValues?: Record<string, unknown>;\n contextValue?: unknown;\n };\n }): Promise<void> {\n if (!isDocumentNode(args.document)) {\n return;\n }\n\n const operation = findExecutedOperation(args.document, args.operationName);\n if (!operation || !gatedOperations.has(operation.operation)) {\n return; // Not a gated operation type — allow.\n }\n\n const evaluationContext = resolveEvaluationContext(args.contextValue);\n if (!evaluationContext) {\n // No workspace context to evaluate against → default-allow.\n logger.warn('[OperationsFlagGate] no workspace context — allowing operation', { flagKey, productId });\n return;\n }\n\n let enabled = true;\n try {\n enabled = await getProvider().isEnabled(flagKey, evaluationContext);\n } catch (error) {\n // Never let a flag-service failure block traffic (default-allow).\n logger.warn('[OperationsFlagGate] flag evaluation failed — allowing operation', {\n flagKey,\n productId,\n error: error instanceof Error ? error.message : String(error),\n });\n return;\n }\n\n if (!enabled) {\n logger.warn('[OperationsFlagGate] flag disabled — blocking operation', {\n flagKey,\n productId,\n workspaceId: evaluationContext.workspaceId,\n });\n throw new GraphQLError(userMessage, {\n extensions: {\n code: 'FEATURE_DISABLED',\n flagKey,\n productId,\n http: { status: 403 },\n },\n });\n }\n },\n };\n}\n","/**\n * Feature Flags Module\n *\n * In-house feature flag evaluation for Burdenoff backend services.\n * Compatible with OpenFeature specification concepts.\n *\n * @module feature-flags\n * @category FeatureFlags\n *\n * @example\n * ```typescript\n * import { FeatureFlagProvider } from '@burdenoff/be-sdk/feature-flags';\n *\n * // Create provider (typically done once at service startup)\n * const provider = new FeatureFlagProvider({\n * gatewayUrl: process.env.GLOBAL_INT_GATEWAY_URL || 'http://global-int-gateway:4000/global/graphql',\n * cacheTtlSeconds: 60,\n * });\n *\n * // Check a boolean flag\n * const ctx = { actorId: 'user-123', actorType: 'user' as const, workspaceId: 'ws-456' };\n * const isEnabled = await provider.isEnabled('calendar.recurring-events', ctx);\n *\n * // Resolve with full details\n * const details = await provider.resolveBoolean('calendar.recurring-events', true, ctx);\n * console.log(details.value); // true\n * console.log(details.reason); // 'TARGETING_MATCH'\n * console.log(details.variant); // 'user-opted-in'\n * ```\n */\n\nexport { FeatureFlagProvider } from './provider.js';\nexport type {\n EvaluationContext,\n FeatureFlagProviderConfig,\n FlagEvaluation,\n FlagType,\n ResolutionDetails,\n} from './types.js';\n\nexport { createOperationsFlagGatePlugin } from './operations-flag-gate.js';\nexport type { OperationsFlagGatePluginOptions, GatedOperationType } from './operations-flag-gate.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,MAAM,iBAAiB;;;;;;;;;;;;;;;;;;;;;AAsBvB,SAAS,mBAAmB,MAAc,UAA0B;CAClE,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,SAAS,SAAS,KAAK,EAAE;CAC/B,OAAO,OAAO,SAAS,MAAM,KAAK,SAAS,IAAI,SAAS;AAC1D;AAEA,IAAa,sBAAb,MAAiC;CAC/B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CACjB,AAAiB;;CAGjB,AAAiB,wBAAQ,IAAI,IAAwB;CAErD,YAAY,QAAmC;EAC7C,KAAK,aAAa,OAAO;EACzB,KAAK,cAAc,OAAO,mBAAmB,MAAM;EAMnD,KAAK,mBAAmB,OAAO,oBAAoB,mBAAmB,mCAAmC,GAAI;EAG7G,KAAK,gBAAgB,OAAO,qBAAqB,mBAAmB,oCAAoC,EAAE,KAAK;EAC/G,KAAK,eAAe,OAAO;EAC3B,KAAK,cAAc,OAAO,eAAe,QAAQ,IAAI,mBAAmB;EACxE,KAAK,mBAAmB,OAAO,oBAAoB;CACrD;;;;;;;;;CAcA,MAAM,eACJ,SACA,cACA,SACqC;EACrC,MAAM,aAAa,MAAM,KAAK,cAAc,SAAS,OAAO;EAC5D,IAAI,CAAC,YACH,OAAO;GACL,OAAO;GACP,QAAQ;GACR,UAAU;EACZ;EAGF,OAAO;GACL,OAAO,QAAQ,WAAW,KAAK;GAC/B,SAAS,WAAW,WAAW;GAC/B,QAAQ,WAAW;GACnB,UAAU,WAAW;GACrB,WAAW,WAAW,aAAa;EACrC;CACF;;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KAAK,oEAAoE;IAC9E;IACA;IACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;GAC9D,CAAC;GACD;EACF;EAEA,IAAI,CAAC,SAAS;GACZ,OAAO,KAAK,2DAA2D;IACrE;IACA;IACA,aAAa,kBAAkB;GACjC,CAAC;GACD,MAAM,IAAI,aAAa,aAAa,EAClC,YAAY;IACV,MAAM;IACN;IACA;IACA,MAAM,EAAE,QAAQ,IAAI;GACtB,EACF,CAAC;EACH;CACF,EACF;AACF"}
@@ -1,4 +1,4 @@
1
- import { _ as FILE_VISIBILITIES, a as FilesClient, c as clampDownloadUrlTtl, d as FILES_CLIENT_GRAPHQL_CODES, f as FilesClientError, g as FILE_ACTOR_TYPES, h as toFilesClientError, i as toFileReference, l as fileExtensionOf, m as isFilesClientError, n as FILE_REFERENCE_KIND, o as MAX_DOWNLOAD_URL_TTL_SECONDS, p as classifyFilesErrors, r as isFileReference, s as MIN_DOWNLOAD_URL_TTL_SECONDS, u as mapFileMetadata } from "../files-DjH0099H.js";
1
+ import { _ as FILE_VISIBILITIES, a as FilesClient, c as clampDownloadUrlTtl, d as FILES_CLIENT_GRAPHQL_CODES, f as FilesClientError, g as FILE_ACTOR_TYPES, h as toFilesClientError, i as toFileReference, l as fileExtensionOf, m as isFilesClientError, n as FILE_REFERENCE_KIND, o as MAX_DOWNLOAD_URL_TTL_SECONDS, p as classifyFilesErrors, r as isFileReference, s as MIN_DOWNLOAD_URL_TTL_SECONDS, u as mapFileMetadata } from "../files-h5U-D2AF.js";
2
2
 
3
3
  export { FILES_CLIENT_GRAPHQL_CODES, FILE_ACTOR_TYPES, FILE_REFERENCE_KIND, FILE_VISIBILITIES, FilesClient, FilesClientError, MAX_DOWNLOAD_URL_TTL_SECONDS, MIN_DOWNLOAD_URL_TTL_SECONDS, clampDownloadUrlTtl, classifyFilesErrors, fileExtensionOf, isFileReference, isFilesClientError, mapFileMetadata, toFileReference, toFilesClientError };
4
4
  //# sourceMappingURL=index.js.map
@@ -734,7 +734,7 @@ var FilesClient = class {
734
734
  try {
735
735
  if (typeof option === "function") return await option();
736
736
  if (option) return option;
737
- const gateway = await import("./client-DcZ3iGES.js").then((n) => n.n);
737
+ const gateway = await import("./client-sAJTrb4i.js").then((n) => n.n);
738
738
  if (this.serviceName) return new gateway.GatewayClient({
739
739
  layer: "wspace",
740
740
  serviceName: this.serviceName,
@@ -827,4 +827,4 @@ var files_exports = /* @__PURE__ */ __exportAll({
827
827
  });
828
828
 
829
829
  export { FILE_VISIBILITIES as _, FilesClient as a, clampDownloadUrlTtl as c, FILES_CLIENT_GRAPHQL_CODES as d, FilesClientError as f, FILE_ACTOR_TYPES as g, toFilesClientError as h, toFileReference as i, fileExtensionOf as l, isFilesClientError as m, FILE_REFERENCE_KIND as n, MAX_DOWNLOAD_URL_TTL_SECONDS as o, classifyFilesErrors as p, isFileReference as r, MIN_DOWNLOAD_URL_TTL_SECONDS as s, files_exports as t, mapFileMetadata as u };
830
- //# sourceMappingURL=files-DjH0099H.js.map
830
+ //# sourceMappingURL=files-h5U-D2AF.js.map