@pitcher/js-api 1.22.0-alpha.5 → 1.22.0-alpha.6

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
@@ -2661,6 +2661,51 @@ function v4(options, buf, offset) {
2661
2661
  return unsafeStringify(rnds);
2662
2662
  }
2663
2663
 
2664
+ const PITCHER_EVENT = "PITCHER_EVENT";
2665
+ var PitcherMessageType = /* @__PURE__ */ ((PitcherMessageType2) => {
2666
+ PitcherMessageType2["REQUEST"] = "PITCHER_REQUEST";
2667
+ PitcherMessageType2["RESPONSE"] = "PITCHER_RESPONSE";
2668
+ return PitcherMessageType2;
2669
+ })(PitcherMessageType || {});
2670
+ var PitcherResponseStatus = /* @__PURE__ */ ((PitcherResponseStatus2) => {
2671
+ PitcherResponseStatus2["OK"] = "ok";
2672
+ PitcherResponseStatus2["ERROR"] = "error";
2673
+ return PitcherResponseStatus2;
2674
+ })(PitcherResponseStatus || {});
2675
+ var PitcherEventName = /* @__PURE__ */ ((PitcherEventName2) => {
2676
+ PitcherEventName2["ENV_CHANGED"] = "env_changed";
2677
+ PitcherEventName2["PHOTOS_CAPTURED"] = "photos_captured";
2678
+ PitcherEventName2["FILE_DOWNLOADED"] = "file_downloaded";
2679
+ PitcherEventName2["FILE_UPLOAD_PROGRESS"] = "file_upload_progress";
2680
+ PitcherEventName2["UPDATE_LOCATION"] = "update_location";
2681
+ PitcherEventName2["CANVAS_UPDATED"] = "canvas_updated";
2682
+ PitcherEventName2["CANVAS_UPDATED_SUCCESS"] = "canvas_updated_success";
2683
+ PitcherEventName2["FILE_CLOSED"] = "file_closed";
2684
+ PitcherEventName2["APP_BACKGROUNDED"] = "app_backgrounded";
2685
+ PitcherEventName2["APP_FOREGROUNDED"] = "app_foregrounded";
2686
+ PitcherEventName2["NON_FILES_SYNC_FINISHED"] = "non_files_sync_finished";
2687
+ PitcherEventName2["CONTENT_LIST_REFRESH_REQUESTED"] = "content_list_refresh_requested";
2688
+ PitcherEventName2["NETWORK_CONNECTION_ESTABLISHED"] = "network_connection_established";
2689
+ PitcherEventName2["NETWORK_CONNECTION_LOST"] = "network_connection_lost";
2690
+ PitcherEventName2["ENTERED_FULLSCREEN"] = "entered_fullscreen";
2691
+ PitcherEventName2["EXITED_FULLSCREEN"] = "exited_fullscreen";
2692
+ PitcherEventName2["SUBMIT_POSTCALL_CLICKED"] = "submit_postcall_clicked";
2693
+ return PitcherEventName2;
2694
+ })(PitcherEventName || {});
2695
+ var PitcherBroadcastedEventName = /* @__PURE__ */ ((PitcherBroadcastedEventName2) => {
2696
+ PitcherBroadcastedEventName2["UI_SHOW_MODAL"] = "ui:show-modal";
2697
+ PitcherBroadcastedEventName2["UI_HIDE_MODAL"] = "ui:hide-modal";
2698
+ PitcherBroadcastedEventName2["FAVORITES_CHANGED"] = "favorites:changed";
2699
+ PitcherBroadcastedEventName2["FILE_DOWNLOAD"] = "file:download";
2700
+ return PitcherBroadcastedEventName2;
2701
+ })(PitcherBroadcastedEventName || {});
2702
+ var PitcherExternalEventName = /* @__PURE__ */ ((PitcherExternalEventName2) => {
2703
+ PitcherExternalEventName2["CREATE_AND_OPEN_CANVAS"] = "create_and_open_canvas";
2704
+ PitcherExternalEventName2["OPEN_CANVAS"] = "open_canvas";
2705
+ PitcherExternalEventName2["START_CALL"] = "start_call";
2706
+ return PitcherExternalEventName2;
2707
+ })(PitcherExternalEventName || {});
2708
+
2664
2709
  class AssertionError extends Error {
2665
2710
  }
2666
2711
  function assert(exp, message) {
@@ -2733,12 +2778,164 @@ function isOriginValid(event, allowedOrigins = [], isDev = ["development", "test
2733
2778
  return isValid;
2734
2779
  }
2735
2780
 
2781
+ const MAX_RETRIES = 5;
2782
+ const BASE_DELAY = 1e3;
2783
+ function paramsSerializer(params) {
2784
+ const searchParams = new URLSearchParams();
2785
+ for (const key in params) {
2786
+ if (Array.isArray(params[key])) {
2787
+ params[key].forEach((val) => searchParams.append(key, val));
2788
+ } else {
2789
+ searchParams.append(key, params[key]);
2790
+ }
2791
+ }
2792
+ return searchParams.toString();
2793
+ }
2794
+ async function fetchWithRetry(url, options, remainingRetries = MAX_RETRIES) {
2795
+ try {
2796
+ const response = await fetch(url, options);
2797
+ if (!response.ok) {
2798
+ if (response.status >= 500 && response.status < 600 && remainingRetries > 0) {
2799
+ const delay = BASE_DELAY * Math.pow(2, MAX_RETRIES - remainingRetries);
2800
+ await new Promise((resolve) => setTimeout(resolve, delay));
2801
+ return fetchWithRetry(url, options, remainingRetries - 1);
2802
+ }
2803
+ throw new Error(`HTTP error! status: ${response.status}`);
2804
+ }
2805
+ return response.json();
2806
+ } catch (error) {
2807
+ if (remainingRetries > 0) {
2808
+ const delay = BASE_DELAY * Math.pow(2, MAX_RETRIES - remainingRetries);
2809
+ await new Promise((resolve) => setTimeout(resolve, delay));
2810
+ return fetchWithRetry(url, options, remainingRetries - 1);
2811
+ }
2812
+ throw error;
2813
+ }
2814
+ }
2815
+ function createHttpClient(origin, token) {
2816
+ const headers = {
2817
+ "Content-Type": "application/json",
2818
+ Authorization: `Bearer ${token}`
2819
+ };
2820
+ const basePath = origin + "/api/v1";
2821
+ const baseCommon = { credentials: "include" };
2822
+ return {
2823
+ get: async (endpoint, options = {}) => {
2824
+ const url = new URL(`${basePath}${endpoint}`);
2825
+ if (options.params) {
2826
+ url.search = paramsSerializer(options.params);
2827
+ }
2828
+ const data = await fetchWithRetry(url.toString(), {
2829
+ ...baseCommon,
2830
+ ...options,
2831
+ method: "GET",
2832
+ headers
2833
+ });
2834
+ return data;
2835
+ },
2836
+ post: async (endpoint, body, options = {}) => {
2837
+ const url = new URL(`${basePath}${endpoint}`);
2838
+ if (options.params) {
2839
+ url.search = paramsSerializer(options.params);
2840
+ }
2841
+ const data = await fetchWithRetry(url.toString(), {
2842
+ ...baseCommon,
2843
+ ...options,
2844
+ method: "POST",
2845
+ headers,
2846
+ body: JSON.stringify(body)
2847
+ });
2848
+ return data;
2849
+ },
2850
+ put: async (endpoint, body, options = {}) => {
2851
+ const url = new URL(`${basePath}${endpoint}`);
2852
+ if (options.params) {
2853
+ url.search = paramsSerializer(options.params);
2854
+ }
2855
+ const data = await fetchWithRetry(url.toString(), {
2856
+ ...baseCommon,
2857
+ ...options,
2858
+ method: "PUT",
2859
+ headers,
2860
+ body: JSON.stringify(body)
2861
+ });
2862
+ return data;
2863
+ },
2864
+ delete: async (endpoint, options = {}) => {
2865
+ const url = new URL(`${basePath}${endpoint}`);
2866
+ if (options.params) {
2867
+ url.search = paramsSerializer(options.params);
2868
+ }
2869
+ const data = await fetchWithRetry(url.toString(), {
2870
+ ...baseCommon,
2871
+ ...options,
2872
+ method: "DELETE",
2873
+ headers
2874
+ });
2875
+ return data;
2876
+ },
2877
+ patch: async (endpoint, body, options = {}) => {
2878
+ const url = new URL(`${basePath}${endpoint}`);
2879
+ if (options.params) {
2880
+ url.search = paramsSerializer(options.params);
2881
+ }
2882
+ const data = await fetchWithRetry(url.toString(), {
2883
+ ...baseCommon,
2884
+ ...options,
2885
+ method: "PATCH",
2886
+ headers,
2887
+ body: JSON.stringify(body)
2888
+ });
2889
+ return data;
2890
+ }
2891
+ };
2892
+ }
2893
+
2894
+ let env;
2895
+ let http;
2896
+ const logInfo = (msg, ...rest) => console.info(`[online handlers]: ${msg}`, ...rest);
2897
+ const check = () => {
2898
+ if (!env) throw new Error("Missing env");
2899
+ if (!http) throw new Error("Missing http");
2900
+ };
2901
+ const setEnv = (e) => {
2902
+ env = e;
2903
+ http = createHttpClient(
2904
+ env.pitcher.token_claims["https://pitcher.com/claims/urls"].custom_domain,
2905
+ env.pitcher.access_token
2906
+ );
2907
+ };
2908
+ const onlineRestApiHandlers = {
2909
+ get_canvases: async (params) => {
2910
+ logInfo("online handler get_canvases called with:", params);
2911
+ check();
2912
+ const { api_base_url, ...restParams } = params;
2913
+ const res = await http.get("/canvases", { params: { ...restParams, instance_id: env.pitcher.instance.id } });
2914
+ return res;
2915
+ },
2916
+ get_canvas: async (params) => {
2917
+ logInfo("online handler get_canvas called with:", params);
2918
+ check();
2919
+ const { id, ...restParams } = params;
2920
+ const res = await http.get(`/canvases/${params.id}`, { params: restParams });
2921
+ return res;
2922
+ }
2923
+ };
2924
+
2925
+ function updateOnlineHandlersEnv(env) {
2926
+ env && setEnv(env);
2927
+ }
2736
2928
  class LowLevelApi extends EventEmitter {
2737
2929
  constructor(options) {
2738
2930
  super();
2739
2931
  this.callbacks = {};
2740
- this.options = options ?? { casing: "snake", logLevel: "off", errorLogger: () => {
2741
- } };
2932
+ this.options = options ?? {
2933
+ casing: "snake",
2934
+ logLevel: "off",
2935
+ errorLogger: () => {
2936
+ },
2937
+ fetchMode: "postmessage"
2938
+ };
2742
2939
  if (typeof window !== "undefined") {
2743
2940
  window.addEventListener("message", (event) => {
2744
2941
  if (!isOriginValid(event)) return;
@@ -2768,6 +2965,7 @@ class LowLevelApi extends EventEmitter {
2768
2965
  this.emit("event", event);
2769
2966
  }
2770
2967
  request(type, body = null) {
2968
+ const fetchMode = this.options.fetchMode ?? "prefer-online";
2771
2969
  return new Promise((resolve, reject) => {
2772
2970
  const id = v4();
2773
2971
  const callback = (res) => {
@@ -2776,6 +2974,7 @@ class LowLevelApi extends EventEmitter {
2776
2974
  resolve(
2777
2975
  this.options.casing === "camel" ? camelCaseKeys(res.response.body) : res.response.body
2778
2976
  );
2977
+ if (type === "get_env") updateOnlineHandlersEnv(res.response.body);
2779
2978
  } else if (res.response.status === "error") {
2780
2979
  this.options.errorLogger?.({
2781
2980
  message: `Pitcher JS API call failure: ${res.request.type}`,
@@ -2793,18 +2992,40 @@ class LowLevelApi extends EventEmitter {
2793
2992
  payload: payload ?? {},
2794
2993
  callback
2795
2994
  };
2796
- if (typeof window !== "undefined" && window.top) {
2797
- window.top.postMessage(
2798
- {
2799
- type: "PITCHER_REQUEST",
2800
- request: {
2801
- type,
2802
- id,
2803
- body: payload
2804
- }
2805
- },
2806
- "*"
2807
- );
2995
+ if (fetchMode === "prefer-online" && type && onlineRestApiHandlers[type]) {
2996
+ onlineRestApiHandlers[type](payload).then((data) => {
2997
+ if (this.callbacks[id]) {
2998
+ this.callbacks[id].callback({
2999
+ type: PitcherMessageType.RESPONSE,
3000
+ request: { id, type },
3001
+ response: { status: PitcherResponseStatus.OK, body: data }
3002
+ });
3003
+ delete this.callbacks[id];
3004
+ }
3005
+ }).catch((error) => {
3006
+ if (this.callbacks[id]) {
3007
+ this.callbacks[id].callback({
3008
+ type: PitcherMessageType.RESPONSE,
3009
+ request: { id, type },
3010
+ response: { status: PitcherResponseStatus.ERROR, body: error }
3011
+ });
3012
+ delete this.callbacks[id];
3013
+ }
3014
+ });
3015
+ } else {
3016
+ if (typeof window !== "undefined" && window.top) {
3017
+ window.top.postMessage(
3018
+ {
3019
+ type: "PITCHER_REQUEST",
3020
+ request: {
3021
+ type,
3022
+ id,
3023
+ body: payload
3024
+ }
3025
+ },
3026
+ "*"
3027
+ );
3028
+ }
2808
3029
  }
2809
3030
  });
2810
3031
  }
@@ -3128,51 +3349,6 @@ const dsr = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
3128
3349
  on
3129
3350
  }, Symbol.toStringTag, { value: 'Module' }));
3130
3351
 
3131
- const PITCHER_EVENT = "PITCHER_EVENT";
3132
- var PitcherMessageType = /* @__PURE__ */ ((PitcherMessageType2) => {
3133
- PitcherMessageType2["REQUEST"] = "PITCHER_REQUEST";
3134
- PitcherMessageType2["RESPONSE"] = "PITCHER_RESPONSE";
3135
- return PitcherMessageType2;
3136
- })(PitcherMessageType || {});
3137
- var PitcherResponseStatus = /* @__PURE__ */ ((PitcherResponseStatus2) => {
3138
- PitcherResponseStatus2["OK"] = "ok";
3139
- PitcherResponseStatus2["ERROR"] = "error";
3140
- return PitcherResponseStatus2;
3141
- })(PitcherResponseStatus || {});
3142
- var PitcherEventName = /* @__PURE__ */ ((PitcherEventName2) => {
3143
- PitcherEventName2["ENV_CHANGED"] = "env_changed";
3144
- PitcherEventName2["PHOTOS_CAPTURED"] = "photos_captured";
3145
- PitcherEventName2["FILE_DOWNLOADED"] = "file_downloaded";
3146
- PitcherEventName2["FILE_UPLOAD_PROGRESS"] = "file_upload_progress";
3147
- PitcherEventName2["UPDATE_LOCATION"] = "update_location";
3148
- PitcherEventName2["CANVAS_UPDATED"] = "canvas_updated";
3149
- PitcherEventName2["CANVAS_UPDATED_SUCCESS"] = "canvas_updated_success";
3150
- PitcherEventName2["FILE_CLOSED"] = "file_closed";
3151
- PitcherEventName2["APP_BACKGROUNDED"] = "app_backgrounded";
3152
- PitcherEventName2["APP_FOREGROUNDED"] = "app_foregrounded";
3153
- PitcherEventName2["NON_FILES_SYNC_FINISHED"] = "non_files_sync_finished";
3154
- PitcherEventName2["CONTENT_LIST_REFRESH_REQUESTED"] = "content_list_refresh_requested";
3155
- PitcherEventName2["NETWORK_CONNECTION_ESTABLISHED"] = "network_connection_established";
3156
- PitcherEventName2["NETWORK_CONNECTION_LOST"] = "network_connection_lost";
3157
- PitcherEventName2["ENTERED_FULLSCREEN"] = "entered_fullscreen";
3158
- PitcherEventName2["EXITED_FULLSCREEN"] = "exited_fullscreen";
3159
- PitcherEventName2["SUBMIT_POSTCALL_CLICKED"] = "submit_postcall_clicked";
3160
- return PitcherEventName2;
3161
- })(PitcherEventName || {});
3162
- var PitcherBroadcastedEventName = /* @__PURE__ */ ((PitcherBroadcastedEventName2) => {
3163
- PitcherBroadcastedEventName2["UI_SHOW_MODAL"] = "ui:show-modal";
3164
- PitcherBroadcastedEventName2["UI_HIDE_MODAL"] = "ui:hide-modal";
3165
- PitcherBroadcastedEventName2["FAVORITES_CHANGED"] = "favorites:changed";
3166
- PitcherBroadcastedEventName2["FILE_DOWNLOAD"] = "file:download";
3167
- return PitcherBroadcastedEventName2;
3168
- })(PitcherBroadcastedEventName || {});
3169
- var PitcherExternalEventName = /* @__PURE__ */ ((PitcherExternalEventName2) => {
3170
- PitcherExternalEventName2["CREATE_AND_OPEN_CANVAS"] = "create_and_open_canvas";
3171
- PitcherExternalEventName2["OPEN_CANVAS"] = "open_canvas";
3172
- PitcherExternalEventName2["START_CALL"] = "start_call";
3173
- return PitcherExternalEventName2;
3174
- })(PitcherExternalEventName || {});
3175
-
3176
3352
  let highLevelApi;
3177
3353
  function usePitcherApi(options) {
3178
3354
  if (!highLevelApi) highLevelApi = createHighLevelApi(options);