|
| 1 | +import snippet, { defaultScriptURL } from "./snippet"; |
| 2 | +import api from "./api"; |
| 3 | +const sdkOptionsDefaults = { |
| 4 | + devMode: false, |
| 5 | + scriptURL: defaultScriptURL, |
| 6 | +}; |
| 7 | +let opts = Object.assign({}, sdkOptionsDefaults); |
| 8 | +const isLoaded = () => window.__ls; |
| 9 | +const getApiMethod = (name) => { |
| 10 | + if (!isLoaded()) { |
| 11 | + throw new Error("LiveSession is not loaded. Call init() before calling other API functions"); |
| 12 | + } |
| 13 | + const objectAPI = api; |
| 14 | + if (!objectAPI.hasOwnProperty(name)) { |
| 15 | + throw new Error(`method "${name}" doesn't exist`); |
| 16 | + } |
| 17 | + if (opts.devMode) { |
| 18 | + const msg = `Skipping method: ${name}, devMode enabled`; |
| 19 | + console.warn(msg); |
| 20 | + return () => msg; |
| 21 | + } |
| 22 | + return objectAPI[name]; |
| 23 | +}; |
| 24 | +const safeCall = (name) => { |
| 25 | + return (args) => { |
| 26 | + const apiMethod = getApiMethod(name); |
| 27 | + if (apiMethod) { |
| 28 | + return apiMethod(args); |
| 29 | + } |
| 30 | + }; |
| 31 | +}; |
| 32 | +const safeCallManyArgs = (name) => { |
| 33 | + return (...args) => { |
| 34 | + const apiMethod = getApiMethod(name); |
| 35 | + if (apiMethod) { |
| 36 | + return apiMethod(...args); |
| 37 | + } |
| 38 | + }; |
| 39 | +}; |
| 40 | +const _init = (trackID, options, sdkOptions = sdkOptionsDefaults) => { |
| 41 | + opts = Object.assign(Object.assign({}, sdkOptionsDefaults), sdkOptions); |
| 42 | + if (isLoaded()) { |
| 43 | + console.warn("LiveSession already inited (skipping init() call)"); |
| 44 | + return; |
| 45 | + } |
| 46 | + if (!trackID) { |
| 47 | + throw new Error(`trackID is required`); |
| 48 | + } |
| 49 | + snippet(window, document, "script", sdkOptions.scriptURL); |
| 50 | + return api.init(trackID, options); |
| 51 | +}; |
| 52 | +export default { |
| 53 | + init: _init, |
| 54 | + getSessionURL: safeCall("getSessionURL"), |
| 55 | + identify: safeCall("identify"), |
| 56 | + invalidateSession: safeCall("invalidateSession"), |
| 57 | + newPageView: safeCall("newPageView"), |
| 58 | + setOptions: safeCall("setOptions"), |
| 59 | + setCustomParams: safeCall("setCustomParams"), |
| 60 | + off: safeCall("off"), |
| 61 | + optOut: safeCall("optOut"), |
| 62 | + debug: safeCall("debug"), |
| 63 | + track: function (eventName, properties) { |
| 64 | + safeCallManyArgs("track")(eventName, properties); |
| 65 | + }, |
| 66 | + log: function (logLevel, ...args) { |
| 67 | + safeCallManyArgs("log")(logLevel, ...args); |
| 68 | + }, |
| 69 | +}; |
0 commit comments