@burdenoff/be-sdk 2026.1028.3 → 2026.1030.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai-credits/index.d.ts +1 -1
- package/dist/ai-credits/index.js +1 -1
- package/dist/{chunk-GKOAAC6D.js → chunk-3YG5JRS5.js} +3 -3
- package/dist/{chunk-GKOAAC6D.js.map → chunk-3YG5JRS5.js.map} +1 -1
- package/dist/{chunk-SC43G6HT.js → chunk-57GT6PJK.js} +3 -3
- package/dist/{chunk-SC43G6HT.js.map → chunk-57GT6PJK.js.map} +1 -1
- package/dist/{chunk-E36LPO3K.js → chunk-5ZP576CV.js} +3 -3
- package/dist/{chunk-E36LPO3K.js.map → chunk-5ZP576CV.js.map} +1 -1
- package/dist/{chunk-RM6AIMZT.js → chunk-6H4T2ADQ.js} +4 -3
- package/dist/chunk-6H4T2ADQ.js.map +1 -0
- package/dist/{chunk-5RBIDJBZ.js → chunk-JSEG3G5L.js} +91 -3
- package/dist/chunk-JSEG3G5L.js.map +1 -0
- package/dist/{chunk-FYFA7WAS.js → chunk-LCDECFJJ.js} +3 -3
- package/dist/{chunk-FYFA7WAS.js.map → chunk-LCDECFJJ.js.map} +1 -1
- package/dist/{chunk-PNWFTWBQ.js → chunk-OHUBPOZ6.js} +3 -3
- package/dist/{chunk-PNWFTWBQ.js.map → chunk-OHUBPOZ6.js.map} +1 -1
- package/dist/{chunk-WSAWJC4D.js → chunk-QCOC2SF3.js} +3 -3
- package/dist/{chunk-WSAWJC4D.js.map → chunk-QCOC2SF3.js.map} +1 -1
- package/dist/{chunk-QGADOWSG.js → chunk-ZWKJKL6Y.js} +23 -6
- package/dist/chunk-ZWKJKL6Y.js.map +1 -0
- package/dist/{client-7DW6EYSA.js → client-FUR7I6DB.js} +3 -3
- package/dist/{client-7DW6EYSA.js.map → client-FUR7I6DB.js.map} +1 -1
- package/dist/export/index.js +3 -3
- package/dist/files/index.js +1 -1
- package/dist/gateway/index.d.ts +1 -1
- package/dist/gateway/index.js +2 -2
- package/dist/{index-DieBtd0X.d.ts → index-CmfPeQza.d.ts} +21 -2
- package/dist/{index-Dcq8OduH.d.ts → index-szTxGaO6.d.ts} +4 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +14 -14
- package/dist/init/index.js +3 -3
- package/dist/prisma/index.js +2 -2
- package/dist/tags/index.js +1 -1
- package/dist/tracker/index.js +3 -3
- package/package.json +1 -1
- package/dist/chunk-5RBIDJBZ.js.map +0 -1
- package/dist/chunk-QGADOWSG.js.map +0 -1
- package/dist/chunk-RM6AIMZT.js.map +0 -1
|
@@ -43,6 +43,18 @@ interface WorkspaceQuotaUsage {
|
|
|
43
43
|
remaining: number | null;
|
|
44
44
|
assignments: number;
|
|
45
45
|
}
|
|
46
|
+
interface AiCreditAllowance {
|
|
47
|
+
quotaName: string;
|
|
48
|
+
allowed: boolean;
|
|
49
|
+
provisioned: boolean;
|
|
50
|
+
noLimit: boolean;
|
|
51
|
+
limitLeft: number | null;
|
|
52
|
+
}
|
|
53
|
+
interface AiCreditGate {
|
|
54
|
+
usage: WorkspaceQuotaUsage | null;
|
|
55
|
+
exhausted: boolean;
|
|
56
|
+
entitled: boolean;
|
|
57
|
+
}
|
|
46
58
|
interface AiCreditLogger {
|
|
47
59
|
info(message: string, ...args: unknown[]): void;
|
|
48
60
|
warn(message: string, ...args: unknown[]): void;
|
|
@@ -106,6 +118,11 @@ declare class AiCreditMeter {
|
|
|
106
118
|
quote(input: AiCreditQuoteInput): Promise<number | null>;
|
|
107
119
|
charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult>;
|
|
108
120
|
readUsage(workspaceId: string, quotaName?: string): Promise<WorkspaceQuotaUsage | null>;
|
|
121
|
+
checkAllowance(workspaceId: string, options?: {
|
|
122
|
+
amount?: number;
|
|
123
|
+
quotaName?: string;
|
|
124
|
+
}): Promise<AiCreditAllowance | null>;
|
|
125
|
+
readGate(workspaceId: string, quotaName?: string): Promise<AiCreditGate>;
|
|
109
126
|
private trackUsage;
|
|
110
127
|
private activityRequest;
|
|
111
128
|
private pricingRequest;
|
|
@@ -115,10 +132,12 @@ declare class AiCreditMeter {
|
|
|
115
132
|
}
|
|
116
133
|
|
|
117
134
|
declare const index_AI_CREDIT_MAX_TOKENS_PER_REPORT: typeof AI_CREDIT_MAX_TOKENS_PER_REPORT;
|
|
135
|
+
type index_AiCreditAllowance = AiCreditAllowance;
|
|
118
136
|
type index_AiCreditChargeGuard = AiCreditChargeGuard;
|
|
119
137
|
type index_AiCreditChargeInput = AiCreditChargeInput;
|
|
120
138
|
type index_AiCreditChargeResult = AiCreditChargeResult;
|
|
121
139
|
type index_AiCreditFetch = AiCreditFetch;
|
|
140
|
+
type index_AiCreditGate = AiCreditGate;
|
|
122
141
|
type index_AiCreditGuardVerdict = AiCreditGuardVerdict;
|
|
123
142
|
type index_AiCreditInputError = AiCreditInputError;
|
|
124
143
|
declare const index_AiCreditInputError: typeof AiCreditInputError;
|
|
@@ -141,7 +160,7 @@ declare const index_encodeAiCreditHashComponent: typeof encodeAiCreditHashCompon
|
|
|
141
160
|
declare const index_isAiCreditInputError: typeof isAiCreditInputError;
|
|
142
161
|
declare const index_validateAiTokenUsage: typeof validateAiTokenUsage;
|
|
143
162
|
declare namespace index {
|
|
144
|
-
export { index_AI_CREDIT_MAX_TOKENS_PER_REPORT as AI_CREDIT_MAX_TOKENS_PER_REPORT, type index_AiCreditChargeGuard as AiCreditChargeGuard, type index_AiCreditChargeInput as AiCreditChargeInput, type index_AiCreditChargeResult as AiCreditChargeResult, type index_AiCreditFetch as AiCreditFetch, type index_AiCreditGuardVerdict as AiCreditGuardVerdict, index_AiCreditInputError as AiCreditInputError, type index_AiCreditInputErrorCode as AiCreditInputErrorCode, type index_AiCreditLogger as AiCreditLogger, index_AiCreditMeter as AiCreditMeter, type index_AiCreditMeterOptions as AiCreditMeterOptions, type index_AiCreditPricingTransport as AiCreditPricingTransport, type index_AiCreditQuoteInput as AiCreditQuoteInput, type index_AiCreditSkipReason as AiCreditSkipReason, type index_AiTokenUsageReport as AiTokenUsageReport, type index_AiTokenUsageValidationError as AiTokenUsageValidationError, type index_AiTokenUsageViolation as AiTokenUsageViolation, type index_WorkspaceQuotaUsage as WorkspaceQuotaUsage, index_aiCreditIdempotencyHash as aiCreditIdempotencyHash, index_aiCreditQuotaName as aiCreditQuotaName, index_defaultAiCreditHashPrefix as defaultAiCreditHashPrefix, index_encodeAiCreditHashComponent as encodeAiCreditHashComponent, index_isAiCreditInputError as isAiCreditInputError, index_validateAiTokenUsage as validateAiTokenUsage };
|
|
163
|
+
export { index_AI_CREDIT_MAX_TOKENS_PER_REPORT as AI_CREDIT_MAX_TOKENS_PER_REPORT, type index_AiCreditAllowance as AiCreditAllowance, type index_AiCreditChargeGuard as AiCreditChargeGuard, type index_AiCreditChargeInput as AiCreditChargeInput, type index_AiCreditChargeResult as AiCreditChargeResult, type index_AiCreditFetch as AiCreditFetch, type index_AiCreditGate as AiCreditGate, type index_AiCreditGuardVerdict as AiCreditGuardVerdict, index_AiCreditInputError as AiCreditInputError, type index_AiCreditInputErrorCode as AiCreditInputErrorCode, type index_AiCreditLogger as AiCreditLogger, index_AiCreditMeter as AiCreditMeter, type index_AiCreditMeterOptions as AiCreditMeterOptions, type index_AiCreditPricingTransport as AiCreditPricingTransport, type index_AiCreditQuoteInput as AiCreditQuoteInput, type index_AiCreditSkipReason as AiCreditSkipReason, type index_AiTokenUsageReport as AiTokenUsageReport, type index_AiTokenUsageValidationError as AiTokenUsageValidationError, type index_AiTokenUsageViolation as AiTokenUsageViolation, type index_WorkspaceQuotaUsage as WorkspaceQuotaUsage, index_aiCreditIdempotencyHash as aiCreditIdempotencyHash, index_aiCreditQuotaName as aiCreditQuotaName, index_defaultAiCreditHashPrefix as defaultAiCreditHashPrefix, index_encodeAiCreditHashComponent as encodeAiCreditHashComponent, index_isAiCreditInputError as isAiCreditInputError, index_validateAiTokenUsage as validateAiTokenUsage };
|
|
145
164
|
}
|
|
146
165
|
|
|
147
|
-
export { AI_CREDIT_MAX_TOKENS_PER_REPORT as A, type WorkspaceQuotaUsage as W, type
|
|
166
|
+
export { AI_CREDIT_MAX_TOKENS_PER_REPORT as A, type WorkspaceQuotaUsage as W, type AiCreditAllowance as a, type AiCreditChargeGuard as b, type AiCreditChargeInput as c, type AiCreditChargeResult as d, type AiCreditFetch as e, type AiCreditGate as f, type AiCreditGuardVerdict as g, AiCreditInputError as h, index as i, type AiCreditInputErrorCode as j, type AiCreditLogger as k, AiCreditMeter as l, type AiCreditMeterOptions as m, type AiCreditPricingTransport as n, type AiCreditQuoteInput as o, type AiCreditSkipReason as p, type AiTokenUsageReport as q, type AiTokenUsageValidationError as r, type AiTokenUsageViolation as s, aiCreditIdempotencyHash as t, aiCreditQuotaName as u, defaultAiCreditHashPrefix as v, encodeAiCreditHashComponent as w, isAiCreditInputError as x, validateAiTokenUsage as y };
|
|
@@ -2,6 +2,7 @@ import { f as GatewayRequestHeaders } from './layer-Cv9vSwBx.js';
|
|
|
2
2
|
import { I as IGatewayClient, G as GatewayClientConfig, a as GraphQLRequestOptions, b as GraphQLResponse, c as ICircuitBreaker, d as GatewayClientHealth, C as CircuitBreakerStats, e as CircuitState, f as GatewayError, g as GatewayErrorType, h as GraphQLError, R as RequestContext } from './types-DgJ4lDYA.js';
|
|
3
3
|
import { i as index$1 } from './index-D3d2TAS-.js';
|
|
4
4
|
|
|
5
|
+
declare function isGatewayClientError(error: unknown): boolean;
|
|
5
6
|
declare class GatewayClient implements IGatewayClient {
|
|
6
7
|
private config;
|
|
7
8
|
private layerManager;
|
|
@@ -61,9 +62,10 @@ declare const index_RequestContext: typeof RequestContext;
|
|
|
61
62
|
declare const index_buildDelegatedGatewayHeaders: typeof buildDelegatedGatewayHeaders;
|
|
62
63
|
declare const index_createGatewayClient: typeof createGatewayClient;
|
|
63
64
|
declare const index_createGatewayClientFromEnv: typeof createGatewayClientFromEnv;
|
|
65
|
+
declare const index_isGatewayClientError: typeof isGatewayClientError;
|
|
64
66
|
declare const index_signServiceJwt: typeof signServiceJwt;
|
|
65
67
|
declare namespace index {
|
|
66
|
-
export { index_CircuitBreakerStats as CircuitBreakerStats, index_CircuitState as CircuitState, index_DELEGATED_AUTHORIZATION_HEADER as DELEGATED_AUTHORIZATION_HEADER, type index_DelegatedGatewayTransportInput as DelegatedGatewayTransportInput, index_GatewayClient as GatewayClient, index_GatewayClientConfig as GatewayClientConfig, index_GatewayClientHealth as GatewayClientHealth, index_GatewayError as GatewayError, index_GatewayErrorType as GatewayErrorType, index_GraphQLError as GraphQLError, index_GraphQLRequestOptions as GraphQLRequestOptions, index_GraphQLResponse as GraphQLResponse, index_ICircuitBreaker as ICircuitBreaker, index_IGatewayClient as IGatewayClient, index_RequestContext as RequestContext, index$1 as Security, index_buildDelegatedGatewayHeaders as buildDelegatedGatewayHeaders, index_createGatewayClient as createGatewayClient, index_createGatewayClientFromEnv as createGatewayClientFromEnv, index_signServiceJwt as signServiceJwt };
|
|
68
|
+
export { index_CircuitBreakerStats as CircuitBreakerStats, index_CircuitState as CircuitState, index_DELEGATED_AUTHORIZATION_HEADER as DELEGATED_AUTHORIZATION_HEADER, type index_DelegatedGatewayTransportInput as DelegatedGatewayTransportInput, index_GatewayClient as GatewayClient, index_GatewayClientConfig as GatewayClientConfig, index_GatewayClientHealth as GatewayClientHealth, index_GatewayError as GatewayError, index_GatewayErrorType as GatewayErrorType, index_GraphQLError as GraphQLError, index_GraphQLRequestOptions as GraphQLRequestOptions, index_GraphQLResponse as GraphQLResponse, index_ICircuitBreaker as ICircuitBreaker, index_IGatewayClient as IGatewayClient, index_RequestContext as RequestContext, index$1 as Security, index_buildDelegatedGatewayHeaders as buildDelegatedGatewayHeaders, index_createGatewayClient as createGatewayClient, index_createGatewayClientFromEnv as createGatewayClientFromEnv, index_isGatewayClientError as isGatewayClientError, index_signServiceJwt as signServiceJwt };
|
|
67
69
|
}
|
|
68
70
|
|
|
69
|
-
export { DELEGATED_AUTHORIZATION_HEADER as D, GatewayClient as G, type DelegatedGatewayTransportInput as a, buildDelegatedGatewayHeaders as b, createGatewayClient as c, createGatewayClientFromEnv as d, index as i, signServiceJwt as s };
|
|
71
|
+
export { DELEGATED_AUTHORIZATION_HEADER as D, GatewayClient as G, type DelegatedGatewayTransportInput as a, buildDelegatedGatewayHeaders as b, createGatewayClient as c, createGatewayClientFromEnv as d, isGatewayClientError as e, index as i, signServiceJwt as s };
|
package/dist/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export { BillingPlanTransport, PlanTier, RESOURCE_CAP_DEFAULTS, ResourceCap, Res
|
|
|
22
22
|
export { i as Sharing } from './index-kssw5ziY.js';
|
|
23
23
|
export { i as Tags } from './index-aHtYvc3i.js';
|
|
24
24
|
export { i as Files } from './index-CbgWNcus.js';
|
|
25
|
-
export { i as AiCredits } from './index-
|
|
25
|
+
export { i as AiCredits } from './index-CmfPeQza.js';
|
|
26
26
|
export { i as Cache } from './index-BvkVcW8I.js';
|
|
27
27
|
export { i as Middleware } from './index-DSOpj8DI.js';
|
|
28
28
|
export { i as Observability } from './index-4gKQKZ2B.js';
|
|
@@ -36,7 +36,7 @@ export { i as DataLoader } from './index-DW9q22GH.js';
|
|
|
36
36
|
export { i as Instrumentation } from './index-Coua7_P7.js';
|
|
37
37
|
export { i as Layer } from './index-ffmipXSA.js';
|
|
38
38
|
export { i as Crypto } from './index-e_18DzAg.js';
|
|
39
|
-
export { i as Gateway } from './index-
|
|
39
|
+
export { i as Gateway } from './index-szTxGaO6.js';
|
|
40
40
|
export { i as FeatureFlags } from './index-B2YkcG0J.js';
|
|
41
41
|
export { i as Captcha, R as RecaptchaVerifyOptions, a as RecaptchaVerifyResult, b as isCaptchaEnabled, v as verifyCaptcha, c as verifyCaptchaIfEnabled } from './index-B70b5mYS.js';
|
|
42
42
|
export { i as Platform } from './index-D8HGwglK.js';
|
package/dist/index.js
CHANGED
|
@@ -1,32 +1,32 @@
|
|
|
1
1
|
export { NAME_MAX_LENGTH, NAME_MIN_LENGTH, RbacCoverageError, USERNAME_MAX_LENGTH, USERNAME_MIN_LENGTH, validation_exports as Validation, analyzeRbacCoverage, assertRbacCoverage, lengthInCodePoints, validateName, validateUserFields, validateUsername } from './chunk-WVOW3CJR.js';
|
|
2
2
|
export { sharing_exports as Sharing } from './chunk-DS3YMJ4X.js';
|
|
3
|
-
export { tags_exports as Tags } from './chunk-
|
|
3
|
+
export { tags_exports as Tags } from './chunk-OHUBPOZ6.js';
|
|
4
4
|
export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-VXVLKRU6.js';
|
|
5
|
-
import { ActivityModule, UsageModule, TrackerModule } from './chunk-
|
|
6
|
-
export { ActivityModule, TrackerModule, UsageModule } from './chunk-
|
|
7
|
-
|
|
5
|
+
import { ActivityModule, UsageModule, TrackerModule } from './chunk-57GT6PJK.js';
|
|
6
|
+
export { ActivityModule, TrackerModule, UsageModule } from './chunk-57GT6PJK.js';
|
|
7
|
+
import './chunk-TANAOLAV.js';
|
|
8
|
+
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
8
9
|
import { TenantNotificationsModule, NotificationsModule } from './chunk-INAZ3PKF.js';
|
|
9
10
|
export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-INAZ3PKF.js';
|
|
10
11
|
export { observability_exports as Observability } from './chunk-VAT66FJA.js';
|
|
11
12
|
export { platform_exports as Platform } from './chunk-XXNT4VCM.js';
|
|
12
|
-
export { prisma_exports as Prisma } from './chunk-
|
|
13
|
+
export { prisma_exports as Prisma } from './chunk-QCOC2SF3.js';
|
|
14
|
+
import './chunk-E4QNLVY4.js';
|
|
13
15
|
export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
|
|
14
16
|
import { RBACModule } from './chunk-PQGMZH6K.js';
|
|
15
17
|
export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-PQGMZH6K.js';
|
|
16
|
-
export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-MZCBEJ67.js';
|
|
17
|
-
import './chunk-TANAOLAV.js';
|
|
18
|
-
import './chunk-E4QNLVY4.js';
|
|
19
18
|
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
|
|
19
|
+
export { init_exports as Init } from './chunk-5ZP576CV.js';
|
|
20
|
+
export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-MZCBEJ67.js';
|
|
20
21
|
export { instrumentation_exports as Instrumentation } from './chunk-E5DTAGCA.js';
|
|
21
22
|
import './chunk-AWPNRV3L.js';
|
|
22
|
-
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
23
23
|
export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
|
|
24
|
-
export { export_exports as Export } from './chunk-
|
|
24
|
+
export { export_exports as Export } from './chunk-3YG5JRS5.js';
|
|
25
25
|
export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
|
|
26
|
-
export { files_exports as Files } from './chunk-
|
|
27
|
-
export { gateway_exports as Gateway } from './chunk-
|
|
26
|
+
export { files_exports as Files } from './chunk-LCDECFJJ.js';
|
|
27
|
+
export { gateway_exports as Gateway } from './chunk-6H4T2ADQ.js';
|
|
28
28
|
import './chunk-NBN52AEM.js';
|
|
29
|
-
import { GatewayClient } from './chunk-
|
|
29
|
+
import { GatewayClient } from './chunk-ZWKJKL6Y.js';
|
|
30
30
|
import './chunk-FZRODKIN.js';
|
|
31
31
|
export { layer_exports as Layer } from './chunk-STWFX5E2.js';
|
|
32
32
|
import './chunk-VFCMR5GX.js';
|
|
@@ -44,7 +44,7 @@ import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
|
|
|
44
44
|
export { graphql_exports as GraphQL } from './chunk-NGAGKLAM.js';
|
|
45
45
|
import './chunk-MWPYA2HD.js';
|
|
46
46
|
import './chunk-ENEDTQET.js';
|
|
47
|
-
export { ai_credits_exports as AiCredits } from './chunk-
|
|
47
|
+
export { ai_credits_exports as AiCredits } from './chunk-JSEG3G5L.js';
|
|
48
48
|
import { AuthModule } from './chunk-GJWQK3IU.js';
|
|
49
49
|
export { AuthModule } from './chunk-GJWQK3IU.js';
|
|
50
50
|
export { utils_exports as Utils } from './chunk-B7I4TABG.js';
|
package/dist/init/index.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
export { getSDKState, initializeBurdenoffSDK, isSDKInitialized, resetSDK } from '../chunk-
|
|
1
|
+
export { getSDKState, initializeBurdenoffSDK, isSDKInitialized, resetSDK } from '../chunk-5ZP576CV.js';
|
|
2
2
|
import '../chunk-MZCBEJ67.js';
|
|
3
3
|
import '../chunk-AWPNRV3L.js';
|
|
4
|
-
import '../chunk-
|
|
4
|
+
import '../chunk-6H4T2ADQ.js';
|
|
5
5
|
import '../chunk-NBN52AEM.js';
|
|
6
|
-
import '../chunk-
|
|
6
|
+
import '../chunk-ZWKJKL6Y.js';
|
|
7
7
|
import '../chunk-FZRODKIN.js';
|
|
8
8
|
import '../chunk-STWFX5E2.js';
|
|
9
9
|
import '../chunk-VFCMR5GX.js';
|
package/dist/prisma/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-
|
|
2
|
-
import '../chunk-OBBCR6WY.js';
|
|
1
|
+
export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-QCOC2SF3.js';
|
|
3
2
|
export { addWorkspaceExtension, buildTransactionContextStatement, defaultWorkspaceExtensionConfig, getCallerTransaction, getScopedWorkspaceContext, getWorkspaceContext, injectCreateFields, injectWhereWorkspaceId, maybeSetRlsGuc, maybeTagConnection, resetCallerTransactionStateForTests, runOperationInCallerTransaction, runOperationWithRlsGuc, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-E4QNLVY4.js';
|
|
3
|
+
import '../chunk-OBBCR6WY.js';
|
|
4
4
|
export { PrismaClientWrapper, configurePrismaLogging, createConnectionPool, createPrismaAdapter, createPrismaClient, ensureServiceApplicationName, installAcquireRetry, isTransientAcquireError } from '../chunk-K52ICDCP.js';
|
|
5
5
|
import '../chunk-TX2GDIWP.js';
|
|
6
6
|
import '../chunk-SIAOIYHW.js';
|
package/dist/tags/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, TagsGatewayAdapter, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey } from '../chunk-
|
|
1
|
+
export { ENTITY_TAGS_GRAPHQL_CODES, EntityTagsError, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, TagsGatewayAdapter, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey } from '../chunk-OHUBPOZ6.js';
|
|
2
2
|
import '../chunk-RU266375.js';
|
|
3
3
|
import '../chunk-XE4OXN2W.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
package/dist/tracker/index.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, TrackerModule, UsageMetricType, trackAgentActivity } from '../chunk-
|
|
2
|
-
import '../chunk-INAZ3PKF.js';
|
|
3
|
-
import '../chunk-PQGMZH6K.js';
|
|
1
|
+
export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, TrackerModule, UsageMetricType, trackAgentActivity } from '../chunk-57GT6PJK.js';
|
|
4
2
|
export { AI_ASSISTANT_ACTOR_ORIGIN, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackOperation, trackerStub } from '../chunk-TANAOLAV.js';
|
|
3
|
+
import '../chunk-INAZ3PKF.js';
|
|
5
4
|
import '../chunk-E4QNLVY4.js';
|
|
5
|
+
import '../chunk-PQGMZH6K.js';
|
|
6
6
|
import '../chunk-QGBXVNRM.js';
|
|
7
7
|
import '../chunk-5CAFHK2Z.js';
|
|
8
8
|
import '../chunk-RU266375.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.
|
|
3
|
+
"version": "2026.1030.1",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/ai-credits/index.ts","../src/ai-credits/validation.ts","../src/ai-credits/errors.ts","../src/ai-credits/meter.ts"],"names":["AI_CREDIT_MAX_TOKENS_PER_REPORT","blank","value","trim","length","validateAiTokenUsage","report","maxTokensPerReport","sessionId","messageId","model","inputTokens","outputTokens","counts","cacheReadTokens","cacheWriteTokens","code","message","some","count","Number","isSafeInteger","reduce","sum","aiCreditQuotaName","productId","id","Error","defaultAiCreditHashPrefix","encodeAiCreditHashComponent","replaceAll","aiCreditIdempotencyHash","prefix","head","AiCreditInputError","graphqlCode","name","isAiCreditInputError","error","DEFAULT_REQUEST_TIMEOUT_MS","QUOTE_AI_CREDITS_QUERY","QUOTE_AI_CREDITS_WITH_CACHE_QUERY","CACHE_PRICING_CAPABILITY_QUERY","TRACK_USAGE_MUTATION","WORKSPACE_QUOTA_ASSIGNMENTS_QUERY","errorMessage","String","requireNonEmpty","field","trimmed","internalServiceHeaders","token","process","env","AiCreditMeter","quotaName","hashPrefix","serviceName","activityGatewayUrl","billingGatewayUrl","pricingOption","fetchImpl","requestTimeoutMs","guard","log","pricing","options","undefined","pricingClient","fetch","url","init","logger","sdkLogger","hashFor","quote","input","warn","client","getPricingClient","hasCacheCounts","priceCache","supportsCachePricing","response","crossLayerQuery","pricingRequest","query","variables","errors","map","join","credits","data","quoteAiCredits","isFinite","charge","workspaceId","invalid","hash","logFields","skipped","reason","detail","status","verdict","allow","trackUsage","amount","description","userId","metadata","info","readUsage","activityRequest","rows","workspaceQuotaAssignments","filter","row","isActive","used","noLimit","limit","remaining","Math","max","assignments","record","workspace","controller","AbortController","timeout","setTimeout","abort","method","headers","resolveServiceName","body","JSON","stringify","signal","ok","text","catch","statusText","slice","result","json","clearTimeout","skipRetry","skipCircuitBreaker","aiCacheTokenPricingSupported","option","gateway","identity","GatewayClient","layer","serviceIdentity","crossLayerGatewayUrl","enableLogging"],"mappings":";;;;AAAA,IAAA,kBAAA,GAAA;;;;;;;;;;;;;;ACWO,IAAMA,+BAAAA,GAAkC;AAiB/C,SAASC,MAAMC,KAAAA,EAAgC;AAC7C,EAAA,OAAO,OAAOA,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAMC,IAAAA,GAAOC,MAAAA,KAAW,CAAA;AAC9D;AAFSH,MAAAA,CAAAA,KAAAA,EAAAA,OAAAA,CAAAA;AAaF,SAASI,oBAAAA,CACdC,MAAAA,EAEAC,kBAAAA,GAA6BP,+BAAAA,EAA+B;AAE5D,EAAA,MAAM,EAAEQ,SAAAA,EAAWC,SAAAA,EAAWC,KAAAA,EAAOC,WAAAA,EAAaC,cAAY,GAAKN,MAAAA;AAGnE,EAAA,MAAMO,MAAAA,GAAS;AAACF,IAAAA,WAAAA;AAAaC,IAAAA,YAAAA;AAAcN,IAAAA,MAAAA,CAAOQ,eAAAA,IAAmB,CAAA;AAAGR,IAAAA,MAAAA,CAAOS,gBAAAA,IAAoB;;AAEnG,EAAA,IAAId,KAAAA,CAAMO,SAAAA,CAAAA,EAAY,OAAO;IAAEQ,IAAAA,EAAM,qBAAA;IAAuBC,OAAAA,EAAS;AAAyB,GAAA;AAC9F,EAAA,IAAIhB,KAAAA,CAAMQ,SAAAA,CAAAA,EAAY,OAAO;IAAEO,IAAAA,EAAM,qBAAA;IAAuBC,OAAAA,EAAS;AAAyB,GAAA;AAC9F,EAAA,IAAIhB,KAAAA,CAAMS,KAAAA,CAAAA,EAAQ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KlB,kBAAAA,EAAkB;AACxC,MAAA,OAAO,IAAIiB,QAAQE,aAAAA,CAAc;;QAE/BC,KAAAA,EAAO,QAAA;QACPlG,WAAAA,EAAagG,QAAAA;QACbG,eAAAA,EAAiBH,QAAAA;QACjBI,oBAAAA,EAAsBvF,GAAAA;AACtB4D,QAAAA,OAAAA,EAAS,IAAA,CAAKpE,gBAAAA;QACdgG,aAAAA,EAAe1G,OAAAA,CAAQC,GAAAA,CAAI,UAAA,CAAA,KAAgB;OAC7C,CAAA;IACF,CAAA,GAAA;AACA,IAAA,IAAA,CAAKY,OAAAA,GAAU;AAAEK,MAAAA,GAAAA;AAAKQ,MAAAA;AAAO,KAAA;AAE7BA,IAAAA,MAAAA,CAAOgE,MAAM,MAAA;AACX,MAAA,IAAI,IAAA,CAAK7E,OAAAA,EAASa,MAAAA,KAAWA,MAAAA,OAAab,OAAAA,GAAU,IAAA;IACtD,CAAA,CAAA;AACA,IAAA,OAAOa,MAAAA;AACT,EAAA;AACF","file":"chunk-5RBIDJBZ.js","sourcesContent":["/**\n * @burdenoff/be-sdk/ai-credits\n *\n * Shared cost-weighted, idempotent AI-credit metering for assistant turns:\n * billing prices the turn (`quoteAiCredits`), wspace-activity-svc records it on\n * the workspace quota (`trackUsage`, deduped by `<prefix>:<session>:<message>`).\n *\n * - {@link AiCreditMeter} — `charge`, `quote`, `readUsage`, `hashFor`.\n * - {@link validateAiTokenUsage}, {@link aiCreditIdempotencyHash},\n * {@link aiCreditQuotaName} — the pure rules, for products' own tests and resolvers.\n *\n * @example\n * ```ts\n * import { AiCreditMeter, isAiCreditInputError } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({ productId: 'healthybowl', hashPrefix: 'hb-assistant' });\n * const result = await meter.charge({ workspaceId, userId, sessionId, messageId, model, inputTokens, outputTokens });\n * ```\n */\n\nexport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n encodeAiCreditHashComponent,\n validateAiTokenUsage,\n type AiTokenUsageValidationError,\n type AiTokenUsageViolation,\n} from './validation.js';\n\nexport { AiCreditInputError, isAiCreditInputError, type AiCreditInputErrorCode } from './errors.js';\n\nexport { AiCreditMeter, type AiCreditMeterOptions } from './meter.js';\n\nexport type {\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGuardVerdict,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n AiTokenUsageReport,\n WorkspaceQuotaUsage,\n} from './types.js';\n","/**\n * Pure rules for AI-credit metering: report validation, quota naming and the\n * idempotency hash. Dependency-free so products can unit-test against them.\n */\nimport type { AiTokenUsageReport } from './types.js';\n\n/**\n * Sanity ceiling for one turn's token counts. Real turns stay far below it even\n * with a large context window; credits price at roughly one credit per input\n * token, so an unbounded count would be an unbounded charge.\n */\nexport const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2_000_000;\n\n/** Stable machine-readable reasons a report is rejected. */\nexport type AiTokenUsageViolation =\n | 'SESSION_ID_REQUIRED'\n | 'MESSAGE_ID_REQUIRED'\n | 'MODEL_REQUIRED'\n | 'TOKEN_COUNTS_NOT_INTEGERS'\n | 'TOKEN_COUNTS_NEGATIVE'\n | 'TOKEN_COUNTS_EXCEED_MAXIMUM';\n\nexport interface AiTokenUsageValidationError {\n code: AiTokenUsageViolation;\n /** Operator-readable reason. Products usually map it to their i18n key by `code`. */\n message: string;\n}\n\nfunction blank(value: string | null | undefined): boolean {\n return typeof value !== 'string' || value.trim().length === 0;\n}\n\n/**\n * Validate a reported turn. Returns null when it is acceptable, otherwise the\n * first violation. Does not throw, so callers choose the error type (VC raises\n * an i18n'd BAD_USER_INPUT, HB a client-facing error).\n *\n * `messageId` is required, not optional: without it the idempotency hash\n * collapses to the session and only the first turn of a conversation would ever\n * be charged. `model` is required because it selects the per-token price.\n */\nexport function validateAiTokenUsage(\n report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> &\n Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>,\n maxTokensPerReport: number = AI_CREDIT_MAX_TOKENS_PER_REPORT\n): AiTokenUsageValidationError | null {\n const { sessionId, messageId, model, inputTokens, outputTokens } = report;\n // Cache counts are optional; an omitted/null count is zero. They are checked and\n // summed with the ordinary counts, because they are priced too.\n const counts = [inputTokens, outputTokens, report.cacheReadTokens ?? 0, report.cacheWriteTokens ?? 0];\n\n if (blank(sessionId)) return { code: 'SESSION_ID_REQUIRED', message: 'sessionId is required.' };\n if (blank(messageId)) return { code: 'MESSAGE_ID_REQUIRED', message: 'messageId is required.' };\n if (blank(model)) return { code: 'MODEL_REQUIRED', message: 'model is required.' };\n if (counts.some((count) => !Number.isSafeInteger(count))) {\n return { code: 'TOKEN_COUNTS_NOT_INTEGERS', message: 'Token counts must be integers.' };\n }\n if (counts.some((count) => count < 0)) {\n return { code: 'TOKEN_COUNTS_NEGATIVE', message: 'Token counts must be non-negative.' };\n }\n if (counts.reduce((sum, count) => sum + count, 0) > maxTokensPerReport) {\n return {\n code: 'TOKEN_COUNTS_EXCEED_MAXIMUM',\n message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`,\n };\n }\n return null;\n}\n\n/**\n * The quota a product's AI credits draw from: `<productId>.ai.credits`\n * (`vibecontrols.ai.credits`, `healthybowl.ai.credits`, …). Must match what\n * billing seeds exactly — a name mismatch reads as \"not provisioned\".\n */\nexport function aiCreditQuotaName(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('aiCreditQuotaName requires a productId');\n return `${id}.ai.credits`;\n}\n\n/** Default hash prefix for a product: `<productId>:aicredit`. */\nexport function defaultAiCreditHashPrefix(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('defaultAiCreditHashPrefix requires a productId');\n return `${id}:aicredit`;\n}\n\n/**\n * Make a hash component unambiguous when joined with `:`. Ids are `ID!` and may\n * contain colons, so raw joining would let `(\"a:b\",\"c\")` and `(\"a\",\"b:c\")`\n * collide — and activity's unique `usage_records.hash` would then drop the second,\n * genuinely different turn as a replay. `%` is escaped first so the escape itself\n * cannot collide. A no-op for ids containing neither character (uuids, `msg_…`),\n * so existing hashes are reproduced byte-for-byte.\n */\nexport function encodeAiCreditHashComponent(value: string): string {\n return value.replaceAll('%', '%25').replaceAll(':', '%3A');\n}\n\n/**\n * Idempotency hash for one turn: `<prefix>:<sessionId>:<messageId>`.\n *\n * activity-svc's unique index is on `hash` ALONE, shared by every product, so\n * the prefix must be product-namespaced. Products that already write a different\n * prefix must keep passing it (`aicredit` for VibeControls, `hb-assistant` for\n * HealthyBowl) — changing a prefix re-hashes every in-flight turn, so a client\n * retry across the deploy would be charged twice.\n */\nexport function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string {\n const head = prefix.trim();\n if (!head) throw new Error('aiCreditIdempotencyHash requires a prefix');\n if (blank(sessionId) || blank(messageId)) {\n throw new Error('aiCreditIdempotencyHash requires a sessionId and a messageId');\n }\n return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;\n}\n","/**\n * Errors raised by the AI-credit meter. Only caller mistakes throw; billing and\n * recording failures are returned as a skipped charge (see `AiCreditMeter.charge`).\n */\nimport type { AiTokenUsageViolation } from './validation.js';\n\nexport type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED';\n\n/** A malformed report or missing workspace context. Map it to BAD_USER_INPUT. */\nexport class AiCreditInputError extends Error {\n readonly code: AiCreditInputErrorCode;\n /** GraphQL error code products should surface. */\n readonly graphqlCode = 'BAD_USER_INPUT';\n\n constructor(code: AiCreditInputErrorCode, message: string) {\n super(message);\n this.name = 'AiCreditInputError';\n this.code = code;\n }\n}\n\nexport function isAiCreditInputError(error: unknown): error is AiCreditInputError {\n return error instanceof AiCreditInputError;\n}\n","/**\n * AiCreditMeter — cost-weighted, idempotent AI-credit charging for an assistant turn.\n *\n * VibeControls (`utils/usage-billing.ts` + `modules/aicredit`) and HealthyBowl\n * (`utils/ai-credit-usage.ts` + `HealthyBowlAiCreditProvider`) each carried their\n * own copy of this path. This is the shared version, built on the path that is\n * proven to record in prod:\n *\n * 1. **Price** — `quoteAiCredits(model, inputTokens, outputTokens[, cacheReadTokens,\n * cacheWriteTokens])` on global-billing-svc, cross-layer through the be-sdk `GatewayClient`\n * (`GLOBAL_PUBLIC_GATEWAY_URL`, which resolves to the peer VPC's internal ALB\n * over the Route53 private zone). The amount is always computed server-side\n * from billing's per-model prices; a client never supplies it.\n * 2. **Record** — wspace-activity-svc `trackUsage` on the workspace's\n * `WorkspaceQuotaAssignment`, same-layer through the wspace INTERNAL gateway\n * (`WSPACE_INT_GATEWAY_URL`) with `x-workspace-id`. Activity resolves the\n * assignment itself and dedupes on the unique `usage_records.hash`, so a\n * replayed report for the same session + message is a no-op charge.\n *\n * Contract:\n * - {@link AiCreditMeter.charge} validates first and THROWS\n * {@link AiCreditInputError} for a malformed report (a caller bug worth\n * surfacing). After that it never throws: the user already has the answer, so a\n * metering failure must not become a user-visible error. Every un-charged\n * outcome is returned as `status: 'skipped'` with a reason AND logged.\n * - A null quote skips the charge: under-charging during an outage is\n * recoverable, charging an invented amount is not.\n * - Recording only counts as success when activity answers `trackUsage: true`.\n *\n * The meter is a METER, not a gate. Products that need a pre-flight gate keep a\n * `@usage(checkQuota: true, trackUsage: false)` field (VC `checkAiCredits`); the\n * charging field must carry NO `@usage(trackUsage)` directive, or the turn is\n * charged twice.\n *\n * @example\n * ```ts\n * import { AiCreditMeter } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({\n * productId: 'vibecontrols',\n * serviceName: 'wspace-vibecontrols-svc',\n * hashPrefix: 'aicredit', // VC's existing prefix — never change a live prefix\n * });\n *\n * const result = await meter.charge({\n * workspaceId: requireWorkspaceId(ctx.workspace?.id),\n * userId: ctx.actor?.id,\n * sessionId: input.sessionId,\n * messageId: input.messageId,\n * model: input.model,\n * inputTokens: input.inputTokens,\n * outputTokens: input.outputTokens,\n * });\n * ```\n */\nimport type { GraphQLRequestOptions } from '../gateway/types.js';\nimport { logger as sdkLogger } from '../logger/index.js';\n\nimport { AiCreditInputError } from './errors.js';\nimport type {\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n WorkspaceQuotaUsage,\n} from './types.js';\nimport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n validateAiTokenUsage,\n} from './validation.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\nconst QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)\n}`;\n\nconst QUOTE_AI_CREDITS_WITH_CACHE_QUERY = `query AiCreditMeterQuoteWithCache($model: String!, $inputTokens: Int!, $outputTokens: Int!, $cacheReadTokens: Int, $cacheWriteTokens: Int) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens, cacheReadTokens: $cacheReadTokens, cacheWriteTokens: $cacheWriteTokens)\n}`;\n\nconst CACHE_PRICING_CAPABILITY_QUERY = `query AiCreditMeterCachePricingSupported {\n aiCacheTokenPricingSupported\n}`;\n\nconst TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n}`;\n\nconst WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {\n workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }\n}`;\n\nexport interface AiCreditMeterOptions {\n /** Product id stamped on usage records, e.g. `vibecontrols`. */\n productId: string;\n /** This service's name; sent as the service identity. Default `SERVICE_IDENTITY` / `SERVICE_NAME` env. */\n serviceName?: string;\n /** Quota to charge. Default `<productId>.ai.credits`. */\n quotaName?: string;\n /**\n * Idempotency-hash prefix. Default `<productId>:aicredit`. A product that already\n * records under another prefix MUST keep it (see {@link aiCreditIdempotencyHash}).\n */\n hashPrefix?: string;\n /** wspace internal gateway URL. Default `WSPACE_INT_GATEWAY_URL` env (read per call). */\n activityGatewayUrl?: string;\n /** Cross-layer global gateway URL for pricing. Default `GLOBAL_PUBLIC_GATEWAY_URL` env (read per call). */\n billingGatewayUrl?: string;\n /**\n * Pricing transport, or a factory for one. Default: a lazily constructed be-sdk\n * `GatewayClient` bound to {@link billingGatewayUrl}, rebuilt if the URL changes.\n */\n pricingClient?:\n | AiCreditPricingTransport\n | ((url: string) => AiCreditPricingTransport | Promise<AiCreditPricingTransport>);\n /** `fetch` for the activity-svc calls. Default: the global `fetch`. */\n fetch?: AiCreditFetch;\n /** Per-request timeout. Default 5s. */\n requestTimeoutMs?: number;\n /** Per-report token ceiling. Default {@link AI_CREDIT_MAX_TOKENS_PER_REPORT}. */\n maxTokensPerReport?: number;\n /** Optional pre-charge hook (e.g. a report-rate ceiling). */\n guard?: AiCreditChargeGuard;\n /** Logger. Default the be-sdk logger. */\n logger?: AiCreditLogger;\n}\n\ninterface GraphQLBody<T> {\n data?: T | null;\n errors?: { message: string }[] | null;\n}\n\ninterface AssignmentRow {\n quotaName: string;\n used: number;\n limit: number | null;\n noLimit: boolean;\n isActive: boolean;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction requireNonEmpty(value: string | undefined, field: string): string {\n const trimmed = value?.trim() ?? '';\n if (!trimmed) throw new Error(`AiCreditMeter: ${field} is required`);\n return trimmed;\n}\n\n/** Same-layer auth header the wspace internal gateway expects from in-cluster callers. */\nfunction internalServiceHeaders(): Record<string, string> {\n const token = process.env['TRUSTED_GATEWAY_TOKEN'] || process.env['INTERNAL_SERVICE_TOKEN'];\n return token ? { 'x-internal-service-token': token } : {};\n}\n\nexport class AiCreditMeter {\n readonly productId: string;\n readonly quotaName: string;\n readonly hashPrefix: string;\n private readonly serviceName: string | undefined;\n private readonly activityGatewayUrl: string | undefined;\n private readonly billingGatewayUrl: string | undefined;\n private readonly pricingOption: AiCreditMeterOptions['pricingClient'];\n private readonly fetchImpl: AiCreditFetch;\n private readonly requestTimeoutMs: number;\n private readonly maxTokensPerReport: number;\n private readonly guard: AiCreditChargeGuard | undefined;\n private readonly log: AiCreditLogger;\n private pricing: { url: string; client: Promise<AiCreditPricingTransport> } | null = null;\n\n constructor(options: AiCreditMeterOptions) {\n this.productId = requireNonEmpty(options.productId, 'productId');\n this.quotaName = options.quotaName?.trim() || aiCreditQuotaName(this.productId);\n this.hashPrefix = options.hashPrefix?.trim() || defaultAiCreditHashPrefix(this.productId);\n this.serviceName = options.serviceName?.trim() || undefined;\n this.activityGatewayUrl = options.activityGatewayUrl?.trim() || undefined;\n this.billingGatewayUrl = options.billingGatewayUrl?.trim() || undefined;\n this.pricingOption = options.pricingClient;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {\n throw new Error('AiCreditMeter: requestTimeoutMs must be a positive integer');\n }\n this.maxTokensPerReport = options.maxTokensPerReport ?? AI_CREDIT_MAX_TOKENS_PER_REPORT;\n if (!Number.isSafeInteger(this.maxTokensPerReport) || this.maxTokensPerReport <= 0) {\n throw new Error('AiCreditMeter: maxTokensPerReport must be a positive integer');\n }\n this.guard = options.guard;\n this.log = options.logger ?? sdkLogger;\n }\n\n /** The idempotency hash this meter records a turn under. */\n hashFor(sessionId: string, messageId: string): string {\n return aiCreditIdempotencyHash(this.hashPrefix, sessionId, messageId);\n }\n\n /**\n * Server-side price of one model call in credits, from billing's per-model\n * token table. Returns null — after logging why — when it cannot be priced.\n *\n * When the turn reports cache counts, billing is first asked whether it prices\n * them (`aiCacheTokenPricingSupported`). If it does, the cache counts are priced\n * with its cache-token prices; if it does not (an older billing, or the probe\n * fails), the turn is priced on input/output alone. The answer is not cached,\n * so a billing rollback is picked up on the next report.\n */\n async quote(input: AiCreditQuoteInput): Promise<number | null> {\n const url = this.billingGatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL']?.trim();\n if (!url) {\n this.log.warn('[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits', {\n productId: this.productId,\n model: input.model,\n });\n return null;\n }\n try {\n const client = await this.getPricingClient(url);\n const hasCacheCounts = input.cacheReadTokens != null || input.cacheWriteTokens != null;\n const priceCache = hasCacheCounts && (await this.supportsCachePricing(client, input.model));\n const response = await client.crossLayerQuery<{ quoteAiCredits?: number | null }>({\n ...this.pricingRequest(),\n query: priceCache ? QUOTE_AI_CREDITS_WITH_CACHE_QUERY : QUOTE_AI_CREDITS_QUERY,\n variables: {\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(priceCache\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n },\n });\n if (response.errors?.length) {\n throw new Error(response.errors.map((error) => error.message).join(', '));\n }\n const credits = response.data?.quoteAiCredits;\n if (typeof credits !== 'number' || !Number.isFinite(credits) || credits < 0) {\n throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);\n }\n return credits;\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to quote AI credits; skipping charge', {\n productId: this.productId,\n model: input.model,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Validate, price and record one completed assistant turn. See the module\n * header for the contract: throws only {@link AiCreditInputError}.\n */\n async charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);\n if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);\n\n const hash = this.hashFor(input.sessionId, input.messageId);\n const logFields = {\n productId: this.productId,\n quotaName: this.quotaName,\n workspaceId,\n sessionId: input.sessionId,\n messageId: input.messageId,\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n };\n const skipped = (reason: AiCreditSkipReason, credits: number | null, detail?: string): AiCreditChargeResult => {\n this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, { ...logFields, credits, detail });\n return { status: 'skipped', reason, credits, hash, quotaName: this.quotaName, ...(detail ? { detail } : {}) };\n };\n\n if (this.guard) {\n try {\n const verdict = await this.guard({ ...input, workspaceId });\n if (!verdict.allow) return skipped('GUARD_REFUSED', null, verdict.detail);\n } catch (error) {\n // Fail open: a guard's infrastructure blip must not silently stop metering.\n this.log.warn('[AiCreditMeter] charge guard threw; charging anyway', {\n ...logFields,\n error: errorMessage(error),\n });\n }\n }\n\n const credits = await this.quote(input);\n if (credits === null) return skipped('NOT_PRICED', null);\n if (credits <= 0) return skipped('ZERO_COST', credits);\n\n try {\n await this.trackUsage({\n workspaceId,\n amount: credits,\n description: input.description?.trim() || `AI credits for session ${input.sessionId}`,\n userId: input.userId ?? undefined,\n hash,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n messageId: input.messageId,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(input.cacheReadTokens != null || input.cacheWriteTokens != null\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n credits,\n ...input.metadata,\n },\n });\n } catch (error) {\n return skipped('RECORD_FAILED', credits, errorMessage(error));\n }\n\n this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {\n ...logFields,\n credits,\n });\n return { status: 'charged', credits, hash, quotaName: this.quotaName };\n }\n\n /**\n * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the\n * charge lands on and the gateway's `@usage` check reads. All active rows are\n * summed, because a workspace can hold several (plan + add-ons, or duplicate\n * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.\n *\n * Returns null (never throws) when activity is unreachable or no assignment\n * exists, so a screen can show \"not provisioned\" instead of a confident zero.\n */\n async readUsage(workspaceId: string, quotaName: string = this.quotaName): Promise<WorkspaceQuotaUsage | null> {\n try {\n const data = await this.activityRequest<{ workspaceQuotaAssignments?: AssignmentRow[] | null }>(\n workspaceId,\n WORKSPACE_QUOTA_ASSIGNMENTS_QUERY,\n { workspaceId: workspaceId.trim() }\n );\n const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);\n if (rows.length === 0) return null;\n const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);\n const noLimit = rows.some((row) => row.noLimit);\n const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);\n return {\n quotaName,\n used,\n limit,\n noLimit,\n remaining: limit === null ? null : Math.max(limit - used, 0),\n assignments: rows.length,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to read workspace quota usage', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n private async trackUsage(record: {\n workspaceId: string;\n amount: number;\n description: string;\n userId: string | undefined;\n hash: string;\n metadata: Record<string, unknown>;\n }): Promise<void> {\n const data = await this.activityRequest<{ trackUsage?: boolean | null }>(record.workspaceId, TRACK_USAGE_MUTATION, {\n input: {\n // Sent in the input AND as x-workspace-id: activity takes the workspace from request\n // context, and the @rbac directive resolves input.workspaceId.\n workspaceId: record.workspaceId,\n quotaName: this.quotaName,\n productId: this.productId,\n amount: record.amount,\n description: record.description,\n userId: record.userId,\n hash: record.hash,\n metadata: record.metadata,\n },\n });\n if (data.trackUsage !== true) {\n throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);\n }\n }\n\n private async activityRequest<T>(workspaceId: string, query: string, variables: Record<string, unknown>): Promise<T> {\n const url = this.activityGatewayUrl ?? process.env['WSPACE_INT_GATEWAY_URL']?.trim();\n if (!url) throw new Error('WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc');\n const workspace = workspaceId.trim();\n if (!workspace) throw new Error('workspaceId is required');\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-actor-type': 'service',\n 'x-actor-id': this.resolveServiceName(),\n ...internalServiceHeaders(),\n 'x-workspace-id': workspace,\n },\n body: JSON.stringify({ query, variables }),\n signal: controller.signal,\n });\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);\n }\n const result = (await response.json()) as GraphQLBody<T>;\n if (result.errors?.length) {\n throw new Error(result.errors.map((error) => error.message).join(', '));\n }\n if (!result.data) throw new Error('activity response did not include data');\n return result.data;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n /** Options shared by every pricing call. */\n private pricingRequest(): Pick<GraphQLRequestOptions, 'headers' | 'timeout' | 'skipRetry' | 'skipCircuitBreaker'> {\n return {\n // Only the actor type: the signed service JWT is the identity. An x-actor-id on a\n // service token is read as \"on behalf of\" and downgrades the actor.\n headers: { 'x-actor-type': 'service' },\n timeout: this.requestTimeoutMs,\n skipRetry: true,\n skipCircuitBreaker: true,\n };\n }\n\n /** Whether billing prices cache counts. Any failure reads as \"no\" and falls back to input/output. */\n private async supportsCachePricing(client: AiCreditPricingTransport, model: string): Promise<boolean> {\n try {\n const response = await client.crossLayerQuery<{ aiCacheTokenPricingSupported?: boolean | null }>({\n ...this.pricingRequest(),\n query: CACHE_PRICING_CAPABILITY_QUERY,\n variables: {},\n });\n if (response.data?.aiCacheTokenPricingSupported === true) return true;\n } catch {\n // Logged below; the turn is still priced on input/output.\n }\n this.log.warn('[AiCreditMeter] billing does not price cache tokens; quoting input/output only', {\n productId: this.productId,\n model,\n });\n return false;\n }\n\n private resolveServiceName(): string {\n return (\n this.serviceName ||\n process.env['SERVICE_IDENTITY'] ||\n process.env['SERVICE_NAME'] ||\n `wspace-${this.productId}-svc`\n );\n }\n\n private getPricingClient(url: string): Promise<AiCreditPricingTransport> {\n // Rebuilt when the URL changes, so a client bound to a stale URL cannot keep failing.\n if (this.pricing && this.pricing.url === url) return this.pricing.client;\n const option = this.pricingOption;\n const client = (async (): Promise<AiCreditPricingTransport> => {\n if (option && typeof option === 'function') return option(url);\n if (option) return option;\n const gateway = await import('../gateway/client.js');\n const identity = this.resolveServiceName();\n return new gateway.GatewayClient({\n // This service's OWN layer; the be-sdk signs the service JWT because the call leaves it.\n layer: 'wspace',\n serviceName: identity,\n serviceIdentity: identity,\n crossLayerGatewayUrl: url,\n timeout: this.requestTimeoutMs,\n enableLogging: process.env['NODE_ENV'] !== 'production',\n });\n })();\n this.pricing = { url, client };\n // A failed construction must not be cached forever.\n client.catch(() => {\n if (this.pricing?.client === client) this.pricing = null;\n });\n return client;\n }\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
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","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","error","GatewayError","type","GatewayErrorType","GRAPHQL_ERROR","CIRCUIT_OPEN","calculateRetryDelay","attempt","Math","min","initialDelay","pow","backoffMultiplier","maxDelay","logRetryAttempt","maxAttempts","delay","settings","skipCircuitBreaker","skipRetry","lastError","result","executeRequest","String","sleep","UNKNOWN_ERROR","buildRequestHeaders","cfHeaders","ContextManager","getCfAccessHeaders","assign","entries","undefined","toString","cfCookie","existing","split","some","c","handleGraphQLErrors","duration","errors","errorMessages","map","e","join","graphqlErrors","handleFetchError","name","TIMEOUT_ERROR","cause","NETWORK_ERROR","serviceActorId","serviceJwt","signServiceJwt","getLayer","body","JSON","stringify","variables","controller","AbortController","timeoutId","setTimeout","abort","response","fetch","method","signal","clearTimeout","ok","json","every","status","statusText","statusCode","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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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\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 if (!options.skipCircuitBreaker) {\n circuitBreaker.recordFailure();\n }\n\n if (!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 throw new GatewayError(\n `HTTP ${response.status}: ${response.statusText}`,\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 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/gateway/index.ts","../src/gateway/delegated-transport.ts"],"names":["DELEGATED_AUTHORIZATION_HEADER","JWT_SEGMENT","isCompactJwt","token","segments","split","length","every","segment","test","buildDelegatedGatewayHeaders","input","appAsUserToken","Error","headers","workspaceId","undefined","trim"],"mappings":";;;;;;;AAAA,IAAA,eAAA,GAAA;;;;;;;;;;;;;;;ACiBO,IAAMA,8BAAAA,GAAiC;AAS9C,IAAMC,WAAAA,GAAc,kBAAA;AAEpB,SAASC,aAAaC,KAAAA,EAAa;AACjC,EAAA,MAAMC,QAAAA,GAAWD,KAAAA,CAAME,KAAAA,CAAM,GAAA,CAAA;AAC7B,EAAA,OAAOD,QAAAA,CAASE,MAAAA,KAAW,CAAA,IAAKF,QAAAA,CAASG,KAAAA,CAAM,CAACC,OAAAA,KAAYP,WAAAA,CAAYQ,IAAAA,CAAKD,OAAAA,CAAAA,CAAAA;AAC/E;AAHSN,MAAAA,CAAAA,YAAAA,EAAAA,cAAAA,CAAAA;AAYF,SAASQ,6BAA6BC,KAAAA,EAAqC;AAChF,EAAA,MAAMR,QAAQQ,KAAAA,CAAMC,cAAAA;AACpB,EAAA,IAAI,OAAOT,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAMG,MAAAA,KAAW,CAAA,IAAKH,KAAAA,CAAMG,MAAAA,GAAS,IAAA,IAAQ,CAACJ,YAAAA,CAAaC,KAAAA,CAAAA,EAAQ;AAClG,IAAA,MAAM,IAAIU,MAAM,kEAAA,CAAA;AAClB,EAAA;AACA,EAAA,MAAMC,OAAAA,GAAiC;IACrC,CAACd,8BAAAA,GAAiC,CAAA,OAAA,EAAUG,KAAAA,CAAAA;AAC9C,GAAA;AACA,EAAA,IAAIQ,KAAAA,CAAMI,gBAAgBC,MAAAA,EAAW;AACnC,IAAA,MAAMD,WAAAA,GAAcJ,KAAAA,CAAMI,WAAAA,CAAYE,IAAAA,EAAI;AAC1C,IAAA,IAAIF,WAAAA,CAAYT,MAAAA,KAAW,CAAA,IAAKS,WAAAA,KAAgBJ,MAAMI,WAAAA,EAAa;AACjE,MAAA,MAAM,IAAIF,MAAM,+DAAA,CAAA;AAClB,IAAA;AACAC,IAAAA,OAAAA,CAAQ,gBAAA,CAAA,GAAoBC,WAAAA;AAC9B,EAAA;AACA,EAAA,OAAOD,OAAAA;AACT;AAhBgBJ,MAAAA,CAAAA,4BAAAA,EAAAA,8BAAAA,CAAAA","file":"chunk-RM6AIMZT.js","sourcesContent":["/**\n * Gateway Module\n *\n * Provides unified gateway client for layer-aware M2M communication\n * with circuit breaker and retry logic.\n *\n * @module gateway\n * @category Gateway\n *\n * @example\n * ```typescript\n * import { GatewayClient, createGatewayClientFromEnv } from '@burdenoff/be-sdk/gateway';\n *\n * // Create from environment variables\n * const client = createGatewayClientFromEnv();\n *\n * // Or create manually\n * const client = new GatewayClient({\n * layer: 'wspace',\n * serviceName: 'wspace-tags-svc',\n * });\n *\n * // Internal call (same layer, uses int-gateway with bypass)\n * const internalResult = await client.internalQuery({\n * query: `query { getTag(id: \"123\") { id name } }`,\n * });\n *\n * // Cross-layer call (via public gateway)\n * const crossLayerResult = await client.crossLayerQuery({\n * query: `query { getCurrentUser { id email } }`,\n * });\n * ```\n */\n\n// Client exports\nexport { GatewayClient, createGatewayClient, createGatewayClientFromEnv } from './client.js';\n\n// Service-JWT minting for cross-layer M2M auth. Exposed so non-GatewayClient\n// callers (e.g. bespoke graphql-request clients) can authenticate identically.\nexport { signServiceJwt } from './service-jwt.js';\n\n// Delegated internal-gateway transport (BOFF-9962): call as an agent acting\n// for a user by presenting a verified app_as_user token, never raw headers.\nexport {\n buildDelegatedGatewayHeaders,\n DELEGATED_AUTHORIZATION_HEADER,\n type DelegatedGatewayTransportInput,\n} from './delegated-transport.js';\n\n// Type exports\nexport {\n CircuitState,\n GatewayErrorType,\n GatewayError,\n type GatewayClientConfig,\n type GraphQLRequestOptions,\n type GraphQLResponse,\n type GraphQLError,\n type IGatewayClient,\n type ICircuitBreaker,\n type CircuitBreakerStats,\n type GatewayClientHealth,\n type RequestContext,\n} from './types.js';\n\n// Gateway-side security plugin stack (for public gateways).\n// Imported by consumers as `@burdenoff/be-sdk/gateway/security` — this\n// re-export lets `@burdenoff/be-sdk/gateway` also resolve the namespace.\nexport * as Security from './security/index.js';\n","/**\n * Delegated gateway transport (BOFF-9962).\n *\n * A service that must call the platform as \"agent X acting for user Y\" does\n * not set actor or consent headers itself: internal gateways strip those.\n * Instead it obtains a short-lived `app_as_user` token from global-auth\n * (`issueAppAsUserTokenInternal`) and presents it on the internal gateway's\n * `x-delegated-authorization` header. The gateway verifies the signature,\n * checks revocation and the grant's workspace bounds, and only then forwards\n * the represented user as the actor together with `x-verified-delegation`.\n *\n * @module gateway/delegated-transport\n */\n\nimport type { GatewayRequestHeaders } from '../types/layer.js';\n\n/** Header an internal gateway reads a delegated `app_as_user` bearer from. */\nexport const DELEGATED_AUTHORIZATION_HEADER = 'x-delegated-authorization';\n\nexport interface DelegatedGatewayTransportInput {\n /** Signed `app_as_user` access token issued by global-auth. */\n appAsUserToken: string;\n /** Workspace the call targets; must be inside the grant's workspace bounds. */\n workspaceId?: string;\n}\n\nconst JWT_SEGMENT = /^[A-Za-z0-9_-]+$/;\n\nfunction isCompactJwt(token: string): boolean {\n const segments = token.split('.');\n return segments.length === 3 && segments.every((segment) => JWT_SEGMENT.test(segment));\n}\n\n/**\n * Builds the request headers for a delegated internal-gateway call, for use as\n * `GatewayClient.internalQuery({ query, headers })`.\n *\n * @throws Error when the token is not a compact JWS (so a malformed value can\n * never be smuggled into a header) or the workspace id is blank.\n */\nexport function buildDelegatedGatewayHeaders(input: DelegatedGatewayTransportInput): GatewayRequestHeaders {\n const token = input.appAsUserToken;\n if (typeof token !== 'string' || token.length === 0 || token.length > 8192 || !isCompactJwt(token)) {\n throw new Error('Delegated gateway transport requires a compact app_as_user token');\n }\n const headers: GatewayRequestHeaders = {\n [DELEGATED_AUTHORIZATION_HEADER]: `Bearer ${token}`,\n };\n if (input.workspaceId !== undefined) {\n const workspaceId = input.workspaceId.trim();\n if (workspaceId.length === 0 || workspaceId !== input.workspaceId) {\n throw new Error('Delegated gateway transport requires a non-blank workspace id');\n }\n headers['x-workspace-id'] = workspaceId;\n }\n return headers;\n}\n"]}
|