@dynatrace-sdk/http-client 1.5.1 → 1.6.0

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/esm/index.js CHANGED
@@ -34,18 +34,72 @@ function isHttpClientNetworkError(e) {
34
34
  return e?.name === "NetworkError";
35
35
  }
36
36
 
37
+ // packages/http-client/src/lib/types/error-types.ts
38
+ var ErrorType = /* @__PURE__ */ ((ErrorType3) => {
39
+ ErrorType3["COMMON"] = "JS Error";
40
+ ErrorType3["HTTP"] = "Http Error";
41
+ return ErrorType3;
42
+ })(ErrorType || {});
43
+
37
44
  // packages/http-client/src/lib/platform/abort-controller.ts
38
45
  var AbortController = globalThis.AbortController;
39
46
 
40
47
  // packages/http-client/src/lib/platform/abort-signal.ts
41
48
  var AbortSignal = globalThis.AbortSignal;
42
49
 
50
+ // packages/http-client/src/lib/platform/api-client-error.ts
51
+ var ApiClientError = class extends Error {
52
+ constructor(name, message, cause) {
53
+ super(message ?? "ApiClientError: an unexpected error occurred.");
54
+ this.cause = cause;
55
+ this.name = name;
56
+ }
57
+ cause;
58
+ isApiClientError = true;
59
+ errorType = "JS Error" /* COMMON */;
60
+ };
61
+ function isApiClientError(e) {
62
+ return e?.isApiClientError === true && e instanceof Error;
63
+ }
64
+
65
+ // packages/http-client/src/lib/platform/client-request-error.ts
66
+ var ClientRequestError = class extends ApiClientError {
67
+ isClientRequestError = true;
68
+ body;
69
+ response;
70
+ constructor(name, response, body, message, cause) {
71
+ super(name, message, cause);
72
+ this.errorType = "Http Error" /* HTTP */;
73
+ this.body = body;
74
+ this.response = response;
75
+ }
76
+ };
77
+ function isClientRequestError(e) {
78
+ return e?.isClientRequestError === true && isApiClientError(e);
79
+ }
80
+
81
+ // packages/http-client/src/lib/platform/api-gateway-error.ts
82
+ var ApiGatewayError = class extends ClientRequestError {
83
+ isApiGatewayError = true;
84
+ code;
85
+ retryAfterSeconds;
86
+ constructor(response, body) {
87
+ super(body.error.details?.errorCode || "ApiGatewayError", response, body, body.error.message);
88
+ this.code = body.error.code;
89
+ this.retryAfterSeconds = body.error.retryAfterSeconds;
90
+ }
91
+ };
92
+ function isApiGatewayError(e) {
93
+ return e?.isApiGatewayError === true && isClientRequestError(e);
94
+ }
95
+
43
96
  // packages/http-client/src/lib/platform/base-error.ts
44
97
  var BaseError = class extends Error {
45
98
  constructor(message, cause) {
46
99
  super(message);
47
100
  this.cause = cause;
48
101
  }
102
+ cause;
49
103
  };
50
104
 
51
105
  // packages/http-client/src/lib/platform/unsupported-operation-error.ts
@@ -77,6 +131,7 @@ var Binary = class _Binary {
77
131
  constructor(data) {
78
132
  this.data = data;
79
133
  }
134
+ data;
80
135
  static fromText(text) {
81
136
  return new _Binary(new Blob([text]));
82
137
  }
@@ -109,6 +164,36 @@ var DataTypeError = class extends BaseError {
109
164
  // packages/http-client/src/lib/platform/default-status-validator.ts
110
165
  var defaultStatusValidator = (status) => 200 <= status && status < 300;
111
166
 
167
+ // packages/http-client/src/lib/platform/get-error-message.ts
168
+ function serializeData(data) {
169
+ try {
170
+ return JSON.stringify(data);
171
+ } catch {
172
+ return String(data);
173
+ }
174
+ }
175
+ function getMessagesFromErrorDetails(details) {
176
+ const messages = [];
177
+ Object.entries(details).forEach(([name, data]) => {
178
+ if (!data) return;
179
+ const serializedData = serializeData(data);
180
+ switch (name) {
181
+ case "missingScopes":
182
+ messages.push(`Missing scopes: ${serializedData}`);
183
+ break;
184
+ default:
185
+ messages.push(`${name}: ${serializedData}`);
186
+ }
187
+ });
188
+ return messages;
189
+ }
190
+ function getErrorMessage(errorBody, defaultMessage) {
191
+ const error = errorBody;
192
+ const msg = error?.error?.message || defaultMessage;
193
+ const details = error?.error?.details || {};
194
+ return [msg, ...getMessagesFromErrorDetails(details)].join(". ");
195
+ }
196
+
112
197
  // packages/http-client/src/lib/platform/encode-request-body.ts
113
198
  function encodeTextRequestBody(body) {
114
199
  return String(body);
@@ -238,6 +323,7 @@ var HttpClientAbortError = class extends Error {
238
323
  );
239
324
  this.cause = cause;
240
325
  }
326
+ cause;
241
327
  name = "AbortError";
242
328
  };
243
329
  var throwIfAbortError = (e) => {
@@ -254,21 +340,20 @@ var HttpClientRequestError = class extends BaseError {
254
340
  );
255
341
  this.cause = cause;
256
342
  }
343
+ cause;
257
344
  name = "RequestError";
258
345
  };
259
346
 
260
347
  // packages/http-client/src/lib/platform/decode-form-data.ts
261
348
  function byteToChar(byte) {
262
- if (byte === void 0)
263
- return void 0;
349
+ if (byte === void 0) return void 0;
264
350
  return String.fromCharCode(byte);
265
351
  }
266
352
  function isTextContentType(contentType) {
267
353
  return ["application/json", "text/plain"].includes(String(contentType).toLowerCase());
268
354
  }
269
355
  function removeEscaping(value) {
270
- if (!value)
271
- return value;
356
+ if (!value) return value;
272
357
  return JSON.parse(`"${value}"`);
273
358
  }
274
359
  function parseContentDisposition(contentDisposition) {
@@ -288,6 +373,8 @@ var FormDataParser = class {
288
373
  this.sourceArray = sourceArray;
289
374
  this.boundary = boundary;
290
375
  }
376
+ sourceArray;
377
+ boundary;
291
378
  currentChar = null;
292
379
  currentByte = null;
293
380
  offset = 0;
@@ -594,11 +681,12 @@ function decodeResponseBody(response, responseBodyType) {
594
681
  }
595
682
 
596
683
  // packages/http-client/src/lib/platform/http-client-response.ts
597
- var HttpClientResponse = class {
684
+ var HttpClientResponse2 = class {
598
685
  constructor(response, data) {
599
686
  this.response = response;
600
687
  this.requestUrl = data?.requestUrl ?? response.url;
601
688
  }
689
+ response;
602
690
  requestUrl;
603
691
  get url() {
604
692
  return this.response.url;
@@ -624,7 +712,7 @@ var HttpClientResponse = class {
624
712
  // packages/http-client/src/lib/platform/http-client-response-error-serializer.ts
625
713
  import {
626
714
  addGlobalErrorSerializer,
627
- ErrorType,
715
+ ErrorType as ErrorType2,
628
716
  isGlobalErrorSerializerSupported
629
717
  } from "@dynatrace-sdk/error-handlers";
630
718
  function getMessageFromObject(obj) {
@@ -679,7 +767,7 @@ var httpClientResponseErrorSerializer = async (error) => {
679
767
  status,
680
768
  message,
681
769
  stack: error.stack,
682
- type: ErrorType.HTTP,
770
+ type: ErrorType2.HTTP,
683
771
  details: {
684
772
  url: error.response.url,
685
773
  requestUrl: error.response.requestUrl,
@@ -716,7 +804,7 @@ var HttpClientResponseError = class extends BaseError {
716
804
  constructor(response, data) {
717
805
  addHttpClientResponseErrorSerializer();
718
806
  super(`HTTP Error ${response.status}: ${response.statusText}`);
719
- this.response = new HttpClientResponse(response, {
807
+ this.response = new HttpClientResponse2(response, {
720
808
  requestUrl: data?.requestUrl ?? response.url
721
809
  });
722
810
  this.requestMethod = data?.requestMethod;
@@ -767,7 +855,7 @@ var HttpClient = class {
767
855
  });
768
856
  const ok = statusValidator(response.status);
769
857
  if (ok) {
770
- return new HttpClientResponse(response, { requestUrl: url });
858
+ return new HttpClientResponse2(response, { requestUrl: url });
771
859
  } else {
772
860
  throw new HttpClientResponseError(response, {
773
861
  requestUrl: url,
@@ -778,6 +866,210 @@ var HttpClient = class {
778
866
  };
779
867
  var httpClient = new HttpClient();
780
868
 
869
+ // packages/http-client/src/lib/platform/invalid-response-error.ts
870
+ var InvalidResponseError = class extends ApiClientError {
871
+ isInvalidResponseError = true;
872
+ responseBody;
873
+ expectedType;
874
+ nestedError;
875
+ response;
876
+ constructor(name, nestedError, body, expectedType, message, response) {
877
+ super(
878
+ name,
879
+ message ?? `${name}: Response does not match expected datatype${expectedType ? " " + expectedType : ""}: ${nestedError?.toString() ?? "unable to deserialize"}`
880
+ );
881
+ this.nestedError = nestedError;
882
+ this.responseBody = body;
883
+ this.expectedType = expectedType;
884
+ this.response = response;
885
+ }
886
+ };
887
+ function isHttpClientDataTypeError(e) {
888
+ return e instanceof Error && e?.name === "DataTypeError";
889
+ }
890
+ function isInvalidResponseError(e) {
891
+ if (e?.isInvalidResponseError === true && isApiClientError(e)) {
892
+ return true;
893
+ }
894
+ return isHttpClientDataTypeError(e);
895
+ }
896
+
897
+ // packages/http-client/src/lib/platform/execute-request.ts
898
+ var API_GATEWAY_RESPONSE_SOURCE_HEADER = "dynatrace-response-source";
899
+ var API_GATEWAY_RESPONSE_SOURCE = "API Gateway";
900
+ function buildStatusValidator(acceptedStatusCodes, statusValidator) {
901
+ if (acceptedStatusCodes !== void 0) {
902
+ return (status) => acceptedStatusCodes.includes(status);
903
+ }
904
+ return statusValidator ?? defaultStatusValidator;
905
+ }
906
+ function resolveBodyType(resolver, response) {
907
+ return typeof resolver === "function" ? resolver(response) : resolver;
908
+ }
909
+ function readBody(response, responseBodyType) {
910
+ return response.body(responseBodyType);
911
+ }
912
+ async function readTextBody(response) {
913
+ try {
914
+ return await response.body("text");
915
+ } catch {
916
+ return "";
917
+ }
918
+ }
919
+ function resolveErrorFactory(status, factories) {
920
+ const exact = factories?.[status];
921
+ if (exact) {
922
+ return { factory: exact, label: `${status}` };
923
+ }
924
+ const range = factories?.[`${Math.floor(status / 100)}XX`];
925
+ if (range) {
926
+ return { factory: range, label: `${status}` };
927
+ }
928
+ if (factories?.default) {
929
+ return { factory: factories.default, label: "err" };
930
+ }
931
+ return void 0;
932
+ }
933
+ async function buildApiGatewayError(response, operationId) {
934
+ if (response.headers?.[API_GATEWAY_RESPONSE_SOURCE_HEADER] !== API_GATEWAY_RESPONSE_SOURCE) {
935
+ return void 0;
936
+ }
937
+ let body;
938
+ try {
939
+ body = await response.body("json");
940
+ } catch (decodeErr) {
941
+ throw new InvalidResponseError(
942
+ `${operationId}:${response.status}`,
943
+ decodeErr,
944
+ await readTextBody(response),
945
+ void 0,
946
+ void 0,
947
+ response
948
+ );
949
+ }
950
+ return new ApiGatewayError(response, body);
951
+ }
952
+ async function buildFactoryError(e, { factory, label }, options) {
953
+ const { response } = e;
954
+ const name = `${options.operationId}:${label}`;
955
+ const expectedType = factory.errorEnvelope ?? options.errorEnvelope;
956
+ const bodyType = resolveBodyType(factory.responseBodyType ?? "json", response);
957
+ let body;
958
+ if (bodyType !== "none") {
959
+ try {
960
+ body = await readBody(response, bodyType);
961
+ } catch (decodeErr) {
962
+ throw new InvalidResponseError(
963
+ name,
964
+ decodeErr,
965
+ await readTextBody(response),
966
+ expectedType,
967
+ void 0,
968
+ response
969
+ );
970
+ }
971
+ }
972
+ if (factory.transformBody) {
973
+ try {
974
+ body = factory.transformBody(body);
975
+ } catch (transformErr) {
976
+ throw new InvalidResponseError(name, transformErr, body, expectedType, void 0, response);
977
+ }
978
+ }
979
+ return factory.build({ response, body, cause: e });
980
+ }
981
+ async function buildFallbackError(e) {
982
+ const { response } = e;
983
+ let responseValue;
984
+ try {
985
+ responseValue = await response.body("json");
986
+ } catch (decodeErr) {
987
+ throw new InvalidResponseError(
988
+ `${response.status}`,
989
+ decodeErr,
990
+ await readTextBody(response),
991
+ "json",
992
+ "Unexpected api response",
993
+ response
994
+ );
995
+ }
996
+ return new ClientRequestError(
997
+ `${response.status}`,
998
+ response,
999
+ responseValue,
1000
+ getErrorMessage(
1001
+ responseValue,
1002
+ `Unexpected api response: code=${response.status} body="${responseValue}"`
1003
+ ),
1004
+ e
1005
+ );
1006
+ }
1007
+ async function dispatchResponseError(e, options) {
1008
+ const gatewayError = await buildApiGatewayError(e.response, options.operationId);
1009
+ if (gatewayError) {
1010
+ throw gatewayError;
1011
+ }
1012
+ const resolved = resolveErrorFactory(e.response.status, options.errorFactories);
1013
+ throw resolved ? await buildFactoryError(e, resolved, options) : await buildFallbackError(e);
1014
+ }
1015
+ async function decodeSuccessBody(response, options) {
1016
+ const resolvedBodyType = resolveBodyType(options.responseBodyType ?? "json", response);
1017
+ if (resolvedBodyType === "none") {
1018
+ return void 0;
1019
+ }
1020
+ const name = `${options.operationId}:${response.status}`;
1021
+ let body;
1022
+ try {
1023
+ body = await readBody(response, resolvedBodyType);
1024
+ } catch (e) {
1025
+ throw new InvalidResponseError(
1026
+ name,
1027
+ e,
1028
+ await readTextBody(response),
1029
+ void 0,
1030
+ void 0,
1031
+ response
1032
+ );
1033
+ }
1034
+ if (!options.transformResponse) {
1035
+ return body;
1036
+ }
1037
+ try {
1038
+ return options.transformResponse(body, response);
1039
+ } catch (e) {
1040
+ throw new InvalidResponseError(name, e, body, void 0, void 0, response);
1041
+ }
1042
+ }
1043
+ async function executeRequest(options) {
1044
+ const { acceptedStatusCodes, statusValidator } = options;
1045
+ if (acceptedStatusCodes !== void 0 && statusValidator !== void 0) {
1046
+ throw new TypeError("acceptedStatusCodes and statusValidator are mutually exclusive.");
1047
+ }
1048
+ const validator = buildStatusValidator(acceptedStatusCodes, statusValidator);
1049
+ const client = options.httpClient ?? httpClient;
1050
+ let response;
1051
+ try {
1052
+ response = await client.send({
1053
+ url: options.url,
1054
+ method: options.method,
1055
+ headers: options.headers,
1056
+ body: options.body,
1057
+ requestBodyType: options.requestBodyType,
1058
+ abortSignal: options.abortSignal,
1059
+ statusValidator: validator
1060
+ });
1061
+ } catch (e) {
1062
+ if (isHttpClientAbortError(e) || isInvalidResponseError(e) || isClientRequestError(e)) {
1063
+ throw e;
1064
+ }
1065
+ if (!isHttpClientResponseError(e)) {
1066
+ throw new ApiClientError("UnexpectedError", "Unexpected error", e);
1067
+ }
1068
+ return await dispatchResponseError(e, options);
1069
+ }
1070
+ return decodeSuccessBody(response, options);
1071
+ }
1072
+
781
1073
  // packages/http-client/src/lib/platform/oauth-http-client.ts
782
1074
  var TOKEN_EXPIRATION_SAFETY_MARGIN_SECONDS = 1;
783
1075
  var OAuthToken = class {
@@ -820,6 +1112,7 @@ var OAuthHttpClient = class {
820
1112
  constructor(config) {
821
1113
  this.config = config;
822
1114
  }
1115
+ config;
823
1116
  oauthToken;
824
1117
  async send(options) {
825
1118
  const { statusValidator = defaultStatusValidator } = options;
@@ -842,7 +1135,7 @@ var OAuthHttpClient = class {
842
1135
  });
843
1136
  const ok = statusValidator(response.status);
844
1137
  if (ok) {
845
- return new HttpClientResponse(response, { requestUrl });
1138
+ return new HttpClientResponse2(response, { requestUrl });
846
1139
  } else {
847
1140
  throw new HttpClientResponseError(response, {
848
1141
  requestUrl,
@@ -876,10 +1169,20 @@ export {
876
1169
  HttpClient as PlatformHttpClient,
877
1170
  HttpClientAbortError as PlatformHttpClientAbortError,
878
1171
  HttpClientRequestError as PlatformHttpClientRequestError,
879
- HttpClientResponse as PlatformHttpClientResponse,
1172
+ HttpClientResponse2 as PlatformHttpClientResponse,
880
1173
  HttpClientResponseError as PlatformHttpClientResponseError,
881
1174
  UnsupportedOperationError as PlatformUnsupportedOperationError,
1175
+ ApiClientError as _ApiClientError,
1176
+ ApiGatewayError as _ApiGatewayError,
1177
+ ClientRequestError as _ClientRequestError,
1178
+ ErrorType as _ErrorType,
1179
+ InvalidResponseError as _InvalidResponseError,
882
1180
  OAuthHttpClient as _OAuthHttpClient,
1181
+ executeRequest as _executeRequest,
1182
+ isApiClientError as _isApiClientError,
1183
+ isApiGatewayError as _isApiGatewayError,
1184
+ isClientRequestError as _isClientRequestError,
1185
+ isInvalidResponseError as _isInvalidResponseError,
883
1186
  httpClient,
884
1187
  isHttpClientAbortError,
885
1188
  isHttpClientNetworkError,
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "module"
3
+ }
package/package.json CHANGED
@@ -1,9 +1,20 @@
1
1
  {
2
2
  "name": "@dynatrace-sdk/http-client",
3
- "version": "1.5.1",
3
+ "version": "1.6.0",
4
4
  "description": "An environment agnostic (browser/deno vs nodejs) abstraction layer for making HTTP calls.",
5
5
  "license": "Apache-2.0",
6
- "dependencies": { "@dynatrace-sdk/error-handlers": "^1.2.0" },
6
+ "exports": {
7
+ ".": {
8
+ "types": "./types/index.d.ts",
9
+ "require": "./cjs/index.js",
10
+ "browser": "./esm/index.js",
11
+ "module": "./esm/index.js",
12
+ "import": "./esm/index.js"
13
+ }
14
+ },
15
+ "dependencies": {
16
+ "@dynatrace-sdk/error-handlers": "^1.2.0"
17
+ },
7
18
  "main": "./cjs/index.js",
8
19
  "module": "./esm/index.js",
9
20
  "types": "./types/index.d.ts"