@wandelbots/nova-js
Version:
Official JS client for the Wandelbots API
336 lines (331 loc) • 10.2 kB
JavaScript
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __async = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
// src/lib/AutoReconnectingWebsocket.ts
import ReconnectingWebSocket from "reconnecting-websocket";
var AutoReconnectingWebsocket = class extends ReconnectingWebSocket {
constructor(targetUrl, opts = {}) {
console.log("Opening websocket to", targetUrl);
super(() => this.targetUrl || targetUrl, void 0, {
startClosed: true
});
this.opts = opts;
this.disposed = false;
Object.defineProperty(this, "url", {
get() {
return this.targetUrl;
}
});
this.targetUrl = targetUrl;
this.addEventListener("open", () => {
console.log(`Websocket to ${this.url} opened`);
});
this.addEventListener("message", (ev) => {
if (!this.receivedFirstMessage) {
this.receivedFirstMessage = ev;
}
});
this.addEventListener("close", () => {
console.log(`Websocket to ${this.url} closed`);
});
const origReconnect = this.reconnect;
this.reconnect = () => {
if (this.opts.mock) {
this.opts.mock.handleWebsocketConnection(this);
} else {
origReconnect.apply(this);
}
};
this.reconnect();
}
changeUrl(targetUrl) {
this.receivedFirstMessage = void 0;
this.targetUrl = targetUrl;
this.reconnect();
}
sendJson(data) {
if (this.opts.mock) {
this.opts.mock.handleWebsocketMessage(this, JSON.stringify(data));
} else {
this.send(JSON.stringify(data));
}
}
/**
* Permanently close this websocket and indicate that
* this object should not be used again.
**/
dispose() {
this.close();
this.disposed = true;
if (this.opts.onDispose) {
this.opts.onDispose();
}
}
/**
* Returns a promise that resolves once the websocket
* is in the OPEN state. */
opened() {
return __async(this, null, function* () {
return new Promise((resolve, reject) => {
if (this.readyState === WebSocket.OPEN) {
resolve();
} else {
this.addEventListener("open", () => resolve());
this.addEventListener("error", reject);
}
});
});
}
/**
* Returns a promise that resolves once the websocket
* is in the CLOSED state. */
closed() {
return __async(this, null, function* () {
return new Promise((resolve, reject) => {
if (this.readyState === WebSocket.CLOSED) {
resolve();
} else {
this.addEventListener("close", () => resolve());
this.addEventListener("error", reject);
}
});
});
}
/**
* Returns a promise that resolves when the first message
* is received from the websocket. Resolves immediately if
* the first message has already been received.
*/
firstMessage() {
return __async(this, null, function* () {
if (this.receivedFirstMessage) {
return this.receivedFirstMessage;
}
return new Promise((resolve, reject) => {
const onMessage = (ev) => {
this.receivedFirstMessage = ev;
this.removeEventListener("message", onMessage);
this.removeEventListener("error", onError);
resolve(ev);
};
const onError = (ev) => {
this.removeEventListener("message", onMessage);
this.removeEventListener("error", onError);
reject(ev);
};
this.addEventListener("message", onMessage);
this.addEventListener("error", onError);
});
});
}
/**
* Returns a promise that resolves when the next message
* is received from the websocket.
*/
nextMessage() {
return __async(this, null, function* () {
return new Promise((resolve, reject) => {
const onMessage = (ev) => {
this.removeEventListener("message", onMessage);
this.removeEventListener("error", onError);
resolve(ev);
};
const onError = (ev) => {
this.removeEventListener("message", onMessage);
this.removeEventListener("error", onError);
reject(ev);
};
this.addEventListener("message", onMessage);
this.addEventListener("error", onError);
});
});
}
};
// src/lib/availableStorage.ts
var AvailableStorage = class {
constructor() {
this.available = typeof window !== "undefined" && !!window.localStorage;
}
getJSON(key) {
if (!this.available) return null;
const result = window.localStorage.getItem(key);
if (result === null) return null;
try {
return JSON.parse(result);
} catch (err) {
return null;
}
}
setJSON(key, obj) {
if (!this.available) return null;
window.localStorage.setItem(key, JSON.stringify(obj));
}
delete(key) {
if (!this.available) return null;
window.localStorage.removeItem(key);
}
setString(key, value) {
if (!this.available) return null;
window.localStorage.setItem(key, value);
}
getString(key) {
if (!this.available) return null;
return window.localStorage.getItem(key);
}
};
var availableStorage = new AvailableStorage();
// src/lib/converters.ts
function tryParseJson(json) {
try {
return JSON.parse(json);
} catch (e) {
return void 0;
}
}
function tryStringifyJson(json) {
try {
return JSON.stringify(json);
} catch (e) {
return void 0;
}
}
function makeUrlQueryString(obj) {
const str = new URLSearchParams(obj).toString();
return str ? `?${str}` : "";
}
function radiansToDegrees(radians) {
return radians * (180 / Math.PI);
}
function degreesToRadians(degrees) {
return degrees * (Math.PI / 180);
}
function poseToWandelscriptString(pose) {
var _a, _b, _c, _d, _e, _f;
const position = [pose.position.x, pose.position.y, pose.position.z];
const orientation = [
(_b = (_a = pose.orientation) == null ? void 0 : _a.x) != null ? _b : 0,
(_d = (_c = pose.orientation) == null ? void 0 : _c.y) != null ? _d : 0,
(_f = (_e = pose.orientation) == null ? void 0 : _e.z) != null ? _f : 0
];
const positionValues = position.map((v) => v.toFixed(1));
const rotationValues = orientation.map((v) => v.toFixed(4));
return `(${positionValues.concat(rotationValues).join(", ")})`;
}
function isSameCoordinateSystem(firstCoordSystem, secondCoordSystem) {
if (!firstCoordSystem) firstCoordSystem = "world";
if (!secondCoordSystem) secondCoordSystem = "world";
return firstCoordSystem === secondCoordSystem;
}
// src/LoginWithAuth0.ts
var DOMAIN_SUFFIX = "wandelbots.io";
var auth0ConfigMap = {
dev: {
domain: `https://auth.portal.dev.${DOMAIN_SUFFIX}`,
clientId: "fLbJD0RLp5r2Dpucm5j8BjwMR6Hunfha"
},
stg: {
domain: `https://auth.portal.stg.${DOMAIN_SUFFIX}`,
clientId: "joVDeD9e786WzFNSGCqoVq7HNkWt5j6s"
},
prod: {
domain: `https://auth.portal.${DOMAIN_SUFFIX}`,
clientId: "J7WJUi38xVQdJAEBNRT9Xw1b0fXDb4J2"
}
};
var getAuth0Config = (instanceUrl) => {
if (instanceUrl.includes(`dev.${DOMAIN_SUFFIX}`)) return auth0ConfigMap.dev;
if (instanceUrl.includes(`stg.${DOMAIN_SUFFIX}`)) return auth0ConfigMap.stg;
if (instanceUrl.includes(DOMAIN_SUFFIX)) return auth0ConfigMap.prod;
throw new Error(
"Unsupported instance URL. Cannot determine Auth0 configuration."
);
};
var loginWithAuth0 = (instanceUrl) => __async(void 0, null, function* () {
var _a;
if (typeof window === "undefined") {
throw new Error(
`Access token must be set to use NovaClient when not in a browser environment.`
);
}
const auth0Config = getAuth0Config(instanceUrl);
if (new URL(instanceUrl).origin === window.location.origin) {
window.location.reload();
throw new Error(
"Failed to reload page to get auth details, please refresh manually"
);
}
const { Auth0Client } = yield import("@auth0/auth0-spa-js");
const auth0Client = new Auth0Client({
domain: auth0Config.domain,
clientId: (_a = auth0Config.clientId) != null ? _a : "",
useRefreshTokens: false,
authorizationParams: {
audience: "nova-api",
redirect_uri: window.location.origin
}
});
if (window.location.search.includes("code=") && window.location.search.includes("state=")) {
const { appState } = yield auth0Client.handleRedirectCallback();
window.history.replaceState(
{},
document.title,
(appState == null ? void 0 : appState.returnTo) || window.location.pathname
);
} else {
yield auth0Client.loginWithRedirect();
}
const accessToken = yield auth0Client.getTokenSilently();
return accessToken;
});
export {
__spreadValues,
__spreadProps,
__async,
AutoReconnectingWebsocket,
availableStorage,
tryParseJson,
tryStringifyJson,
makeUrlQueryString,
radiansToDegrees,
degreesToRadians,
poseToWandelscriptString,
isSameCoordinateSystem,
loginWithAuth0
};
//# sourceMappingURL=chunk-V3NJLR6P.js.map