@burdenoff/be-sdk 2026.1107.1 → 2026.1107.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/configs/eslint/index.js +28 -48
- package/configs/tsconfig/tsconfig.json +22 -37
- package/dist/EventQueueFactory-PP534MBQ.js +8 -0
- package/dist/{EventQueueFactory-PEYWB2RY.js.map → EventQueueFactory-PP534MBQ.js.map} +1 -1
- package/dist/ai-credits/index.js +1 -1
- package/dist/cache/index.js +2 -2
- package/dist/{chunk-PAQK3YF2.js → chunk-2HJC3ZL6.js} +3 -3
- package/dist/chunk-2HJC3ZL6.js.map +1 -0
- package/dist/{chunk-6SDWH4OM.js → chunk-2WBJFTQ6.js} +2 -2
- package/dist/{chunk-6SDWH4OM.js.map → chunk-2WBJFTQ6.js.map} +1 -1
- package/dist/{chunk-DS3YMJ4X.js → chunk-554Z4C2K.js} +2 -2
- package/dist/chunk-554Z4C2K.js.map +1 -0
- package/dist/{chunk-23WAZL7I.js → chunk-5CS3ZITV.js} +2 -2
- package/dist/chunk-5CS3ZITV.js.map +1 -0
- package/dist/{chunk-5ENWB2S6.js → chunk-5EVD6HOD.js} +5 -5
- package/dist/chunk-5EVD6HOD.js.map +1 -0
- package/dist/{chunk-MZCBEJ67.js → chunk-63ZXJ42X.js} +3 -3
- package/dist/{chunk-MZCBEJ67.js.map → chunk-63ZXJ42X.js.map} +1 -1
- package/dist/{chunk-7QCJE6IQ.js → chunk-7EISSMFP.js} +3 -3
- package/dist/{chunk-7QCJE6IQ.js.map → chunk-7EISSMFP.js.map} +1 -1
- package/dist/{chunk-Q5H45UXV.js → chunk-AP7PXEC7.js} +5 -5
- package/dist/{chunk-Q5H45UXV.js.map → chunk-AP7PXEC7.js.map} +1 -1
- package/dist/{chunk-64QUSPYG.js → chunk-BD3SMWUU.js} +3 -3
- package/dist/chunk-BD3SMWUU.js.map +1 -0
- package/dist/{chunk-EHUFQHMV.js → chunk-DIOS6L7M.js} +4 -4
- package/dist/{chunk-EHUFQHMV.js.map → chunk-DIOS6L7M.js.map} +1 -1
- package/dist/{chunk-42PJSEQK.js → chunk-DJNHR37J.js} +3 -3
- package/dist/{chunk-42PJSEQK.js.map → chunk-DJNHR37J.js.map} +1 -1
- package/dist/{chunk-7SWIUDYM.js → chunk-E6OAFS7A.js} +4 -4
- package/dist/chunk-E6OAFS7A.js.map +1 -0
- package/dist/{chunk-AWPNRV3L.js → chunk-GCIB76AJ.js} +2 -2
- package/dist/chunk-GCIB76AJ.js.map +1 -0
- package/dist/{chunk-XXNT4VCM.js → chunk-HC6MPUIH.js} +2 -2
- package/dist/{chunk-XXNT4VCM.js.map → chunk-HC6MPUIH.js.map} +1 -1
- package/dist/{chunk-TANAOLAV.js → chunk-JVMAQOA3.js} +2 -2
- package/dist/chunk-JVMAQOA3.js.map +1 -0
- package/dist/{chunk-DXCWPTKC.js → chunk-K56L7NUR.js} +3 -3
- package/dist/chunk-K56L7NUR.js.map +1 -0
- package/dist/{chunk-UWQ2OKA6.js → chunk-LQYHWC7F.js} +4 -4
- package/dist/{chunk-UWQ2OKA6.js.map → chunk-LQYHWC7F.js.map} +1 -1
- package/dist/{chunk-JSEG3G5L.js → chunk-MESLAC5W.js} +3 -3
- package/dist/{chunk-JSEG3G5L.js.map → chunk-MESLAC5W.js.map} +1 -1
- package/dist/{chunk-IGWTT2YA.js → chunk-OBZQ4AJC.js} +6 -6
- package/dist/{chunk-IGWTT2YA.js.map → chunk-OBZQ4AJC.js.map} +1 -1
- package/dist/{chunk-LCDECFJJ.js → chunk-OXNCBE7P.js} +4 -4
- package/dist/{chunk-LCDECFJJ.js.map → chunk-OXNCBE7P.js.map} +1 -1
- package/dist/{chunk-OHUBPOZ6.js → chunk-PBZFAAOM.js} +3 -3
- package/dist/{chunk-OHUBPOZ6.js.map → chunk-PBZFAAOM.js.map} +1 -1
- package/dist/{chunk-2Q6RH3GE.js → chunk-PYD44IHJ.js} +2 -2
- package/dist/chunk-PYD44IHJ.js.map +1 -0
- package/dist/{chunk-4KK6YJ46.js → chunk-QWNNFE4P.js} +2 -2
- package/dist/chunk-QWNNFE4P.js.map +1 -0
- package/dist/{chunk-E5DTAGCA.js → chunk-RYTSVGGA.js} +3 -3
- package/dist/chunk-RYTSVGGA.js.map +1 -0
- package/dist/{chunk-ZWKJKL6Y.js → chunk-SPRG6G6G.js} +3 -3
- package/dist/{chunk-ZWKJKL6Y.js.map → chunk-SPRG6G6G.js.map} +1 -1
- package/dist/{chunk-WTEHAVBX.js → chunk-VGAHZKNJ.js} +3 -3
- package/dist/{chunk-WTEHAVBX.js.map → chunk-VGAHZKNJ.js.map} +1 -1
- package/dist/{chunk-3YG5JRS5.js → chunk-VTJTAAXC.js} +3 -3
- package/dist/{chunk-3YG5JRS5.js.map → chunk-VTJTAAXC.js.map} +1 -1
- package/dist/{chunk-YK7C5DU6.js → chunk-WWUU5ETI.js} +2 -2
- package/dist/chunk-WWUU5ETI.js.map +1 -0
- package/dist/{client-FUR7I6DB.js → client-JU6T3UPB.js} +4 -4
- package/dist/{client-FUR7I6DB.js.map → client-JU6T3UPB.js.map} +1 -1
- package/dist/{esm-M2M7HGV4.js → dist-2X4Q7PJA.js} +628 -493
- package/dist/dist-2X4Q7PJA.js.map +1 -0
- package/dist/event-queue/index.js +3 -3
- package/dist/export/index.js +5 -5
- package/dist/files/index.js +2 -2
- package/dist/gateway/index.js +4 -4
- package/dist/gateway/security/index.js +1 -1
- package/dist/graph/index.js +5 -5
- package/dist/index.js +37 -37
- package/dist/index.js.map +1 -1
- package/dist/init/index.js +7 -7
- package/dist/instrumentation/index.js +2 -2
- package/dist/metrics/index.js +2 -2
- package/dist/notifications/index.js +1 -1
- package/dist/pino-logger-H4HPW5P6.js +5 -0
- package/dist/{pino-logger-GJ2CYLD5.js.map → pino-logger-H4HPW5P6.js.map} +1 -1
- package/dist/platform/index.js +1 -1
- package/dist/prisma/index.js +4 -4
- package/dist/resource-caps/index.js +2 -2
- package/dist/server/index.js +4 -4
- package/dist/server/index.js.map +1 -1
- package/dist/sharing/index.js +1 -1
- package/dist/tags/index.js +1 -1
- package/dist/telemetry/index.js +5 -5
- package/dist/tracker/index.js +8 -8
- package/dist/usage/index.js +5 -5
- package/dist/validation/index.js +1 -1
- package/package.json +66 -44
- package/dist/EventQueueFactory-PEYWB2RY.js +0 -8
- package/dist/chunk-23WAZL7I.js.map +0 -1
- package/dist/chunk-2Q6RH3GE.js.map +0 -1
- package/dist/chunk-4KK6YJ46.js.map +0 -1
- package/dist/chunk-5ENWB2S6.js.map +0 -1
- package/dist/chunk-64QUSPYG.js.map +0 -1
- package/dist/chunk-7SWIUDYM.js.map +0 -1
- package/dist/chunk-AWPNRV3L.js.map +0 -1
- package/dist/chunk-DS3YMJ4X.js.map +0 -1
- package/dist/chunk-DXCWPTKC.js.map +0 -1
- package/dist/chunk-E5DTAGCA.js.map +0 -1
- package/dist/chunk-PAQK3YF2.js.map +0 -1
- package/dist/chunk-TANAOLAV.js.map +0 -1
- package/dist/chunk-YK7C5DU6.js.map +0 -1
- package/dist/esm-M2M7HGV4.js.map +0 -1
- package/dist/pino-logger-GJ2CYLD5.js +0 -5
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { LayerManager } from './chunk-STWFX5E2.js';
|
|
2
2
|
import { signServiceJwt } from './chunk-VFCMR5GX.js';
|
|
3
3
|
import { ContextManager } from './chunk-RZOFS2BQ.js';
|
|
4
|
-
import { CircuitState, GatewayError, GatewayErrorType } from './chunk-
|
|
4
|
+
import { CircuitState, GatewayError, GatewayErrorType } from './chunk-QWNNFE4P.js';
|
|
5
5
|
import { currentEnvironment, isDeployedEnvironment } from './chunk-A5F6Z5UE.js';
|
|
6
6
|
import { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG } from './chunk-5CAFHK2Z.js';
|
|
7
7
|
import { logger } from './chunk-RU266375.js';
|
|
@@ -526,5 +526,5 @@ function createGatewayClientFromEnv() {
|
|
|
526
526
|
__name(createGatewayClientFromEnv, "createGatewayClientFromEnv");
|
|
527
527
|
|
|
528
528
|
export { GatewayClient, createGatewayClient, createGatewayClientFromEnv, isGatewayClientError, resolveBypassPermissionValue };
|
|
529
|
-
//# sourceMappingURL=chunk-
|
|
530
|
-
//# sourceMappingURL=chunk-
|
|
529
|
+
//# sourceMappingURL=chunk-SPRG6G6G.js.map
|
|
530
|
+
//# sourceMappingURL=chunk-SPRG6G6G.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"names":["SERVICE_JWT_SECRET_ENV","serviceJwtMisconfigurationMessage","context","environment","currentEnvironment","layer","operation","operationName","identity","serviceIdentity","gatewayUrl","assertServiceJwtConfigured","isDeployedEnvironment","Error","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","key","Object","keys","toLowerCase","isGraphQLError","value","message","extensions","Array","isArray","TRANSIENT_CLIENT_STATUSES","Set","isGatewayClientError","error","GatewayError","type","GatewayErrorType","GRAPHQL_ERROR","NETWORK_ERROR","statusCode","undefined","has","resolveBypassPermissionValue","token","process","env","normalizedToken","trim","CircuitBreaker","state","CircuitState","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","Date","now","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","serviceName","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","options","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","actorId","workspaceId","startTime","shouldRetryError","CIRCUIT_OPEN","calculateRetryDelay","attempt","Math","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","clientError","sleep","UNKNOWN_ERROR","buildRequestHeaders","cfHeaders","ContextManager","getCfAccessHeaders","assign","entries","toString","cfCookie","existing","split","some","c","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","graphqlErrors","handleFetchError","name","TIMEOUT_ERROR","cause","serviceActorId","serviceJwt","signServiceJwt","getLayer","body","JSON","stringify","variables","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","json","every","httpMessage","status","statusText","hasData","data","ms","Promise","resolve","createGatewayClient","createGatewayClientFromEnv"],"mappings":";;;;;;;;;;AAoCO,IAAMA,sBAAAA,GAAyB,oBAAA;AAkB/B,SAASC,kCAAkCC,OAAAA,EAA+B;AAC/E,EAAA,MAAMC,WAAAA,GAAcC,oBAAAA,IAAwB,OAAA;AAC5C,EAAA,MAAMC,KAAAA,GAAQH,QAAQG,KAAAA,IAAS,SAAA;AAC/B,EAAA,MAAMC,YAAYJ,OAAAA,CAAQK,aAAAA,GAAgB,CAAA,YAAA,EAAeL,OAAAA,CAAQK,aAAa,CAAA,CAAA,CAAA,GAAM,EAAA;AACpF,EAAA,MAAMC,WAAWN,OAAAA,CAAQO,eAAAA,GAAkB,CAAA,KAAA,EAAQP,OAAAA,CAAQO,eAAe,CAAA,CAAA,CAAA,GAAM,EAAA;AAChF,EAAA,OACE,uCAAuCP,OAAAA,CAAQQ,UAAU,CAAA,EAAGJ,SAAAA,2BAAoCE,QAAAA,CAAAA,EAAAA,EAC7FR,sBAAAA,CAAAA,kNAAAA,EAE6C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AAYA,UAAU,QAAA,EAAW;AACxD,IAAA,MAAM,IAAIQ,KAAAA,CAAM,CAAA,sFAAA,EAAyFR,KAAAA,CAAAA,CAAAA,CAAQ,CAAA;AACnH,EAAA;AAEA,EAAA,MAAMwF,WAAAA,GAAclD,OAAAA,CAAQC,GAAAA,CAAI,cAAA,CAAA;AAChC,EAAA,IAAI,CAACiD,WAAAA,EAAa;AAChB,IAAA,MAAM,IAAIhF,MAAM,+DAAA,CAAA;AAClB,EAAA;AAEA,EAAA,MAAMJ,eAAAA,GAAkBkC,OAAAA,CAAQC,GAAAA,CAAI,kBAAA,CAAA,IAAuBiD,WAAAA;AAE3D,EAAA,OAAO,IAAIT,aAAAA,CAAc;AACvB/E,IAAAA,KAAAA;AACAwF,IAAAA,WAAAA;AACApF,IAAAA;GACF,CAAA;AACF;AAnBgBsM,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-ZWKJKL6Y.js","sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\n/**\n * HTTP statuses in the 4xx range that describe a transient condition rather than\n * a problem with the request itself: the request timed out at the peer (408) or\n * the peer is shedding load (429 without a GraphQL body, i.e. an edge or proxy\n * limit). Those stay retryable and still count toward the circuit breaker.\n */\nconst TRANSIENT_CLIENT_STATUSES: ReadonlySet<number> = new Set([408, 429]);\n\n/**\n * Is this failure a definitive answer about the request rather than a sign that\n * the gateway or the transport is unhealthy?\n *\n * True for:\n * - `GRAPHQL_ERROR`: the gateway executed the operation and answered with\n * GraphQL errors (for example `NOT_FOUND`, `BAD_USER_INPUT`, `FORBIDDEN`),\n * whether that arrived with HTTP 200 or with a 4xx status;\n * - an HTTP 4xx without a GraphQL body (for example an edge 403 or 404), except\n * the transient statuses 408 and 429.\n *\n * Such failures are never retried (the same request gets the same answer) and\n * are not counted toward the circuit breaker: a burst of legitimate \"not found\"\n * lookups must not open the circuit for every other call the service makes.\n *\n * @param error - Anything thrown by a GatewayClient call\n * @returns Whether the error is a client error in the sense above\n */\nexport function isGatewayClientError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) return false;\n if (error.type === GatewayErrorType.GRAPHQL_ERROR) return true;\n if (error.type !== GatewayErrorType.NETWORK_ERROR || error.statusCode === undefined) return false;\n return error.statusCode >= 400 && error.statusCode < 500 && !TRANSIENT_CLIENT_STATUSES.has(error.statusCode);\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n const clientError = isGatewayClientError(error);\n if (!options.skipCircuitBreaker) {\n // A client error means the gateway answered: record it as a healthy\n // round trip (which also closes a half-open circuit) instead of a failure.\n if (clientError) {\n circuitBreaker.recordSuccess();\n } else {\n circuitBreaker.recordFailure();\n }\n }\n\n if (clientError || !this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n // Keep the \"HTTP <status>: <text>\" prefix callers may already match on,\n // and append the GraphQL messages so logs show what the gateway said.\n const httpMessage = `HTTP ${response.status}: ${response.statusText}`;\n throw new GatewayError(\n graphqlErrors\n ? `${httpMessage} (GraphQL error: ${graphqlErrors.map((e) => e.message).join(', ')})`\n : httpMessage,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/gateway/service-jwt-guard.ts","../src/gateway/client.ts"],"names":["SERVICE_JWT_SECRET_ENV","serviceJwtMisconfigurationMessage","context","environment","currentEnvironment","layer","operation","operationName","identity","serviceIdentity","gatewayUrl","assertServiceJwtConfigured","isDeployedEnvironment","Error","uuidv4","crypto","randomUUID","hasAuthorizationHeader","headers","key","Object","keys","toLowerCase","isGraphQLError","value","message","extensions","Array","isArray","TRANSIENT_CLIENT_STATUSES","Set","isGatewayClientError","error","GatewayError","type","GatewayErrorType","GRAPHQL_ERROR","NETWORK_ERROR","statusCode","undefined","has","resolveBypassPermissionValue","token","process","env","normalizedToken","trim","CircuitBreaker","state","CircuitState","CLOSED","failures","successes","consecutiveFailures","lastFailureTime","lastSuccessTime","openedAt","failureTimestamps","config","getState","checkStateTransition","recordSuccess","Date","now","HALF_OPEN","logger","info","recordFailure","push","windowStart","failureWindow","filter","t","length","failureThreshold","OPEN","warn","threshold","allowRequest","forceOpen","forceClose","getStats","elapsed","resetTimeout","GatewayClient","layerManager","internalCircuitBreaker","crossLayerCircuitBreaker","retryConfig","defaultHeaders","timeout","enableLogging","LayerManager","serviceName","internalGatewayUrl","crossLayerGatewayUrl","cbConfig","DEFAULT_CIRCUIT_BREAKER_CONFIG","circuitBreaker","DEFAULT_GATEWAY_RETRY_CONFIG","retry","getServiceIdentity","debug","internalUrl","getInternalUrl","crossLayerUrl","getCrossLayerUrl","getInternalGatewayUrl","getCrossLayerGatewayUrl","internalQuery","options","createRequestContext","executeWithRetry","bypassPermission","crossLayerQuery","query","getInternalCircuitBreaker","getCrossLayerCircuitBreaker","getHealthStatus","internal","url","circuitState","stats","crossLayer","updateDefaultHeaders","callType","requestId","actorId","workspaceId","startTime","shouldRetryError","CIRCUIT_OPEN","calculateRetryDelay","attempt","Math","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","clientError","sleep","UNKNOWN_ERROR","buildRequestHeaders","cfHeaders","ContextManager","getCfAccessHeaders","assign","entries","toString","cfCookie","existing","split","some","c","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","graphqlErrors","handleFetchError","name","TIMEOUT_ERROR","cause","serviceActorId","serviceJwt","signServiceJwt","getLayer","body","JSON","stringify","variables","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","json","every","httpMessage","status","statusText","hasData","data","ms","Promise","resolve","createGatewayClient","createGatewayClientFromEnv"],"mappings":";;;;;;;;;;AAoCO,IAAMA,sBAAAA,GAAyB,oBAAA;AAkB/B,SAASC,kCAAkCC,OAAAA,EAA+B;AAC/E,EAAA,MAAMC,WAAAA,GAAcC,oBAAAA,IAAwB,OAAA;AAC5C,EAAA,MAAMC,KAAAA,GAAQH,QAAQG,KAAAA,IAAS,SAAA;AAC/B,EAAA,MAAMC,YAAYJ,OAAAA,CAAQK,aAAAA,GAAgB,CAAA,YAAA,EAAeL,OAAAA,CAAQK,aAAa,CAAA,CAAA,CAAA,GAAM,EAAA;AACpF,EAAA,MAAMC,WAAWN,OAAAA,CAAQO,eAAAA,GAAkB,CAAA,KAAA,EAAQP,O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,EAAAA,qBAAAA,CAAAA;AAgBT,SAASC,0BAAAA,GAAAA;AACd,EAAA,MAAM1M,KAAAA,GAAQsC,OAAAA,CAAQC,GAAAA,CAAI,eAAA,CAAA;AAE1B,EAAA,IAAI,CAACvC,KAAAA,IAAUA,KAAAA,KAAU,QAAA,IAAYA,UAAU,QAAA,EAAW;AACxD,IAAA,MAAM,IAAIQ,KAAAA,CAAM,CAAA,sFAAA,EAAyFR,KAAAA,CAAAA,CAAAA,CAAQ,CAAA;AACnH,EAAA;AAEA,EAAA,MAAMwF,WAAAA,GAAclD,OAAAA,CAAQC,GAAAA,CAAI,cAAA,CAAA;AAChC,EAAA,IAAI,CAACiD,WAAAA,EAAa;AAChB,IAAA,MAAM,IAAIhF,MAAM,+DAAA,CAAA;AAClB,EAAA;AAEA,EAAA,MAAMJ,eAAAA,GAAkBkC,OAAAA,CAAQC,GAAAA,CAAI,kBAAA,CAAA,IAAuBiD,WAAAA;AAE3D,EAAA,OAAO,IAAIT,aAAAA,CAAc;AACvB/E,IAAAA,KAAAA;AACAwF,IAAAA,WAAAA;AACApF,IAAAA;GACF,CAAA;AACF;AAnBgBsM,MAAAA,CAAAA,0BAAAA,EAAAA,4BAAAA,CAAAA","file":"chunk-SPRG6G6G.js","sourcesContent":["/**\n * Cross-layer service-JWT configuration guard.\n *\n * A cross-layer call transits the peer layer's PUBLIC gateway, which propagates\n * `x-actor-*` context to subgraphs only when the request carries a valid JWT.\n * Without one the gateway strips those headers as potential client spoofing and\n * the subgraph rejects the call. So on a cross-layer request with no\n * Authorization header and no mintable service JWT, the outcome is already\n * decided before the request leaves the process: it will fail, downstream, with\n * an authentication error that names the callee rather than the missing secret.\n *\n * That is a bad trade in a deployed environment. It converts a one-line config\n * problem into an opaque failure attributed to the wrong service, and — because\n * several cross-layer callers treat these calls as best-effort and swallow the\n * error — into no visible failure at all. Alpha ran exactly that way: 414 calls\n * in 24h on `AddWorkspaceMemberFromWspace` and `WorkspaceOrganization`, every\n * one rejected, workspace-member mirroring silently not happening, and nothing\n * in the caller's logs above debug level.\n *\n * So in alpha, staging and production this throws before the request is sent,\n * naming the secret and the bundle to fix. Locally it stays a log: a laptop\n * calling across layers without a service JWT is a normal state while a\n * developer is mid-setup, and failing their `bun run dev` would be hostile.\n *\n * Verified inert before shipping, the same way the cache guard was: of the\n * alpha and prod service bundles in Secrets Manager, every be-sdk service that\n * makes cross-layer calls already carries `SERVICE_JWT_SECRET` (166 bundles).\n * The bundles without it are Temporal, OPA, the OTel collectors, NATS, Gatus,\n * the vibetunnels pair, the ai-assistant trio, the dormant `*-community`\n * deployments and the retired `state-archive-*` configs — none of which\n * constructs a GatewayClient or makes a cross-layer call. Nothing changes\n * today; this only catches the next caller rolled out without the secret.\n */\nimport { isDeployedEnvironment, currentEnvironment } from '../runtime/deployed-environment.js';\n\n/** Env var that must hold the signing key for service-actor JWTs. */\nexport const SERVICE_JWT_SECRET_ENV = 'SERVICE_JWT_SECRET';\n\nexport interface ServiceJwtGuardContext {\n /** Absolute URL of the peer gateway the call was about to be sent to. */\n gatewayUrl: string;\n /** GraphQL operation name, when the caller supplied one. */\n operationName?: string;\n /** Layer boundary of the CALLER, used to name the bundle to fix. */\n layer?: string;\n /** Service identity the JWT would have been minted for. */\n serviceIdentity?: string;\n}\n\n/**\n * Build the operator-facing explanation. Exported so the message itself is\n * covered by tests — a guard whose text does not say what to change just moves\n * the debugging, it does not remove it.\n */\nexport function serviceJwtMisconfigurationMessage(context: ServiceJwtGuardContext): string {\n const environment = currentEnvironment() || 'unset';\n const layer = context.layer ?? '{layer}';\n const operation = context.operationName ? ` (operation ${context.operationName})` : '';\n const identity = context.serviceIdentity ? ` as '${context.serviceIdentity}'` : '';\n return (\n `[GatewayClient] Cross-layer call to ${context.gatewayUrl}${operation} cannot be authenticated${identity}: ` +\n `${SERVICE_JWT_SECRET_ENV} is not set, so no service JWT can be minted. The peer layer's public ` +\n `gateway will strip actor headers and the subgraph will reject the request, so this call cannot ` +\n `succeed. Refusing to send it with DEPLOY_ENV=${environment}. Set ${SERVICE_JWT_SECRET_ENV} in ` +\n `boff/${environment}/${layer}/{module} — it must match the value the peer layer's gateway ` +\n `verifies with, which is per-environment and must never be copied across environments.`\n );\n}\n\n/**\n * Throw in a deployed environment when a cross-layer call is about to be sent\n * with no way to authenticate it. Returns normally everywhere else, and\n * whenever a JWT was available — so this costs nothing on the happy path.\n */\nexport function assertServiceJwtConfigured(context: ServiceJwtGuardContext): void {\n if (!isDeployedEnvironment()) return;\n throw new Error(serviceJwtMisconfigurationMessage(context));\n}\n","/**\n * Unified Gateway Client\n *\n * Provides a layer-aware GraphQL client with circuit breaker,\n * retry logic, and automatic header management for M2M communication.\n *\n * @module gateway/client\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient } from '@burdenoff/be-sdk/gateway';\n *\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer)\n * const result = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call\n * const authResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\nimport { ContextManager } from '../context/index.js';\nimport { LayerManager } from '../layer/index.js';\nimport { logger } from '../logger/index.js';\nimport { signServiceJwt } from './service-jwt.js';\nimport { assertServiceJwtConfigured } from './service-jwt-guard.js';\nimport {\n DEFAULT_CIRCUIT_BREAKER_CONFIG,\n DEFAULT_GATEWAY_RETRY_CONFIG,\n type CircuitBreakerConfig,\n type GatewayRequestHeaders,\n type GatewayRetryConfig,\n type ServiceLayer,\n} from '../types/layer.js';\nimport {\n CircuitState,\n GatewayError,\n GatewayErrorType,\n type CircuitBreakerStats,\n type GatewayClientConfig,\n type GatewayClientHealth,\n type GraphQLError,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type ICircuitBreaker,\n type IGatewayClient,\n type RequestContext,\n} from './types.js';\n\nconst uuidv4 = (): string => crypto.randomUUID();\n\n/**\n * Case-insensitive presence check for the `Authorization` header. HTTP header\n * names are case-insensitive (RFC 7230), and while the outbound `fetch` will\n * preserve whatever casing the caller supplies, callers may legitimately set\n * `authorization` / `Authorization` / even `AUTHORIZATION` via defaultHeaders\n * or options.headers. We must not overwrite an already-supplied token.\n */\nfunction hasAuthorizationHeader(headers: Record<string, string>): boolean {\n for (const key of Object.keys(headers)) {\n if (key.toLowerCase() === 'authorization') return true;\n }\n return false;\n}\n\nfunction isGraphQLError(value: unknown): value is GraphQLError {\n return (\n value !== null &&\n typeof value === 'object' &&\n 'message' in value &&\n typeof value.message === 'string' &&\n (!('extensions' in value) ||\n (value.extensions !== null && typeof value.extensions === 'object' && !Array.isArray(value.extensions)))\n );\n}\n\n/**\n * HTTP statuses in the 4xx range that describe a transient condition rather than\n * a problem with the request itself: the request timed out at the peer (408) or\n * the peer is shedding load (429 without a GraphQL body, i.e. an edge or proxy\n * limit). Those stay retryable and still count toward the circuit breaker.\n */\nconst TRANSIENT_CLIENT_STATUSES: ReadonlySet<number> = new Set([408, 429]);\n\n/**\n * Is this failure a definitive answer about the request rather than a sign that\n * the gateway or the transport is unhealthy?\n *\n * True for:\n * - `GRAPHQL_ERROR`: the gateway executed the operation and answered with\n * GraphQL errors (for example `NOT_FOUND`, `BAD_USER_INPUT`, `FORBIDDEN`),\n * whether that arrived with HTTP 200 or with a 4xx status;\n * - an HTTP 4xx without a GraphQL body (for example an edge 403 or 404), except\n * the transient statuses 408 and 429.\n *\n * Such failures are never retried (the same request gets the same answer) and\n * are not counted toward the circuit breaker: a burst of legitimate \"not found\"\n * lookups must not open the circuit for every other call the service makes.\n *\n * @param error - Anything thrown by a GatewayClient call\n * @returns Whether the error is a client error in the sense above\n */\nexport function isGatewayClientError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) return false;\n if (error.type === GatewayErrorType.GRAPHQL_ERROR) return true;\n if (error.type !== GatewayErrorType.NETWORK_ERROR || error.statusCode === undefined) return false;\n return error.statusCode >= 400 && error.statusCode < 500 && !TRANSIENT_CLIENT_STATUSES.has(error.statusCode);\n}\n\nexport function resolveBypassPermissionValue(\n token: string | undefined = process.env['INTERNAL_SERVICE_TOKEN']\n): string {\n const normalizedToken = token?.trim();\n\n if (!normalizedToken) {\n throw new Error('INTERNAL_SERVICE_TOKEN must be configured for bypass-enabled gateway calls');\n }\n\n return normalizedToken;\n}\n\n/**\n * Circuit Breaker Implementation\n */\nclass CircuitBreaker implements ICircuitBreaker {\n private state: CircuitState = CircuitState.CLOSED;\n private failures = 0;\n private successes = 0;\n private consecutiveFailures = 0;\n private lastFailureTime: number | null = null;\n private lastSuccessTime: number | null = null;\n private openedAt: number | null = null;\n private failureTimestamps: number[] = [];\n private config: CircuitBreakerConfig;\n\n constructor(config: CircuitBreakerConfig) {\n this.config = config;\n }\n\n getState(): CircuitState {\n this.checkStateTransition();\n return this.state;\n }\n\n recordSuccess(): void {\n this.successes++;\n this.consecutiveFailures = 0;\n this.lastSuccessTime = Date.now();\n\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit closed after successful test');\n }\n }\n\n recordFailure(): void {\n this.failures++;\n this.consecutiveFailures++;\n this.lastFailureTime = Date.now();\n this.failureTimestamps.push(Date.now());\n\n // Clean up old timestamps\n const windowStart = Date.now() - this.config.failureWindow;\n this.failureTimestamps = this.failureTimestamps.filter((t) => t > windowStart);\n\n // Check if we should open the circuit\n if (this.state === CircuitState.CLOSED && this.failureTimestamps.length >= this.config.failureThreshold) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit opened due to failures', {\n failures: this.failureTimestamps.length,\n threshold: this.config.failureThreshold,\n });\n }\n\n // If we're half-open and fail, go back to open\n if (this.state === CircuitState.HALF_OPEN) {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.warn('[CircuitBreaker] Circuit re-opened after failed test');\n }\n }\n\n allowRequest(): boolean {\n this.checkStateTransition();\n\n switch (this.state) {\n case CircuitState.CLOSED:\n return true;\n case CircuitState.OPEN:\n return false;\n case CircuitState.HALF_OPEN:\n // Allow one test request\n return true;\n default:\n return true;\n }\n }\n\n forceOpen(): void {\n this.state = CircuitState.OPEN;\n this.openedAt = Date.now();\n logger.info('[CircuitBreaker] Circuit force-opened');\n }\n\n forceClose(): void {\n this.state = CircuitState.CLOSED;\n this.failures = 0;\n this.consecutiveFailures = 0;\n this.failureTimestamps = [];\n this.openedAt = null;\n logger.info('[CircuitBreaker] Circuit force-closed');\n }\n\n getStats(): CircuitBreakerStats {\n return {\n state: this.state,\n failures: this.failures,\n successes: this.successes,\n consecutiveFailures: this.consecutiveFailures,\n lastFailureTime: this.lastFailureTime,\n lastSuccessTime: this.lastSuccessTime,\n openedAt: this.openedAt,\n };\n }\n\n private checkStateTransition(): void {\n if (this.state === CircuitState.OPEN && this.openedAt) {\n const elapsed = Date.now() - this.openedAt;\n if (elapsed >= this.config.resetTimeout) {\n this.state = CircuitState.HALF_OPEN;\n logger.info('[CircuitBreaker] Circuit transitioning to half-open');\n }\n }\n }\n}\n\n/**\n * Unified Gateway Client\n */\nexport class GatewayClient implements IGatewayClient {\n private config: GatewayClientConfig;\n private layerManager: LayerManager;\n private internalCircuitBreaker: CircuitBreaker;\n private crossLayerCircuitBreaker: CircuitBreaker;\n private retryConfig: GatewayRetryConfig;\n private defaultHeaders: GatewayRequestHeaders;\n\n constructor(config: GatewayClientConfig) {\n this.config = {\n timeout: 30000,\n enableLogging: true,\n ...config,\n };\n\n // Initialize layer manager\n this.layerManager = new LayerManager({\n layer: config.layer,\n serviceName: config.serviceName,\n serviceIdentity: config.serviceIdentity,\n });\n\n // Override URLs if provided\n if (config.internalGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n if (config.crossLayerGatewayUrl) {\n // Use getter internally, but we'll store the override\n }\n\n // Initialize circuit breakers\n const cbConfig: CircuitBreakerConfig = {\n ...DEFAULT_CIRCUIT_BREAKER_CONFIG,\n ...config.circuitBreaker,\n };\n this.internalCircuitBreaker = new CircuitBreaker(cbConfig);\n this.crossLayerCircuitBreaker = new CircuitBreaker(cbConfig);\n\n // Initialize retry config\n this.retryConfig = {\n ...DEFAULT_GATEWAY_RETRY_CONFIG,\n ...config.retry,\n };\n\n // Initialize default headers\n this.defaultHeaders = {\n 'x-service-identity': this.layerManager.getServiceIdentity(),\n 'x-actor-type': 'service',\n ...config.defaultHeaders,\n };\n\n logger.debug('[GatewayClient] Initialized', {\n layer: config.layer,\n serviceName: config.serviceName,\n internalUrl: this.getInternalUrl(),\n crossLayerUrl: this.getCrossLayerUrl(),\n });\n }\n\n private getInternalUrl(): string {\n return this.config.internalGatewayUrl || this.layerManager.getInternalGatewayUrl();\n }\n\n private getCrossLayerUrl(): string {\n return this.config.crossLayerGatewayUrl || this.layerManager.getCrossLayerGatewayUrl();\n }\n\n /**\n * Execute internal (same layer) GraphQL query/mutation\n */\n async internalQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('internal', options);\n\n return this.executeWithRetry(this.getInternalUrl(), options, this.internalCircuitBreaker, context, {\n bypassPermission: true,\n });\n }\n\n /**\n * Execute cross-layer GraphQL query/mutation\n */\n async crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('cross-layer', options);\n\n return this.executeWithRetry(\n this.getCrossLayerUrl(),\n options,\n this.crossLayerCircuitBreaker,\n context,\n { bypassPermission: false } // Cross-layer calls go through public gateway\n );\n }\n\n /**\n * Execute GraphQL query/mutation with explicit gateway URL\n */\n async query<T = unknown>(gatewayUrl: string, options: GraphQLRequestOptions): Promise<GraphQLResponse<T>> {\n const context = this.createRequestContext('direct', options);\n\n // Use internal circuit breaker for direct calls\n return this.executeWithRetry(gatewayUrl, options, this.internalCircuitBreaker, context, {\n bypassPermission: false,\n });\n }\n\n getInternalCircuitBreaker(): ICircuitBreaker {\n return this.internalCircuitBreaker;\n }\n\n getCrossLayerCircuitBreaker(): ICircuitBreaker {\n return this.crossLayerCircuitBreaker;\n }\n\n getHealthStatus(): GatewayClientHealth {\n return {\n internal: {\n url: this.getInternalUrl(),\n circuitState: this.internalCircuitBreaker.getState(),\n stats: this.internalCircuitBreaker.getStats(),\n },\n crossLayer: {\n url: this.getCrossLayerUrl(),\n circuitState: this.crossLayerCircuitBreaker.getState(),\n stats: this.crossLayerCircuitBreaker.getStats(),\n },\n };\n }\n\n updateDefaultHeaders(headers: Partial<GatewayRequestHeaders>): void {\n this.defaultHeaders = { ...this.defaultHeaders, ...headers };\n }\n\n private createRequestContext(\n callType: 'internal' | 'cross-layer' | 'direct',\n options: GraphQLRequestOptions\n ): RequestContext {\n return {\n requestId: uuidv4(),\n actorId: options.headers?.['x-actor-id'] || this.defaultHeaders['x-actor-id'],\n workspaceId: options.headers?.['x-workspace-id'] || this.defaultHeaders['x-workspace-id'],\n startTime: Date.now(),\n callType,\n };\n }\n\n /**\n * Check if an error should be retried\n */\n private shouldRetryError(error: unknown): boolean {\n if (!(error instanceof GatewayError)) {\n return true;\n }\n // Don't retry GraphQL errors or circuit open errors\n return error.type !== GatewayErrorType.GRAPHQL_ERROR && error.type !== GatewayErrorType.CIRCUIT_OPEN;\n }\n\n /**\n * Calculate retry delay with exponential backoff\n */\n private calculateRetryDelay(attempt: number): number {\n return Math.min(\n this.retryConfig.initialDelay * Math.pow(this.retryConfig.backoffMultiplier, attempt - 1),\n this.retryConfig.maxDelay\n );\n }\n\n /**\n * Log retry attempt if logging is enabled\n */\n private logRetryAttempt(\n context: RequestContext,\n attempt: number,\n maxAttempts: number,\n delay: number,\n error: Error\n ): void {\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] Request failed, retrying', {\n requestId: context.requestId,\n attempt,\n maxAttempts,\n delay,\n error: error.message,\n });\n }\n }\n\n private async executeWithRetry<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n circuitBreaker: CircuitBreaker,\n context: RequestContext,\n settings: { bypassPermission: boolean }\n ): Promise<GraphQLResponse<T>> {\n // Check circuit breaker\n if (!options.skipCircuitBreaker && !circuitBreaker.allowRequest()) {\n throw new GatewayError(`Circuit breaker is open for ${gatewayUrl}`, GatewayErrorType.CIRCUIT_OPEN, gatewayUrl);\n }\n\n const maxAttempts = options.skipRetry ? 1 : this.retryConfig.maxAttempts;\n let lastError: Error | null = null;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n const result = await this.executeRequest<T>(gatewayUrl, options, context, settings.bypassPermission);\n if (!options.skipCircuitBreaker) {\n circuitBreaker.recordSuccess();\n }\n return result;\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n const clientError = isGatewayClientError(error);\n if (!options.skipCircuitBreaker) {\n // A client error means the gateway answered: record it as a healthy\n // round trip (which also closes a half-open circuit) instead of a failure.\n if (clientError) {\n circuitBreaker.recordSuccess();\n } else {\n circuitBreaker.recordFailure();\n }\n }\n\n if (clientError || !this.shouldRetryError(error)) {\n throw error;\n }\n\n if (attempt < maxAttempts) {\n const delay = this.calculateRetryDelay(attempt);\n this.logRetryAttempt(context, attempt, maxAttempts, delay, lastError);\n await this.sleep(delay);\n }\n }\n }\n\n throw lastError || new GatewayError('Request failed after retries', GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n /**\n * Build headers for a request\n */\n private buildRequestHeaders(\n context: RequestContext,\n options: GraphQLRequestOptions,\n bypassPermission: boolean\n ): Record<string, string> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n 'x-request-id': context.requestId,\n 'x-call-type': context.callType,\n };\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which on alpha\n // sits behind Cloudflare Access. Re-present the inbound request's CF creds\n // (service token and/or the CF_Authorization cookie) so the call passes the\n // CF edge. Added before default/request headers so a caller may still\n // override the non-cookie CF headers explicitly; the CF cookie is reconciled\n // after the merges below so it is never silently clobbered. No-op when the\n // inbound request carried no CF creds (local dev, production) — returns {}.\n const cfHeaders = context.callType === 'cross-layer' ? ContextManager.getCfAccessHeaders() : {};\n Object.assign(headers, cfHeaders);\n\n // Add default headers\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n\n // Add request-specific headers\n if (options.headers) {\n for (const [key, value] of Object.entries(options.headers)) {\n if (value !== undefined) {\n headers[key] = String(value);\n }\n }\n }\n\n // Add bypass headers for internal calls\n if (bypassPermission) {\n headers['x-bypass-permission'] = resolveBypassPermissionValue();\n headers['x-bypass-source'] = this.layerManager.getServiceIdentity();\n headers['x-bypass-timestamp'] = Date.now().toString();\n }\n\n // Reconcile the CF_Authorization cookie: the default/request-header merges\n // above may set their own `cookie`, which would otherwise clobber the CF\n // cookie applied earlier (or vice versa). Merge so both survive, without\n // duplicating if it's already present.\n const cfCookie = cfHeaders['cookie'];\n if (cfCookie) {\n const existing = headers['cookie'];\n if (!existing) {\n headers['cookie'] = cfCookie;\n } else if (!existing.split(';').some((c) => c.trim() === cfCookie)) {\n headers['cookie'] = `${existing}; ${cfCookie}`;\n }\n }\n\n return headers;\n }\n\n /**\n * Handle GraphQL errors in response\n */\n private handleGraphQLErrors<T>(\n result: GraphQLResponse<T>,\n context: RequestContext,\n gatewayUrl: string,\n duration: number\n ): void {\n if (!result.errors || result.errors.length === 0) {\n return;\n }\n\n const errorMessages = result.errors.map((e: GraphQLError) => e.message).join(', ');\n\n if (this.config.enableLogging) {\n logger.warn('[GatewayClient] GraphQL errors', {\n requestId: context.requestId,\n errors: result.errors,\n duration,\n });\n }\n\n throw new GatewayError(`GraphQL error: ${errorMessages}`, GatewayErrorType.GRAPHQL_ERROR, gatewayUrl, {\n graphqlErrors: result.errors,\n });\n }\n\n /**\n * Handle fetch errors\n */\n private handleFetchError(\n error: unknown,\n context: RequestContext,\n gatewayUrl: string,\n timeout: number,\n duration: number\n ): never {\n if (error instanceof GatewayError) {\n throw error;\n }\n\n if (error instanceof Error) {\n if (error.name === 'AbortError') {\n throw new GatewayError(`Request timed out after ${timeout}ms`, GatewayErrorType.TIMEOUT_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n if (this.config.enableLogging) {\n logger.error('[GatewayClient] Request failed', {\n requestId: context.requestId,\n error: error.message,\n duration,\n });\n }\n\n throw new GatewayError(error.message, GatewayErrorType.NETWORK_ERROR, gatewayUrl, {\n cause: error,\n });\n }\n\n throw new GatewayError(String(error), GatewayErrorType.UNKNOWN_ERROR, gatewayUrl);\n }\n\n private async executeRequest<T>(\n gatewayUrl: string,\n options: GraphQLRequestOptions,\n context: RequestContext,\n bypassPermission: boolean\n ): Promise<GraphQLResponse<T>> {\n const timeout = options.timeout || this.config.timeout || 30000;\n const headers = this.buildRequestHeaders(context, options, bypassPermission);\n\n // Cross-layer calls transit the peer layer's PUBLIC gateway, which\n // requires JWT auth to propagate actor context. Mint a short-lived\n // service-actor JWT so the gateway admits the call and preserves\n // `x-actor-type: service` downstream. Skipped when the caller has\n // already supplied an Authorization header (e.g., user-originated\n // cross-layer flows) or when SERVICE_JWT_SECRET is unset.\n if (context.callType === 'cross-layer' && !hasAuthorizationHeader(headers)) {\n const serviceActorId = this.layerManager.getServiceIdentity();\n const serviceJwt = await signServiceJwt(serviceActorId);\n if (serviceJwt) {\n headers['Authorization'] = `Bearer ${serviceJwt}`;\n } else {\n // Without the JWT this call is already decided: the peer layer's public\n // gateway strips actor headers and the subgraph rejects it. Continuing\n // only converts a missing secret into an authentication error that names\n // the callee — and several cross-layer callers swallow that as\n // best-effort, so it surfaces as nothing at all. In a deployed\n // environment, refuse instead. See ./service-jwt-guard.ts.\n assertServiceJwtConfigured({\n gatewayUrl,\n operationName: options.operationName,\n layer: this.layerManager.getLayer(),\n serviceIdentity: serviceActorId,\n });\n if (this.config.enableLogging) {\n logger.debug(\n '[GatewayClient] SERVICE_JWT_SECRET not configured — cross-layer call will proceed without service JWT',\n { requestId: context.requestId, gatewayUrl }\n );\n }\n }\n }\n\n const body = JSON.stringify({\n query: options.query,\n variables: options.variables || {},\n operationName: options.operationName,\n });\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Executing request', {\n requestId: context.requestId,\n gatewayUrl,\n operationName: options.operationName,\n callType: context.callType,\n bypassPermission,\n });\n }\n\n try {\n const controller = new AbortController();\n const timeoutId = setTimeout(() => controller.abort(), timeout);\n\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n\n clearTimeout(timeoutId);\n const duration = Date.now() - context.startTime;\n\n if (!response.ok) {\n let graphqlErrors: GraphQLError[] | undefined;\n try {\n const body: unknown = await response.json();\n if (\n body !== null &&\n typeof body === 'object' &&\n 'errors' in body &&\n Array.isArray(body.errors) &&\n body.errors.length > 0 &&\n body.errors.every(isGraphQLError)\n )\n graphqlErrors = body.errors;\n } catch {\n // Edge/proxy errors need not contain JSON; retain the original HTTP failure.\n }\n // Keep the \"HTTP <status>: <text>\" prefix callers may already match on,\n // and append the GraphQL messages so logs show what the gateway said.\n const httpMessage = `HTTP ${response.status}: ${response.statusText}`;\n throw new GatewayError(\n graphqlErrors\n ? `${httpMessage} (GraphQL error: ${graphqlErrors.map((e) => e.message).join(', ')})`\n : httpMessage,\n graphqlErrors && response.status < 500 ? GatewayErrorType.GRAPHQL_ERROR : GatewayErrorType.NETWORK_ERROR,\n gatewayUrl,\n { statusCode: response.status, graphqlErrors }\n );\n }\n\n const result = (await response.json()) as GraphQLResponse<T>;\n this.handleGraphQLErrors(result, context, gatewayUrl, duration);\n\n if (this.config.enableLogging) {\n logger.debug('[GatewayClient] Request completed', {\n requestId: context.requestId,\n duration,\n hasData: !!result.data,\n });\n }\n\n return result;\n } catch (error) {\n const duration = Date.now() - context.startTime;\n this.handleFetchError(error, context, gatewayUrl, timeout, duration);\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n }\n}\n\n/**\n * Create a gateway client for a specific layer\n */\nexport function createGatewayClient(config: GatewayClientConfig): GatewayClient {\n return new GatewayClient(config);\n}\n\n/**\n * Create a gateway client from environment variables\n *\n * Required environment variables:\n * - SERVICE_LAYER: 'wspace' | 'global'\n * - SERVICE_NAME: Service name\n *\n * Optional:\n * - SERVICE_IDENTITY: Service identity (defaults to SERVICE_NAME)\n * - {LAYER}_INT_GATEWAY_URL: Internal gateway URL\n * - {OPPOSITE_LAYER}_PUBLIC_GATEWAY_URL: Cross-layer gateway URL\n */\nexport function createGatewayClientFromEnv(): GatewayClient {\n const layer = process.env['SERVICE_LAYER'] as ServiceLayer;\n\n if (!layer || (layer !== 'wspace' && layer !== 'global')) {\n throw new Error(`[GatewayClient] Invalid or missing SERVICE_LAYER. Expected 'wspace' or 'global', got '${layer}'`);\n }\n\n const serviceName = process.env['SERVICE_NAME'];\n if (!serviceName) {\n throw new Error('[GatewayClient] SERVICE_NAME environment variable is required');\n }\n\n const serviceIdentity = process.env['SERVICE_IDENTITY'] || serviceName;\n\n return new GatewayClient({\n layer,\n serviceName,\n serviceIdentity,\n });\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getMetricsRegistry } from './chunk-
|
|
1
|
+
import { getMetricsRegistry } from './chunk-GCIB76AJ.js';
|
|
2
2
|
import { __name } from './chunk-XE4OXN2W.js';
|
|
3
3
|
|
|
4
4
|
// src/metrics/workspace-quota-metrics.ts
|
|
@@ -62,5 +62,5 @@ function resetWorkspaceQuotaRegistry() {
|
|
|
62
62
|
__name(resetWorkspaceQuotaRegistry, "resetWorkspaceQuotaRegistry");
|
|
63
63
|
|
|
64
64
|
export { getWorkspaceQuotaRegistry, resetWorkspaceQuotaRegistry };
|
|
65
|
-
//# sourceMappingURL=chunk-
|
|
66
|
-
//# sourceMappingURL=chunk-
|
|
65
|
+
//# sourceMappingURL=chunk-VGAHZKNJ.js.map
|
|
66
|
+
//# sourceMappingURL=chunk-VGAHZKNJ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/metrics/workspace-quota-metrics.ts"],"names":["WorkspaceQuotaRegistry","collectors","gauges","Map","previousWorkspaceIds","register","collector","push","collectAll","Promise","allSettled","map","has","metricName","set","getMetricsRegistry","createGauge","help","gauge","get","values","collect","currentWorkspaceIds","Set","keys","labelSetKey","quotaName","workspaceId","workspace_id","quota_name","value","getCollectors","_registry","getWorkspaceQuotaRegistry","resetWorkspaceQuotaRegistry"],"mappings":";;;;AAkCA,IAAMA,sBAAAA,GAAN,MAAMA,uBAAAA,CAAAA;EAlCN;;;AAmCmBC,EAAAA,UAAAA,GAAwC,EAAA;AACxCC,EAAAA,MAAAA,uBAAaC,GAAAA,EAAAA;AACbC,EAAAA,oBAAAA,uBAA2BD,GAAAA,EAAAA;AAE5CE,EAAAA,QAAAA,CAASC,SAAAA,EAA0C;AACjD,IAAA,IAAA,CAAKL,UAAAA,CAAWM,KAAKD,SAAAA,CAAAA;AACvB,EAAA;;;;;;AAOA,EAAA,MAAME,UAAAA,GAA4B;AAChC,IAAA,MAAMC,QAAQC,UAAAA,CACZ,IAAA,CAAKT,UAAAA,CAAWU,GAAAA,CAAI,OAAOL,SAAAA,KAAAA;AACzB,MAAA,IAAI,CAAC,IAAA,CAAKJ,MAAAA,CAAOU,GAAAA,CAAIN,SAAAA,CAAUO,UAAU,CAAA,EAAG;AAC1C,QAAA,IAAA,CAAKX,MAAAA,CAAOY,GAAAA,CAAIR,SAAAA,CAAUO,UAAAA,EAAYE,kBAAAA,EAAAA,CAAqBC,WAAAA,CAAYV,SAAAA,CAAUO,UAAAA,EAAYP,SAAAA,CAAUW,IAAI,CAAA,CAAA;AAC7G,MAAA;AACA,MAAA,MAAMC,KAAAA,GAAQ,IAAA,CAAKhB,MAAAA,CAAOiB,GAAAA,CAAIb,UAAUO,UAAU,CAAA;AAClD,MAAA,IAAI,CAACK,KAAAA,EAAO;AACZ,MAAA,MAAME,MAAAA,GAAS,MAAMd,SAAAA,CAAUe,OAAAA,E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yBAAAA,EAAAA,2BAAAA,CAAAA;AAMT,SAASC,2BAAAA,GAAAA;AACdF,EAAAA,SAAAA,GAAY,IAAA;AACd;AAFgBE,MAAAA,CAAAA,2BAAAA,EAAAA,6BAAAA,CAAAA","file":"chunk-
|
|
1
|
+
{"version":3,"sources":["../src/metrics/workspace-quota-metrics.ts"],"names":["WorkspaceQuotaRegistry","collectors","gauges","Map","previousWorkspaceIds","register","collector","push","collectAll","Promise","allSettled","map","has","metricName","set","getMetricsRegistry","createGauge","help","gauge","get","values","collect","currentWorkspaceIds","Set","keys","labelSetKey","quotaName","workspaceId","workspace_id","quota_name","value","getCollectors","_registry","getWorkspaceQuotaRegistry","resetWorkspaceQuotaRegistry"],"mappings":";;;;AAkCA,IAAMA,sBAAAA,GAAN,MAAMA,uBAAAA,CAAAA;EAlCN;;;AAmCmBC,EAAAA,UAAAA,GAAwC,EAAA;AACxCC,EAAAA,MAAAA,uBAAaC,GAAAA,EAAAA;AACbC,EAAAA,oBAAAA,uBAA2BD,GAAAA,EAAAA;AAE5CE,EAAAA,QAAAA,CAASC,SAAAA,EAA0C;AACjD,IAAA,IAAA,CAAKL,UAAAA,CAAWM,KAAKD,SAAAA,CAAAA;AACvB,EAAA;;;;;;AAOA,EAAA,MAAME,UAAAA,GAA4B;AAChC,IAAA,MAAMC,QAAQC,UAAAA,CACZ,IAAA,CAAKT,UAAAA,CAAWU,GAAAA,CAAI,OAAOL,SAAAA,KAAAA;AACzB,MAAA,IAAI,CAAC,IAAA,CAAKJ,MAAAA,CAAOU,GAAAA,CAAIN,SAAAA,CAAUO,UAAU,CAAA,EAAG;AAC1C,QAAA,IAAA,CAAKX,MAAAA,CAAOY,GAAAA,CAAIR,SAAAA,CAAUO,UAAAA,EAAYE,kBAAAA,EAAAA,CAAqBC,WAAAA,CAAYV,SAAAA,CAAUO,UAAAA,EAAYP,SAAAA,CAAUW,IAAI,CAAA,CAAA;AAC7G,MAAA;AACA,MAAA,MAAMC,KAAAA,GAAQ,IA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A;AAExC,SAASC,yBAAAA,GAAAA;AACd,EAAA,IAAI,CAACD,SAAAA,EAAWA,SAAAA,GAAY,IAAIhC,sBAAAA,EAAAA;AAChC,EAAA,OAAOgC,SAAAA;AACT;AAHgBC,MAAAA,CAAAA,yBAAAA,EAAAA,2BAAAA,CAAAA;AAMT,SAASC,2BAAAA,GAAAA;AACdF,EAAAA,SAAAA,GAAY,IAAA;AACd;AAFgBE,MAAAA,CAAAA,2BAAAA,EAAAA,6BAAAA,CAAAA","file":"chunk-VGAHZKNJ.js","sourcesContent":["import { getMetricsRegistry } from '../instrumentation/metrics-collector.js';\nimport type { Gauge } from '../instrumentation/metrics-collector.js';\n\n/**\n * A single workspace-scoped quota metric.\n *\n * Services implement this and register it with WorkspaceQuotaRegistry at startup.\n * The metrics endpoint calls collectAll() on every scrape so values are always fresh.\n *\n * Pattern:\n * 1. Service registers collectors at startup (after instrumentation is initialized)\n * 2. /api/metrics handler calls collectAll() before serializing Prometheus output\n * 3. activity-svc scrapes /api/metrics and correlates values via quotaName to billing limits\n */\nexport interface WorkspaceQuotaCollector {\n /** Prometheus metric name, e.g. \"vibecontrols_tunnels_active\" */\n readonly metricName: string;\n /** Human-readable description shown in Prometheus HELP output */\n readonly help: string;\n /**\n * Billing quota name this metric maps to.\n * activity-svc uses this to correlate scraped values with quota limits.\n * e.g. \"vibecontrols.tunnels.active\"\n */\n readonly quotaName: string;\n /**\n * Called on every Prometheus scrape.\n * Must return current value per workspace ID.\n * Should be a fast, bounded DB query (GROUP BY workspace_id).\n * Failures are caught with Promise.allSettled — one failing collector does not block others.\n */\n collect(): Promise<Map<string, number>>;\n}\n\nclass WorkspaceQuotaRegistry {\n private readonly collectors: WorkspaceQuotaCollector[] = [];\n private readonly gauges = new Map<string, Gauge>();\n private readonly previousWorkspaceIds = new Map<string, Set<string>>();\n\n register(collector: WorkspaceQuotaCollector): void {\n this.collectors.push(collector);\n }\n\n /**\n * Runs all registered collectors and updates their gauges with fresh values.\n * Gauges are created lazily on first collectAll() to ensure MetricsRegistry\n * is initialized before gauge creation (instrumentation must be set up first).\n */\n async collectAll(): Promise<void> {\n await Promise.allSettled(\n this.collectors.map(async (collector) => {\n if (!this.gauges.has(collector.metricName)) {\n this.gauges.set(collector.metricName, getMetricsRegistry().createGauge(collector.metricName, collector.help));\n }\n const gauge = this.gauges.get(collector.metricName);\n if (!gauge) return;\n const values = await collector.collect();\n const currentWorkspaceIds = new Set(values.keys());\n const labelSetKey = `${collector.metricName}\\0${collector.quotaName}`;\n const previousWorkspaceIds = this.previousWorkspaceIds.get(labelSetKey);\n\n // Prometheus gauges retain every previously emitted label set. A GROUP BY\n // collector naturally omits a workspace once its value reaches zero, so\n // explicitly zero labels that disappeared from a successful collection.\n // Do not do this when collect() throws: Promise.allSettled preserves the\n // last known values until a later successful scrape can replace them.\n for (const workspaceId of previousWorkspaceIds ?? []) {\n if (!currentWorkspaceIds.has(workspaceId)) {\n gauge.set(0, { workspace_id: workspaceId, quota_name: collector.quotaName });\n }\n }\n for (const [workspaceId, value] of values) {\n gauge.set(value, { workspace_id: workspaceId, quota_name: collector.quotaName });\n }\n this.previousWorkspaceIds.set(labelSetKey, currentWorkspaceIds);\n })\n );\n }\n\n /** Returns registered collectors — useful for activity-svc to discover tracked quota names. */\n getCollectors(): readonly WorkspaceQuotaCollector[] {\n return this.collectors;\n }\n}\n\nlet _registry: WorkspaceQuotaRegistry | null = null;\n\nexport function getWorkspaceQuotaRegistry(): WorkspaceQuotaRegistry {\n if (!_registry) _registry = new WorkspaceQuotaRegistry();\n return _registry;\n}\n\n/** For testing only. */\nexport function resetWorkspaceQuotaRegistry(): void {\n _registry = null;\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { GatewayClient } from './chunk-
|
|
1
|
+
import { GatewayClient } from './chunk-SPRG6G6G.js';
|
|
2
2
|
import { __export, __name } from './chunk-XE4OXN2W.js';
|
|
3
3
|
|
|
4
4
|
// src/export/index.ts
|
|
@@ -623,5 +623,5 @@ async function triggerExportJob(params) {
|
|
|
623
623
|
__name(triggerExportJob, "triggerExportJob");
|
|
624
624
|
|
|
625
625
|
export { BaseModuleExporter, PaginationService, convertToCSV, csvToJSON, estimateCSVSize, export_exports, getCSVHeaders, parseCSV, triggerExportJob };
|
|
626
|
-
//# sourceMappingURL=chunk-
|
|
627
|
-
//# sourceMappingURL=chunk-
|
|
626
|
+
//# sourceMappingURL=chunk-VTJTAAXC.js.map
|
|
627
|
+
//# sourceMappingURL=chunk-VTJTAAXC.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/export/index.ts","../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts"],"names":["BaseModuleExporter","moduleKey","displayName","description","defaultExcludeFields","supportedProducts","modelName","filterFields","entity","excludeFields","fieldsToExclude","length","filtered","record","key","value","Object","entries","includes","filterFieldsMany","entities","map","paginate","queryFn","page","pageSize","skip","take","items","total","data","hasMore","nextCursor","String","undefined","fetchAll","fetchBatch","batchSize","allItems","cursor","batch","push","lastItem","id","transformForExport","validateOptions","options","validFormats","format","Error","join","getSupportedFormats","getMetadata","supportedFormats","PaginationService","params","start","end","paginatedItems","slice","totalCount","pageInfo","hasNextPage","hasPreviousPage","startCursor","endCursor","Math","min","calculatePagination","totalPages","ceil","startIndex","endIndex","currentPage","paginatedQuery","fetchFn","limit","initialCursor","totalYielded","item","collectPaginatedQuery","createPrismaFetchFn","_batchSize","calculateOffset","max","parseCursor","decoded","Buffer","from","toString","JSON","parse","createCursor","stringify","FORMULA_PREFIX_RE","sanitizeCSVCell","test","convertToCSV","delimiter","includeHeaders","flattenFields","maxFlattenDepth","flattenObject","obj","prefix","depth","result","newKey","Date","toISOString","Array","isArray","assign","flattenedRecords","allKeys","Set","keys","add","headers","sort","a","b","localeCompare","escapeCSV","sanitizedValue","replace","lines","row","header","parseCSV","csv","hasHeaders","split","filter","line","trim","parseLine","values","current","inQuotes","i","char","nextChar","dataLines","firstLine","firstRow","_","forEach","csvToJSON","pretty","parseOptions","getCSVHeaders","collectKeys","fullKey","estimateCSVSize","sampleSize","sample","sampleCSV","averageRowSize","headerSize","CREATE_EXPORT_JOB_MUTATION","triggerExportJob","serviceName","layer","actorId","actorType","workspaceId","name","entityTypes","includeMetadata","dateRangeStart","dateRangeEnd","client","GatewayClient","input","response","internalQuery","query","variables","job","createExportJob"],"mappings":";;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;ACoCO,IAAeA,qBAAf,MAAeA;EApCtB;;;;AAsCEC,EAAAA,SAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,oBAAAA;;AAGAC,EAAAA,iBAAAA;;AAGUC,EAAAA,SAAAA;;;;;;;;;;;;;;;;;AA6BAC,EAAAA,YAAAA,CAAaC,QAAqCC,aAAAA,EAAmD;AAC7G,IAAA,MAAMC,eAAAA,GAAkBD,aAAAA,IAAiB,IAAA,CAAKL,oBAAAA,IAAwB,EAAA;AAEtE,IAAA,IAAIM,eAAAA,CAAgBC,WAAW,CAAA,EAAG;AAChC,MAAA,OAAOH,MAAAA;AACT,IAAA;AAEA,IAAA,MAAMI,WAAoC,EAAC;AAC3C,IAAA,MAAMC,MAAAA,GAASL,MAAAA;AAEf,IAAA,KAAA,MAAW,CAACM,GAAAA,EAAKC,KAAAA,KAAUC,MAAAA,CAAOC,OAAAA,CAAQJ,MAAAA,CAAAA,EAAS;AACjD,MAAA,IAAI,CAACH,eAAAA,CAAgBQ,QAAAA,CAASJ,GAAAA,CAAAA,EAAM;AAClCF,QAAAA,QAAAA,CAASE,GAAAA,CAAAA,GAAOC,KAAAA;AAClB,MAAA;AACF,IAAA;AAEA,IAAA,OAAOH,QAAAA;AACT,EAAA;;;;;;;;AASUO,EAAAA,gBAAAA,CACRC,UACAX,aAAAA,EAC2B;AAC3B,IAAA,OAAOW,QAAAA,CAASC,IAAI,CAACb,MAAAA,KAAW,KAAKD,YAAAA,C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,MAAAA;AAAa,KAAA,GAAI;AACtD,GAAA;AAEA,EAAA,MAAMI,QAAAA,GAAW,MAAMH,MAAAA,CAAOI,aAAAA,CAAuC;IACnEC,KAAAA,EAAOjB,0BAAAA;IACPkB,SAAAA,EAAW;AAAEJ,MAAAA;AAAM,KAAA;IACnBxD,OAAAA,EAAS;MACP,YAAA,EAAc8C,OAAAA;MACd,cAAA,EAAgBC,SAAAA;MAChB,gBAAA,EAAkBC;AACpB;GACF,CAAA;AAEA,EAAA,MAAMa,GAAAA,GAAMJ,SAASjJ,IAAAA,EAAMsJ,eAAAA;AAC3B,EAAA,IAAI,CAACD,GAAAA,EAAK;AACR,IAAA,MAAM,IAAIlI,MAAM,qCAAA,CAAA;AAClB,EAAA;AACA,EAAA,OAAOkI,GAAAA;AACT;AA9CsBlB,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA","file":"chunk-3YG5JRS5.js","sourcesContent":["/**\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","/**\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"]}
|
|
1
|
+
{"version":3,"sources":["../src/export/index.ts","../src/export/base-exporter.ts","../src/export/pagination.ts","../src/export/csv.ts","../src/export/gateway-client.ts"],"names":["BaseModuleExporter","moduleKey","displayName","description","defaultExcludeFields","supportedProducts","modelName","filterFields","entity","excludeFields","fieldsToExclude","length","filtered","record","key","value","Object","entries","includes","filterFieldsMany","entities","map","paginate","queryFn","page","pageSize","skip","take","items","total","data","hasMore","nextCursor","String","undefined","fetchAll","fetchBatch","batchSize","allItems","cursor","batch","push","lastItem","id","transformForExport","validateOptions","options","validFormats","format","Error","join","getSupportedFormats","getMetadata","supportedFormats","PaginationService","params","start","end","paginatedItems","slice","totalCount","pageInfo","hasNextPage","hasPreviousPage","startCursor","endCursor","Math","min","calculatePagination","totalPages","ceil","startIndex","endIndex","currentPage","paginatedQuery","fetchFn","limit","initialCursor","totalYielded","item","collectPaginatedQuery","createPrismaFetchFn","_batchSize","calculateOffset","max","parseCursor","decoded","Buffer","from","toString","JSON","parse","createCursor","stringify","FORMULA_PREFIX_RE","sanitizeCSVCell","test","convertToCSV","delimiter","includeHeaders","flattenFields","maxFlattenDepth","flattenObject","obj","prefix","depth","result","newKey","Date","toISOString","Array","isArray","assign","flattenedRecords","allKeys","Set","keys","add","headers","sort","a","b","localeCompare","escapeCSV","sanitizedValue","replace","lines","row","header","parseCSV","csv","hasHeaders","split","filter","line","trim","parseLine","values","current","inQuotes","i","char","nextChar","dataLines","firstLine","firstRow","_","forEach","csvToJSON","pretty","parseOptions","getCSVHeaders","collectKeys","fullKey","estimateCSVSize","sampleSize","sample","sampleCSV","averageRowSize","headerSize","CREATE_EXPORT_JOB_MUTATION","triggerExportJob","serviceName","layer","actorId","actorType","workspaceId","name","entityTypes","includeMetadata","dateRangeStart","dateRangeEnd","client","GatewayClient","input","response","internalQuery","query","variables","job","createExportJob"],"mappings":";;;;AAAA,IAAA,cAAA,GAAA;;;;;;;;;;;;;ACoCO,IAAeA,qBAAf,MAAeA;EApCtB;;;;AAsCEC,EAAAA,SAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,WAAAA;;AAGAC,EAAAA,oBAAAA;;AAGAC,EAAAA,iBAAAA;;AAGUC,EAAAA,SAAAA;;;;;;;;;;;;;;;;;AA6BAC,EAAAA,YAAAA,CAAaC,QAAqCC,aAAAA,EAAmD;AAC7G,IAAA,MAAMC,eAAAA,GAAkBD,aAAAA,IAAiB,IAAA,CAAKL,oBAAAA,IAAwB,EAAA;AAEtE,IAAA,IAAIM,eAAAA,CAAgBC,WAAW,CAAA,EAAG;AAChC,MAAA,OAAOH,MAAAA;AACT,IAAA;AAEA,IAAA,MAAMI,WAAoC,EAAC;AAC3C,IAAA,MAAMC,MAAAA,GAASL,MAAAA;AAEf,IAAA,KAAA,MAAW,CAACM,GAAAA,EAAKC,KAAAA,KAAUC,MAAAA,CAAOC,OAAAA,CAAQJ,MAAAA,CAAAA,EAAS;AACjD,MAAA,IAAI,CAACH,eAAAA,CAAgBQ,QAAAA,CAASJ,GAAAA,CAAAA,EAAM;AAClCF,QAAAA,QAAAA,CAASE,GAAAA,CAAAA,GAAOC,KAAAA;AAClB,MAAA;AACF,IAAA;AAEA,IAAA,OAAOH,QAAAA;AACT,EAAA;;;;;;;;AASUO,EAAAA,gBAAAA,CACRC,UACAX,aAAAA,EAC2B;AAC3B,IAAA,OAAOW,QAAAA,CAASC,IAAI,CAACb,MAAAA,KAAW,KAAKD,YAAAA,CAAa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AAA;AAAa,KAAA,GAAI;AACtD,GAAA;AAEA,EAAA,MAAMI,QAAAA,GAAW,MAAMH,MAAAA,CAAOI,aAAAA,CAAuC;IACnEC,KAAAA,EAAOjB,0BAAAA;IACPkB,SAAAA,EAAW;AAAEJ,MAAAA;AAAM,KAAA;IACnBxD,OAAAA,EAAS;MACP,YAAA,EAAc8C,OAAAA;MACd,cAAA,EAAgBC,SAAAA;MAChB,gBAAA,EAAkBC;AACpB;GACF,CAAA;AAEA,EAAA,MAAMa,GAAAA,GAAMJ,SAASjJ,IAAAA,EAAMsJ,eAAAA;AAC3B,EAAA,IAAI,CAACD,GAAAA,EAAK;AACR,IAAA,MAAM,IAAIlI,MAAM,qCAAA,CAAA;AAClB,EAAA;AACA,EAAA,OAAOkI,GAAAA;AACT;AA9CsBlB,MAAAA,CAAAA,gBAAAA,EAAAA,kBAAAA,CAAAA","file":"chunk-VTJTAAXC.js","sourcesContent":["/**\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","/**\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"]}
|