@icanbwell/bwell-sdk-ts 2.0.0-alpha.0-rc.1752772167 → 2.0.0-alpha.0-rc.1753298141

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.
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * This file is automatically generated. Please do not edit this file directly.
3
3
  */
4
- export declare const VERSION = "2.0.0-alpha.0-rc.1752772167";
4
+ export declare const VERSION = "2.0.0-alpha.0-rc.1753298141";
@@ -1,4 +1,4 @@
1
1
  /**
2
2
  * This file is automatically generated. Please do not edit this file directly.
3
3
  */
4
- export const VERSION = "2.0.0-alpha.0-rc.1752772167";
4
+ export const VERSION = "2.0.0-alpha.0-rc.1753298141";
@@ -1,7 +1,10 @@
1
- import type { GetAllergyIntoleranceGroupsQueryResults, GetAllergyIntolerancesQueryResults, GetCarePlanGroupsQueryResults, GetConditionGroupsQueryResults, GetDiagnosticReportLabGroupsQueryResults, GetEncountersGroupQueryResults, GetImmunizationGroupsQueryResults, GetLabGroupsQueryResults, GetMedicationGroupsQueryResults, GetProcedureGroupsQueryResults, GetVitalSignGroupsQueryResults } from "../../../graphql/operations/types.js";
1
+ import type { GetAllergyIntoleranceGroupsQueryResults, GetAllergyIntolerancesQueryResults, GetCarePlanGroupsQueryResults, GetConditionGroupsQueryResults, GetDiagnosticReportLabGroupsQueryResults, GetEncountersGroupQueryResults, GetHealthSummaryQueryResults, GetImmunizationGroupsQueryResults, GetLabGroupsQueryResults, GetMedicationGroupsQueryResults, GetProcedureGroupsQueryResults, GetVitalSignGroupsQueryResults } from "../../../graphql/operations/types.js";
2
2
  import type { BWellQueryResult } from "../../../results/index.js";
3
3
  import type { BaseManagerError } from "../errors.js";
4
4
  import type { AllergyIntoleranceGroupsRequest, CarePlanGroupsRequest, ConditionGroupsRequest, DiagnosticReportLabGroupsRequest, EncounterGroupsRequest, HealthDataRequest, ImmunizationGroupsRequest, LabGroupsRequest, MedicationGroupsRequest, ProcedureGroupsRequest, VitalSignGroupsRequest } from "./health-data-request.js";
5
+ type HealthSummaryResultsType = GetHealthSummaryQueryResults["getHealthSummary"];
6
+ export interface HealthSummaryResults extends HealthSummaryResultsType {
7
+ }
5
8
  export type AllergyIntolerancesResults = GetAllergyIntolerancesQueryResults["allergyIntolerances"];
6
9
  type AllergyIntolerancesGroupsResultsType = GetAllergyIntoleranceGroupsQueryResults["getAllergyIntoleranceGroups"];
7
10
  export interface AllergyIntolerancesGroupsResults extends AllergyIntolerancesGroupsResultsType {
@@ -37,6 +40,12 @@ export interface MedicationGroupsResults extends MedicationGroupsResultsType {
37
40
  * The HealthManager interface provides methods for retrieving health care records.
38
41
  */
39
42
  export interface HealthManager {
43
+ /**
44
+ * Retrieve a summary view of current health care records by category. This view includes counts for AllergyIntolerance, CarePlan, Condition, Encounter, Immunization, Procedure, Vital Sign, Medication Statement, and Lab resources.
45
+ *
46
+ * @returns {Promise<BWellQueryResult<HealthSummaryResults>>} A promise resolving to An object which based off of generated ResourceGroups representing an aggregation of AllergyIntolerance, CarePlan, Condition, Encounter, Immunization, Procedure, MedicationStatement, Observation (Vital Sign and Lab) resources.
47
+ */
48
+ getHealthSummary(): Promise<BWellQueryResult<HealthSummaryResults, BaseManagerError>>;
40
49
  getAllergyIntolerances(request?: HealthDataRequest): Promise<BWellQueryResult<AllergyIntolerancesResults, BaseManagerError>>;
41
50
  /**
42
51
  * Retrieves a list of AllergyIntoleranceGroup resources.
@@ -2,4 +2,4 @@ export { HealthDataRequestInput, AllergyIntolerancesRequest, AllergyIntoleranceG
2
2
  export { MedicationPricingRequest, MedicationPricingRequestInput, } from "./medication-pricing-request.js";
3
3
  export { MedicationKnowledgeRequest, MedicationKnowledgeRequestInput, } from "./medication-knowledge-request.js";
4
4
  export { LabKnowledgeRequest, LabKnowledgeRequestInput, } from "./lab-knowledge-request.js";
5
- export { AllergyIntolerancesResults, AllergyIntolerancesGroupsResults, ConditionGroupsResults, LabGroupsResults, CarePlanGroupsResults, EncounterGroupsResults, ImmunizationGroupsResults, ProcedureGroupsResults, VitalSignGroupsResults, MedicationGroupsResults, HealthManager, DiagnosticReportLabGroupsResults, } from "./health-manager.js";
5
+ export { HealthSummaryResults, AllergyIntolerancesResults, AllergyIntolerancesGroupsResults, ConditionGroupsResults, LabGroupsResults, CarePlanGroupsResults, EncounterGroupsResults, ImmunizationGroupsResults, ProcedureGroupsResults, VitalSignGroupsResults, MedicationGroupsResults, HealthManager, DiagnosticReportLabGroupsResults, } from "./health-manager.js";
@@ -11,7 +11,7 @@ import { GraphQLClient } from "graphql-request";
11
11
  import { getSdk } from "../../../graphql/index.js";
12
12
  export function graphQLSDKFactory(endpoint, tokenManager, language) {
13
13
  let requestMiddleware = undefined;
14
- if (tokenManager) {
14
+ if (tokenManager !== undefined) {
15
15
  requestMiddleware = createAuthMiddleware(tokenManager);
16
16
  }
17
17
  const headers = {};
@@ -9,6 +9,7 @@ import type { GraphQLSdk } from "../graphql-sdk/index.js";
9
9
  export declare class GraphQLHealthManager extends GraphQLManager implements HealthManager {
10
10
  #private;
11
11
  constructor(sdk: GraphQLSdk, loggerProvider?: LoggerProvider);
12
+ getHealthSummary(): Promise<BWellQueryResult<health.HealthSummaryResults, BaseManagerError>>;
12
13
  getAllergyIntolerances(request?: health.HealthDataRequest): Promise<BWellQueryResult<health.AllergyIntolerancesResults>>;
13
14
  getAllergyIntoleranceGroups(request?: health.AllergyIntoleranceGroupsRequest): Promise<BWellQueryResult<health.AllergyIntolerancesGroupsResults, ValidationError | BaseManagerError>>;
14
15
  getConditionGroups(request?: health.ConditionGroupsRequest): Promise<BWellQueryResult<health.ConditionGroupsResults, ValidationError | BaseManagerError>>;
@@ -32,19 +32,21 @@ export class GraphQLHealthManager extends GraphQLManager {
32
32
  __classPrivateFieldSet(this, _GraphQLHealthManager_sdk, sdk, "f");
33
33
  __classPrivateFieldSet(this, _GraphQLHealthManager_logger, loggerProvider.getLogger("GraphQLHealthManager"), "f");
34
34
  }
35
- // public async getHealthSummary(): Promise<
36
- // BWellQueryResult<health.HealthSummaryResults, BaseManagerError>
37
- // > {
38
- // this.#logger.verbose("calling getHealthSummary...");
39
- // const result = await this.handleQuery(this.#sdk.GetHealthSummary());
40
- // this.#logger.verbose("getHealthSummary complete");
41
- // if (result.hasError()) {
42
- // this.#logger.error("getHealthSummary failed", result.error);
43
- // } else {
44
- // this.#logger.info("successfully called getHealthSummary");
45
- // }
46
- // return new BWellQueryResult(result.data?.getHealthSummary, result.error);
47
- // }
35
+ getHealthSummary() {
36
+ return __awaiter(this, void 0, void 0, function* () {
37
+ var _a;
38
+ __classPrivateFieldGet(this, _GraphQLHealthManager_logger, "f").verbose("calling getHealthSummary...");
39
+ const result = yield this.handleQuery(__classPrivateFieldGet(this, _GraphQLHealthManager_sdk, "f").GetHealthSummary());
40
+ __classPrivateFieldGet(this, _GraphQLHealthManager_logger, "f").verbose("getHealthSummary complete");
41
+ if (result.hasError()) {
42
+ __classPrivateFieldGet(this, _GraphQLHealthManager_logger, "f").error("getHealthSummary failed", result.error);
43
+ }
44
+ else {
45
+ __classPrivateFieldGet(this, _GraphQLHealthManager_logger, "f").info("successfully called getHealthSummary");
46
+ }
47
+ return new BWellQueryResult((_a = result.data) === null || _a === void 0 ? void 0 : _a.getHealthSummary, result.error);
48
+ });
49
+ }
48
50
  getAllergyIntolerances(request) {
49
51
  return __awaiter(this, void 0, void 0, function* () {
50
52
  var _a;
@@ -3,7 +3,7 @@ import { HealthManager } from "../api/base/health-data/index.js";
3
3
  import type { AuthTokens, CreateGuestAccessTokenResults } from "../api/base/identity/index.js";
4
4
  import { type Credentials } from "../auth/index.js";
5
5
  import { type BWellConfig } from "../config/index.js";
6
- import { type AuthenticationError, type InvalidClientKeyError, type InvalidTokenError, type OperationOutcomeError } from "../errors/index.js";
6
+ import { BWellError, type AuthenticationError, type InvalidClientKeyError, type InvalidTokenError, type OperationOutcomeError } from "../errors/index.js";
7
7
  import { ConnectionManager, HealthSpaceManager, QuestionnaireManager, UserManager } from "../index.js";
8
8
  import { BWellTransactionResult } from "../results/index.js";
9
9
  export { AuthTokens } from "../api/base/identity/index.js";
@@ -71,6 +71,7 @@ export declare class BWellSDK {
71
71
  * @returns {Promise<BWellTransactionResult<null, OperationOutcomeError | InvalidTokenError>>}
72
72
  */
73
73
  setAuthTokens(authTokens: AuthTokens): Promise<BWellTransactionResult<null, OperationOutcomeError | InvalidTokenError>>;
74
+ authenticateFromStorage(): Promise<BWellTransactionResult<null, AuthenticationError | InvalidTokenError | BWellError>>;
74
75
  /**
75
76
  * Creates a set of guest access tokens (access, id, and refresh)
76
77
  * @returns A promise that resolves to a BWellTransactionResult containing the guest access tokens or an error.
@@ -26,7 +26,7 @@ import { BWellError, } from "../errors/index.js";
26
26
  import { LoggerFactory, } from "../logger/index.js";
27
27
  import { BWellTransactionResult } from "../results/index.js";
28
28
  import { OpenTelemetry } from "../telemetry/index.js";
29
- import { JWTTokenManager, } from "../tokens/index.js";
29
+ import { JWTTokenManager, loadAuthTokens, } from "../tokens/index.js";
30
30
  import { isNotNullOrUndefined, parseUserFromIdToken } from "../utils/index.js";
31
31
  /**
32
32
  * The BWell SDK is the main entry point for the SDK.
@@ -155,6 +155,36 @@ export class BWellSDK {
155
155
  return BWellTransactionResult.success(null);
156
156
  });
157
157
  }
158
+ authenticateFromStorage() {
159
+ return __awaiter(this, void 0, void 0, function* () {
160
+ if (__classPrivateFieldGet(this, _BWellSDK_config, "f").tokenStorage === undefined) {
161
+ return BWellTransactionResult.failure(new BWellError("tokenStorage not provided in config"));
162
+ }
163
+ __classPrivateFieldGet(this, _BWellSDK_logger, "f").debug("Loading credentials from token storage");
164
+ const storageTokensResult = yield loadAuthTokens(__classPrivateFieldGet(this, _BWellSDK_config, "f").tokenStorage);
165
+ if (storageTokensResult.failure()) {
166
+ __classPrivateFieldGet(this, _BWellSDK_logger, "f").warn("Error loading credentials from token storage");
167
+ return storageTokensResult.intoFailure();
168
+ }
169
+ __classPrivateFieldGet(this, _BWellSDK_logger, "f").info("Successfully loaded credentials from token storage");
170
+ const authTokens = storageTokensResult.data();
171
+ const bootsrapResult = yield __classPrivateFieldGet(this, _BWellSDK_instances, "m", _BWellSDK_bootstrapAuth).call(this, authTokens);
172
+ if (bootsrapResult.failure()) {
173
+ return bootsrapResult.intoFailure();
174
+ }
175
+ if (__classPrivateFieldGet(this, _BWellSDK_tokenManager, "f") === undefined) {
176
+ // Token manager is set by #bootstrapAuth so it shouldn't ever be undefined
177
+ // here. We can't imply that through TS though so we need to presence check
178
+ /* istanbul ignore next */
179
+ throw new Error("TokenManager not set");
180
+ }
181
+ const refreshResult = yield __classPrivateFieldGet(this, _BWellSDK_tokenManager, "f").refreshAccessToken();
182
+ if (refreshResult.failure()) {
183
+ return refreshResult.intoFailure();
184
+ }
185
+ return BWellTransactionResult.success(null);
186
+ });
187
+ }
158
188
  /**
159
189
  * Creates a set of guest access tokens (access, id, and refresh)
160
190
  * @returns A promise that resolves to a BWellTransactionResult containing the guest access tokens or an error.
@@ -48,6 +48,7 @@ export declare const GetCarePlanGroupsDocument = "\n query getCarePlanGroups(
48
48
  export declare const GetConditionGroupsDocument = "\n query getConditionGroups($request: ConditionGroupQueryRequest) {\n getConditionGroups(request: $request) {\n paging_info {\n ...PagingFields\n }\n resources {\n id\n name\n coding {\n ...CodingFields\n }\n references\n recordedDate\n source\n sourceDisplay\n }\n }\n}\n \n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n \n\n fragment CodingFields on Coding {\n system\n code\n display\n}\n ";
49
49
  export declare const GetDiagnosticReportLabGroupsDocument = "\n query getDiagnosticReportLabGroups($request: DiagnosticReportLabGroupQueryRequest) {\n getDiagnosticReportLabGroups(request: $request) {\n resources {\n id\n effectiveDateTime\n issued\n name\n performer\n references\n source\n sourceDisplay\n coding {\n ...CodingFields\n }\n }\n paging_info {\n ...PagingFields\n }\n }\n}\n \n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n ";
50
50
  export declare const GetEncountersGroupDocument = "\n query getEncountersGroup($request: EncounterGroupQueryRequest) {\n getEncounterGroups(request: $request) {\n paging_info {\n ...PagingFields\n }\n resources {\n id\n name\n references\n class {\n ...CodingFields\n }\n type {\n ...CodingFields\n }\n participant\n coding {\n ...CodingFields\n }\n date\n source\n sourceDisplay\n }\n }\n}\n \n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n \n\n fragment CodingFields on Coding {\n system\n code\n display\n}\n ";
51
+ export declare const GetHealthSummaryDocument = "\n query GetHealthSummary {\n getHealthSummary {\n resources {\n category\n total\n }\n }\n}\n ";
51
52
  export declare const GetImmunizationGroupsDocument = "\n query getImmunizationGroups($request: ImmunizationGroupQueryRequest) {\n getImmunizationGroups(request: $request) {\n paging_info {\n ...PagingFields\n }\n resources {\n id\n name\n references\n coding {\n ...CodingFields\n }\n occurrenceDateTime\n source\n sourceDisplay\n }\n }\n}\n \n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n \n\n fragment CodingFields on Coding {\n system\n code\n display\n}\n ";
52
53
  export declare const GetProcedureGroupsDocument = "\n query getProcedureGroups($request: ProcedureGroupQueryRequest) {\n getProcedureGroups(request: $request) {\n paging_info {\n ...PagingFields\n }\n resources {\n id\n name\n references\n coding {\n ...CodingFields\n }\n performer\n performedDate\n source\n sourceDisplay\n }\n }\n}\n \n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n \n\n fragment CodingFields on Coding {\n system\n code\n display\n}\n ";
53
54
  export declare const GetVitalSignGroupsDocument = "\n query getVitalSignGroups($request: VitalSignGroupQueryRequest) {\n getVitalSignGroups(request: $request) {\n paging_info {\n ...PagingFields\n }\n resources {\n id\n name\n source\n sourceDisplay\n category {\n ...CodeableConceptFields\n }\n coding {\n ...CodingFields\n }\n effectiveDateTime\n interpretation {\n ...CodeableConceptFields\n }\n value {\n ...ValueFields\n }\n referenceRange {\n ...ReferenceRangeFields\n }\n component {\n ...ComponentFields\n }\n references\n effectiveDateTime\n }\n }\n}\n \n fragment PagingFields on PagingResults {\n page_number\n page_size\n total_pages\n total_items\n}\n \n\n fragment CodeableConceptFields on CodeableConcept {\n text\n coding {\n ...CodingFields\n }\n}\n \n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment ValueFields on Value {\n valueQuantity {\n ...QuantityFields\n }\n valueCodeableConcept {\n ...CodeableConceptFields\n }\n valueString\n valueBoolean\n valueInteger\n valueRatio {\n ...RatioFields\n }\n valueRange {\n ...RangeFields\n }\n valueTime\n valueDateTime\n valuePeriod {\n ...PeriodFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment CodeableConceptFields on CodeableConcept {\n text\n coding {\n ...CodingFields\n }\n}\n \n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment RatioFields on Ratio {\n numerator {\n ...QuantityFields\n }\n denominator {\n ...QuantityFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment RangeFields on Range {\n low {\n ...QuantityFields\n }\n high {\n ...QuantityFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment PeriodFields on Period {\n start\n end\n}\n \n\n fragment ReferenceRangeFields on ReferenceRange {\n low {\n ...QuantityFields\n }\n high {\n ...QuantityFields\n }\n text\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment ComponentFields on Component {\n code {\n ...CodeableConceptFields\n }\n value {\n ...ValueFields\n }\n referenceRange {\n ...ReferenceRangeFields\n }\n interpretation {\n ...CodeableConceptFields\n }\n dataAbsentReason {\n ...CodeableConceptFields\n }\n}\n \n fragment CodeableConceptFields on CodeableConcept {\n text\n coding {\n ...CodingFields\n }\n}\n \n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment ValueFields on Value {\n valueQuantity {\n ...QuantityFields\n }\n valueCodeableConcept {\n ...CodeableConceptFields\n }\n valueString\n valueBoolean\n valueInteger\n valueRatio {\n ...RatioFields\n }\n valueRange {\n ...RangeFields\n }\n valueTime\n valueDateTime\n valuePeriod {\n ...PeriodFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment CodeableConceptFields on CodeableConcept {\n text\n coding {\n ...CodingFields\n }\n}\n \n fragment CodingFields on Coding {\n system\n code\n display\n}\n \n\n fragment RatioFields on Ratio {\n numerator {\n ...QuantityFields\n }\n denominator {\n ...QuantityFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment RangeFields on Range {\n low {\n ...QuantityFields\n }\n high {\n ...QuantityFields\n }\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n \n\n fragment PeriodFields on Period {\n start\n end\n}\n \n\n fragment ReferenceRangeFields on ReferenceRange {\n low {\n ...QuantityFields\n }\n high {\n ...QuantityFields\n }\n text\n}\n \n fragment QuantityFields on Quantity {\n value\n unit\n code\n comparator\n system\n}\n ";
@@ -148,6 +149,13 @@ export declare function getSdk(client: GraphQLClient, withWrapper?: SdkFunctionW
148
149
  headers: Headers;
149
150
  status: number;
150
151
  }>;
152
+ GetHealthSummary(variables?: Types.GetHealthSummaryQueryVariables, requestHeaders?: GraphQLClientRequestHeaders): Promise<{
153
+ data: Types.GetHealthSummaryQueryResults;
154
+ errors?: GraphQLError[];
155
+ extensions?: any;
156
+ headers: Headers;
157
+ status: number;
158
+ }>;
151
159
  getImmunizationGroups(variables?: Types.GetImmunizationGroupsQueryVariables, requestHeaders?: GraphQLClientRequestHeaders): Promise<{
152
160
  data: Types.GetImmunizationGroupsQueryResults;
153
161
  errors?: GraphQLError[];
@@ -744,6 +744,16 @@ export const GetEncountersGroupDocument = `
744
744
  }
745
745
  ${PagingFieldsFragmentDoc}
746
746
  ${CodingFieldsFragmentDoc}`;
747
+ export const GetHealthSummaryDocument = `
748
+ query GetHealthSummary {
749
+ getHealthSummary {
750
+ resources {
751
+ category
752
+ total
753
+ }
754
+ }
755
+ }
756
+ `;
747
757
  export const GetImmunizationGroupsDocument = `
748
758
  query getImmunizationGroups($request: ImmunizationGroupQueryRequest) {
749
759
  getImmunizationGroups(request: $request) {
@@ -1310,6 +1320,9 @@ export function getSdk(client, withWrapper = defaultWrapper) {
1310
1320
  getEncountersGroup(variables, requestHeaders) {
1311
1321
  return withWrapper((wrappedRequestHeaders) => client.rawRequest(GetEncountersGroupDocument, variables, Object.assign(Object.assign({}, requestHeaders), wrappedRequestHeaders)), 'getEncountersGroup', 'query', variables);
1312
1322
  },
1323
+ GetHealthSummary(variables, requestHeaders) {
1324
+ return withWrapper((wrappedRequestHeaders) => client.rawRequest(GetHealthSummaryDocument, variables, Object.assign(Object.assign({}, requestHeaders), wrappedRequestHeaders)), 'GetHealthSummary', 'query', variables);
1325
+ },
1313
1326
  getImmunizationGroups(variables, requestHeaders) {
1314
1327
  return withWrapper((wrappedRequestHeaders) => client.rawRequest(GetImmunizationGroupsDocument, variables, Object.assign(Object.assign({}, requestHeaders), wrappedRequestHeaders)), 'getImmunizationGroups', 'query', variables);
1315
1328
  },
@@ -2462,6 +2462,17 @@ export type GetEncountersGroupQueryResults = {
2462
2462
  }>;
2463
2463
  };
2464
2464
  };
2465
+ export type GetHealthSummaryQueryVariables = Types.Exact<{
2466
+ [key: string]: never;
2467
+ }>;
2468
+ export type GetHealthSummaryQueryResults = {
2469
+ getHealthSummary: {
2470
+ resources: Array<{
2471
+ category: Types.HealthSummaryCategory | null;
2472
+ total: number | null;
2473
+ }>;
2474
+ };
2475
+ };
2465
2476
  export type GetImmunizationGroupsQueryVariables = Types.Exact<{
2466
2477
  request: Types.InputMaybe<Types.ImmunizationGroupQueryRequest>;
2467
2478
  }>;
@@ -1,2 +1,4 @@
1
1
  export * from "./jwt-token-manager.js";
2
2
  export * from "./token-storage.js";
3
+ export * from "./token-manager.js";
4
+ export { loadAuthTokens } from "./load-auth-tokens.js";
@@ -1,2 +1,4 @@
1
1
  export * from "./jwt-token-manager.js";
2
2
  export * from "./token-storage.js";
3
+ export * from "./token-manager.js";
4
+ export { loadAuthTokens } from "./load-auth-tokens.js";
@@ -1,7 +1,8 @@
1
1
  import { IdentityManager } from "../api/base/identity/index.js";
2
- import { InvalidTokenError, OperationOutcomeError } from "../errors/index.js";
2
+ import { BWellError, InvalidTokenError, OperationOutcomeError } from "../errors/index.js";
3
3
  import { LoggerProvider } from "../logger/index.js";
4
4
  import { BWellTransactionResult } from "../results/index.js";
5
+ import { TokenManager } from "./token-manager.js";
5
6
  import { TokenStorage } from "./token-storage.js";
6
7
  export type TokenManagerConfig = {
7
8
  accessToken: string;
@@ -9,11 +10,6 @@ export type TokenManagerConfig = {
9
10
  clientKey: string;
10
11
  refreshToken: string;
11
12
  };
12
- export interface TokenManager {
13
- getAccessToken(): Promise<BWellTransactionResult<string, OperationOutcomeError | InvalidTokenError>>;
14
- refreshAccessToken(): Promise<BWellTransactionResult<null, OperationOutcomeError | InvalidTokenError>>;
15
- getIdToken(): Promise<string | undefined>;
16
- }
17
13
  export declare class JWTTokenManager implements TokenManager {
18
14
  #private;
19
15
  private constructor();
@@ -27,7 +23,7 @@ export declare class JWTTokenManager implements TokenManager {
27
23
  *
28
24
  * @returns {BWellTransactionResult<JWTTokenManager, InvalidTokenError>}
29
25
  */
30
- static initialize(config: TokenManagerConfig, identManager: IdentityManager, loggerProvider?: LoggerProvider, tokenStorage?: TokenStorage): Promise<BWellTransactionResult<JWTTokenManager, InvalidTokenError>>;
26
+ static initialize(config: TokenManagerConfig, identManager: IdentityManager, loggerProvider?: LoggerProvider, tokenStorage?: TokenStorage): Promise<BWellTransactionResult<JWTTokenManager, InvalidTokenError | BWellError>>;
31
27
  getAccessToken(): Promise<BWellTransactionResult<string, OperationOutcomeError | InvalidTokenError>>;
32
28
  getIdToken(): Promise<string | undefined>;
33
29
  refreshAccessToken(): Promise<BWellTransactionResult<null, OperationOutcomeError | InvalidTokenError>>;
@@ -23,6 +23,7 @@ import { BWellError, InvalidTokenError, } from "../errors/index.js";
23
23
  import { ConsoleLoggerProvider, } from "../logger/index.js";
24
24
  import { BWellTransactionResult } from "../results/index.js";
25
25
  import { isUndefined, parseTokenExpiration } from "../utils/index.js";
26
+ import { ACCESS_TOKEN_STORAGE_KEY, CLIENT_KEY_STORAGE_KEY, EXPRIATION_TOKEN_STORAGE_KEY, ID_TOKEN_STORAGE_KEY, REFRESH_TOKEN_STORAGE_KEY, } from "./token-manager.js";
26
27
  import { InMemoryTokenStorage } from "./token-storage.js";
27
28
  export class JWTTokenManager {
28
29
  constructor(config, identManager, loggerProvider, tokenStorage) {
@@ -52,16 +53,16 @@ export class JWTTokenManager {
52
53
  }
53
54
  const tokenManager = new _a(Object.assign(Object.assign({}, config), { expiration: expirationResult.data() }), identManager, loggerProvider, tokenStorage);
54
55
  try {
55
- yield Promise.all([
56
- tokenStorage.set("idToken", config.idToken),
57
- tokenStorage.set("clientKey", config.clientKey),
58
- tokenStorage.set("accessToken", config.accessToken),
59
- tokenStorage.set("refreshToken", config.refreshToken),
60
- tokenStorage.set("expiration", expirationResult.data().toISOString()),
56
+ yield tokenStorage.setMany([
57
+ [ID_TOKEN_STORAGE_KEY, config.idToken],
58
+ [CLIENT_KEY_STORAGE_KEY, config.clientKey],
59
+ [ACCESS_TOKEN_STORAGE_KEY, config.accessToken],
60
+ [REFRESH_TOKEN_STORAGE_KEY, config.refreshToken],
61
+ [EXPRIATION_TOKEN_STORAGE_KEY, expirationResult.data().toISOString()],
61
62
  ]);
62
63
  }
63
- catch (_b) {
64
- return BWellTransactionResult.failure(new InvalidTokenError("Failed to set tokens in token storage"));
64
+ catch (e) {
65
+ return BWellTransactionResult.failure(new BWellError("Failed to set tokens in token storage", { cause: e }));
65
66
  }
66
67
  return BWellTransactionResult.success(tokenManager);
67
68
  });
@@ -0,0 +1,6 @@
1
+ import { AuthTokens } from "../api/base/identity/identity-manager.js";
2
+ import { BWellError } from "../errors/bwell-error.js";
3
+ import { InvalidTokenError } from "../errors/invalid-token-error.js";
4
+ import { BWellTransactionResult } from "../results/index.js";
5
+ import { TokenStorage } from "./token-storage.js";
6
+ export declare function loadAuthTokens(storage: TokenStorage): Promise<BWellTransactionResult<AuthTokens, InvalidTokenError | BWellError>>;
@@ -0,0 +1,43 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { BWellError } from "../errors/bwell-error.js";
11
+ import { InvalidTokenError } from "../errors/invalid-token-error.js";
12
+ import { BWellTransactionResult } from "../results/index.js";
13
+ import { isNullOrUndefinedOrEmptyString } from "../utils/type-utils.js";
14
+ import * as tm from "./token-manager.js";
15
+ export function loadAuthTokens(storage) {
16
+ return __awaiter(this, void 0, void 0, function* () {
17
+ let results;
18
+ try {
19
+ results = yield storage.getMany([
20
+ tm.ACCESS_TOKEN_STORAGE_KEY,
21
+ tm.ID_TOKEN_STORAGE_KEY,
22
+ tm.REFRESH_TOKEN_STORAGE_KEY,
23
+ ]);
24
+ }
25
+ catch (e) {
26
+ return BWellTransactionResult.failure(new BWellError("Error loading credentials froms torage", { cause: e }));
27
+ }
28
+ const [accessTokenKV = [], idTokenKV = [], refreshTokenKV = []] = results;
29
+ const [, accessToken] = accessTokenKV;
30
+ const [, idToken] = idTokenKV;
31
+ const [, refreshToken] = refreshTokenKV;
32
+ if (isNullOrUndefinedOrEmptyString(accessToken) ||
33
+ isNullOrUndefinedOrEmptyString(idToken) ||
34
+ isNullOrUndefinedOrEmptyString(refreshToken)) {
35
+ return BWellTransactionResult.failure(new InvalidTokenError("Credentials could not be loaded from token storage"));
36
+ }
37
+ return BWellTransactionResult.success({
38
+ accessToken,
39
+ idToken,
40
+ refreshToken,
41
+ });
42
+ });
43
+ }
@@ -0,0 +1,12 @@
1
+ import { InvalidTokenError, OperationOutcomeError } from "../errors/index.js";
2
+ import { BWellTransactionResult } from "../results/index.js";
3
+ export declare const ID_TOKEN_STORAGE_KEY = "idToken";
4
+ export declare const CLIENT_KEY_STORAGE_KEY = "clientKey";
5
+ export declare const ACCESS_TOKEN_STORAGE_KEY = "accessToken";
6
+ export declare const REFRESH_TOKEN_STORAGE_KEY = "refreshToken";
7
+ export declare const EXPRIATION_TOKEN_STORAGE_KEY = "expiration";
8
+ export interface TokenManager {
9
+ getAccessToken(): Promise<BWellTransactionResult<string, OperationOutcomeError | InvalidTokenError>>;
10
+ refreshAccessToken(): Promise<BWellTransactionResult<null, OperationOutcomeError | InvalidTokenError>>;
11
+ getIdToken(): Promise<string | undefined>;
12
+ }
@@ -0,0 +1,5 @@
1
+ export const ID_TOKEN_STORAGE_KEY = "idToken";
2
+ export const CLIENT_KEY_STORAGE_KEY = "clientKey";
3
+ export const ACCESS_TOKEN_STORAGE_KEY = "accessToken";
4
+ export const REFRESH_TOKEN_STORAGE_KEY = "refreshToken";
5
+ export const EXPRIATION_TOKEN_STORAGE_KEY = "expiration";
@@ -1,3 +1,4 @@
1
+ export type GetManyResult = [string, string | undefined];
1
2
  /**
2
3
  * Interface for storing tokens.
3
4
  * We might want to store more than one kind of token, so the interface is for a key-value store.
@@ -9,12 +10,25 @@ export interface TokenStorage {
9
10
  * @param key The key to look up the value.
10
11
  */
11
12
  get(key: string): Promise<string | undefined>;
13
+ /**
14
+ * Gets all keys at once. Returns list of key value pairs where the value is
15
+ * `undefined` if not found.
16
+ *
17
+ * @param keys - List of keys to fetch.
18
+ */
19
+ getMany(keys: string[]): Promise<GetManyResult[]>;
12
20
  /**
13
21
  * Set the value for a key.
14
22
  * @param key The key to set the value.
15
23
  * @param value The value to set.
16
24
  */
17
25
  set(key: string, value: string): Promise<void>;
26
+ /**
27
+ * Sets many values at once.
28
+ *
29
+ * @param keyValues - List of key value pairs to set
30
+ */
31
+ setMany(keyValues: [string, string][]): Promise<void>;
18
32
  /**
19
33
  * Delete the value for a key.
20
34
  * @param key The key to delete the value.
@@ -28,6 +42,8 @@ export declare class InMemoryTokenStorage {
28
42
  private storage;
29
43
  constructor(storage?: Map<string, string>);
30
44
  get(key: string): Promise<string | undefined>;
45
+ getMany(keys: string[]): Promise<GetManyResult[]>;
31
46
  set(key: string, value: string): Promise<void>;
47
+ setMany(keyValues: [string, string][]): Promise<void>;
32
48
  delete(key: string): Promise<boolean>;
33
49
  }
@@ -19,11 +19,28 @@ export class InMemoryTokenStorage {
19
19
  return this.storage.get(key);
20
20
  });
21
21
  }
22
+ getMany(keys) {
23
+ return __awaiter(this, void 0, void 0, function* () {
24
+ const results = [];
25
+ for (let i = 0; i < keys.length; i++) {
26
+ const key = keys[i];
27
+ results[i] = [key, this.storage.get(key)];
28
+ }
29
+ return results;
30
+ });
31
+ }
22
32
  set(key, value) {
23
33
  return __awaiter(this, void 0, void 0, function* () {
24
34
  this.storage.set(key, value);
25
35
  });
26
36
  }
37
+ setMany(keyValues) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ for (const [k, v] of keyValues) {
40
+ this.storage.set(k, v);
41
+ }
42
+ });
43
+ }
27
44
  delete(key) {
28
45
  return __awaiter(this, void 0, void 0, function* () {
29
46
  return this.storage.delete(key);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@icanbwell/bwell-sdk-ts",
3
- "version": "2.0.0-alpha.0-rc.1752772167",
3
+ "version": "2.0.0-alpha.0-rc.1753298141",
4
4
  "description": "b.well TypeScript SDK",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",