@pitcher/js-api 1.21.0-beta.6 → 1.21.0-beta.8

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/js-api.esm.js CHANGED
@@ -2471,7 +2471,10 @@ function getUsers(payload) {
2471
2471
  return this.API.request("get_users", payload);
2472
2472
  }
2473
2473
  function refreshServiceToken(payload) {
2474
- return this.API.request("refresh_service_token", payload);
2474
+ return this.API.request("refresh_service_token", payload ?? {});
2475
+ }
2476
+ function refreshAccessToken() {
2477
+ return this.API.request("refresh_access_token");
2475
2478
  }
2476
2479
 
2477
2480
  function fetchDocumentInfo(payload) {
@@ -2579,6 +2582,7 @@ const modules = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
2579
2582
  openExternalUrl,
2580
2583
  openWebViewAlwaysOnTop,
2581
2584
  query,
2585
+ refreshAccessToken,
2582
2586
  refreshServiceToken,
2583
2587
  renderPageAsImage,
2584
2588
  search,
@@ -2770,6 +2774,29 @@ const snakeCaseKeys = (obj, skipKeys = defaultSkipKeys, skipObjectKeys = default
2770
2774
  return obj;
2771
2775
  };
2772
2776
 
2777
+ function truncateObject(obj, currentDepth = 1, lengthTrigger = 20) {
2778
+ if (typeof obj !== "object" || obj === null) {
2779
+ return obj;
2780
+ }
2781
+ if (Array.isArray(obj)) {
2782
+ if (obj.length > lengthTrigger && currentDepth <= 0) {
2783
+ return `[Truncated - ${obj.length} length array]`;
2784
+ }
2785
+ return obj.map((item) => truncateObject(item, currentDepth - 1, lengthTrigger));
2786
+ }
2787
+ const keys = Object.keys(obj);
2788
+ if (keys.length > lengthTrigger && currentDepth <= 0) {
2789
+ return `{Truncated - ${keys.length} properties obj}`;
2790
+ }
2791
+ return keys.reduce(
2792
+ (acc, key) => {
2793
+ acc[key] = truncateObject(obj[key], currentDepth - 1, lengthTrigger);
2794
+ return acc;
2795
+ },
2796
+ {}
2797
+ );
2798
+ }
2799
+
2773
2800
  function isOriginValid(event, allowedOrigins = [], isDev = ["development", "test"].includes("production")) {
2774
2801
  if (isDev) {
2775
2802
  return true;
@@ -2789,6 +2816,27 @@ function isOriginValid(event, allowedOrigins = [], isDev = ["development", "test
2789
2816
 
2790
2817
  const MAX_RETRIES = 5;
2791
2818
  const BASE_DELAY = 1e3;
2819
+ let refreshPromise = null;
2820
+ async function refreshToken() {
2821
+ if (refreshPromise) return refreshPromise;
2822
+ console.info("Refreshing access token...");
2823
+ refreshPromise = (async () => {
2824
+ try {
2825
+ return await highLevelApi.refreshAccessToken().then(
2826
+ (accessTokenResponse) => highLevelApi.getEnv().then((env) => {
2827
+ setEnv(env);
2828
+ return accessTokenResponse.access_token;
2829
+ })
2830
+ );
2831
+ } catch (error) {
2832
+ console.error("Failed to refresh token:", error);
2833
+ throw error;
2834
+ } finally {
2835
+ refreshPromise = null;
2836
+ }
2837
+ })();
2838
+ return refreshPromise;
2839
+ }
2792
2840
  function paramsSerializer(params) {
2793
2841
  const searchParams = new URLSearchParams();
2794
2842
  function addParam(key, value) {
@@ -2814,17 +2862,23 @@ async function fetchWithRetry(url, options, remainingRetries = MAX_RETRIES) {
2814
2862
  try {
2815
2863
  const response = await fetch(url, options);
2816
2864
  if (!response.ok) {
2817
- if (response.status >= 500 && response.status < 600 && remainingRetries > 0) {
2865
+ if (response.status === 401) {
2866
+ const newToken = await refreshToken();
2867
+ options.headers = options.headers || {};
2868
+ options.headers.Authorization = `Bearer ${newToken}`;
2869
+ return fetchWithRetry(url, options, remainingRetries);
2870
+ } else if (response.status >= 500 && response.status < 600 && remainingRetries > 0) {
2818
2871
  const delay = BASE_DELAY * Math.pow(2, MAX_RETRIES - remainingRetries);
2819
2872
  await new Promise((resolve) => setTimeout(resolve, delay));
2820
2873
  return fetchWithRetry(url, options, remainingRetries - 1);
2874
+ } else {
2875
+ const errorData = await response.json();
2876
+ const error = new Error(
2877
+ `HTTP error! status: ${response.status}, message: ${errorData.message || response.statusText}`
2878
+ );
2879
+ error.status = response.status;
2880
+ throw error;
2821
2881
  }
2822
- const errorData = await response.json();
2823
- const error = new Error(
2824
- `HTTP error! status: ${response.status}, message: ${errorData.message || response.statusText}`
2825
- );
2826
- error.status = response.status;
2827
- throw error;
2828
2882
  }
2829
2883
  return response.json();
2830
2884
  } catch (error) {
@@ -2998,6 +3052,7 @@ const onlineRestApiHandlers = {
2998
3052
  }
2999
3053
  };
3000
3054
 
3055
+ const TRUNCATE_LENGTH_TRIGGER = 10;
3001
3056
  function updateOnlineHandlersEnv(env) {
3002
3057
  env && setEnv(env);
3003
3058
  }
@@ -3052,10 +3107,12 @@ class LowLevelApi extends EventEmitter {
3052
3107
  );
3053
3108
  if (type === "get_env") updateOnlineHandlersEnv(res.response.body);
3054
3109
  } else if (res.response.status === "error") {
3055
- this.options.errorLogger?.({
3056
- message: `Pitcher JS API call failure: ${res.request.type}`,
3057
- js_api_response: JSON.stringify(res)
3058
- });
3110
+ if (this.options.errorLogger) {
3111
+ this.options.errorLogger({
3112
+ message: `Pitcher JS API call failure: ${res.request.type}`,
3113
+ js_api_response: JSON.stringify(truncateObject(res, 3, TRUNCATE_LENGTH_TRIGGER))
3114
+ });
3115
+ }
3059
3116
  reject(this.options.casing === "camel" ? camelCaseKeys(res.response.body) : res.response.body);
3060
3117
  } else {
3061
3118
  throw new Error("unsupported response status");