koalaware-js
Version:
SDK for Koalaware session and event recording
157 lines (148 loc) • 6.15 kB
JavaScript
import React, { createContext, useState, useEffect, useContext } from 'react';
import { KoalawareTracker } from '..';
/******************************************************************************
Copyright (c) Microsoft Corporation.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise, SuppressedError, Symbol, Iterator */
function __spreadArray(to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
}
typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
var e = new Error(message);
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
};
// Check if we're in a browser environment
var isBrowser = function () { return typeof window !== 'undefined'; };
var defaultContext = {
koalaware: null,
queueEvent: function (event) {
// In server-side, just no-op
if (typeof window === 'undefined') {
return;
}
console.warn('Koalaware not initialized yet, event queued:', event);
}
};
var KoalawareContext = createContext(defaultContext);
var KoalawareProvider = function (_a) {
var apiKey = _a.apiKey, client = _a.client, children = _a.children;
var _b = useState(client || null), koalaware = _b[0], setKoalaware = _b[1];
var _c = useState([]), eventQueue = _c[0], setEventQueue = _c[1];
var _d = useState(false), isMounted = _d[0], setIsMounted = _d[1];
// Function to queue events before initialization
var queueEvent = function (event) {
setEventQueue(function (prev) { return __spreadArray(__spreadArray([], prev, true), [event], false); });
};
// Handle mounting state
useEffect(function () {
setIsMounted(true);
}, []);
useEffect(function () {
// Only run in browser
if (!(isBrowser())) {
return;
}
// Skip if not mounted yet (handles Next.js hydration)
if (!isMounted) {
return;
}
// If client is provided, use that
if (client) {
setKoalaware(client);
return;
}
// If no client is provided, apiKey is required
if (!apiKey || apiKey.trim() === '') {
console.error("An apiKey is required when no client is provided");
return;
}
if (koalaware !== null) {
return;
}
// Create new tracker instance with the validated apiKey
var tracker = new KoalawareTracker(apiKey.trim());
setKoalaware(tracker);
// Process any queued events
if (eventQueue.length > 0) {
eventQueue.forEach(function (event) {
if (event.type === 'identify') {
console.log('Processing queued identify event', event.identifier, event.userProperties);
tracker.identifyUser(event.identifier, event.userProperties);
}
else {
tracker.addEvent(event);
}
});
setEventQueue([]); // Clear the queue
}
}, [apiKey, client, eventQueue, isMounted]);
// If not in browser, render children without context
if (!(isBrowser())) {
return React.createElement(React.Fragment, null, children);
}
return (React.createElement(KoalawareContext.Provider, { value: { koalaware: koalaware, queueEvent: queueEvent } }, children));
};
var useKoalaware = function () {
var context = useContext(KoalawareContext);
// Only throw if the hook is used outside of a provider entirely
if (context === null) {
throw new Error("useKoalaware must be used within a KoalawareProvider");
}
// If we're in the server-side, return a no-op implementation
if (typeof window === 'undefined') {
console.warn('Koalaware is being used before being initialized');
return {
addEvent: function () { },
identifyUser: function () { },
start: function () { },
stop: function () { },
viewLogs: function () { },
};
}
// If we have an initialized tracker, return it as the interface
if (context.koalaware) {
return context.koalaware;
}
// If we reach here, we're in the initialization period where:
// - context.koalaware is null
// - context.queueEvent is available
// - we need to queue all operations until initialization completes
return {
addEvent: function (event) {
context.queueEvent(event);
},
identifyUser: function (identifier, userProperties) {
context.queueEvent({
type: 'identify',
identifier: identifier,
userProperties: userProperties,
});
},
start: function () {
// Start will be called automatically when initialized
},
stop: function () {
// Stop is a no-op when not initialized
},
viewLogs: function () {
console.warn('Logs are not available until KoalawareTracker is initialized');
}
};
};
export { KoalawareProvider, useKoalaware };
//# sourceMappingURL=index.js.map