@tyrads.com/tyrads-sdk-iframe
Version:
Official TyrAds SDK for NodeJS
182 lines (181 loc) • 9.24 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TyradsSDK = exports.resolveIframeBaseUrl = void 0;
exports.resolveAuthPath = resolveAuthPath;
exports.isV4OrAbove = isV4OrAbove;
const config_1 = require("./config");
const authentication_request_1 = require("./contract/authentication-request");
const authentication_sign_1 = require("./contract/authentication-sign");
const env_var_1 = require("./enum/env-var");
const http_client_1 = require("./http-client");
var config_2 = require("./config");
Object.defineProperty(exports, "resolveIframeBaseUrl", { enumerable: true, get: function () { return config_2.resolveIframeBaseUrl; } });
/**
* Resolves the auth endpoint path for the given API version.
* v3 and earlier expose POST /auth at the version prefix.
* v4 and later moved auth under POST /initialize/auth.
* Unrecognized version strings fall back to the latest layout.
*/
function resolveAuthPath(apiVersion) {
const major = parseInt(apiVersion.toLowerCase().replace(/^v/, '').split('.')[0], 10);
if (Number.isNaN(major) || major >= 4) {
return '/initialize/auth';
}
return '/auth';
}
/**
* Returns true when the given API version is v4 or later (or unrecognized,
* in which case we treat it as the latest supported version).
*/
function isV4OrAbove(apiVersion) {
const major = parseInt(apiVersion.toLowerCase().replace(/^v/, '').split('.')[0], 10);
return Number.isNaN(major) || major >= 4;
}
class TyradsSDK {
/**
* Creates an instance of TyradsSDK.
* @param {Config} config - The configuration object for the SDK.
*/
constructor(config) {
this.config = config;
this.httpClient = (0, http_client_1.getHttpClient)(this.config);
}
/**
* Creates an instance of TyradsSDK.
* @param apiKey - The API key for authentication.
* @param apiSecret - The API secret for authentication.
* @param language - The language for the SDK (default is 'en').
* @param apiVersion - Optional API version override (e.g. 'v3.0', 'v4.0'). Defaults to the SDK's latest supported version when omitted.
* @returns An instance of TyradsSDK.
*/
static make(apiKey, apiSecret, language = 'en', apiVersion) {
var _a, _b;
const initArgs = {
apiKey: (_a = apiKey !== null && apiKey !== void 0 ? apiKey : process.env[env_var_1.EnvVar.TYRADS_API_KEY]) !== null && _a !== void 0 ? _a : '',
apiSecret: (_b = apiSecret !== null && apiSecret !== void 0 ? apiSecret : process.env[env_var_1.EnvVar.TYRADS_API_SECRET]) !== null && _b !== void 0 ? _b : '',
language,
};
if (apiVersion !== undefined) {
initArgs.sdkApiVersion = apiVersion;
}
return new TyradsSDK((0, config_1.init)(initArgs));
}
/**
* Authenticates a user with the Tyrads SDK.
* @param {AuthenticationRequest} request - The authentication request containing user details.
* @returns {Promise<AuthenticationSign | null>} A promise that resolves to an AuthenticationSign object if authentication is successful, or null if it fails.
* @throws {Error}
* @description This method validates the authentication request, sends it to the Tyrads API,
* and returns an AuthenticationSign object containing the authentication token, publisher user ID, age,
* and gender.
*/
authenticate(request) {
return __awaiter(this, void 0, void 0, function* () {
(0, authentication_request_1.validateAuthenticationRequest)(request);
const data = (0, authentication_request_1.getParsedAuthenticationRequestData)(request);
const response = yield this.httpClient.post(resolveAuthPath(this.config.sdkApiVersion), data);
if (response.data['data'] && response.data['data']['token']) {
return new authentication_sign_1.AuthenticationSign(response.data['data']['token'], request.publisherUserId);
}
return null;
});
}
/**
* Generates an iframe URL for the Tyrads SDK.
* @param {AuthenticationSign | string} authSignOrToken - An instance of AuthenticationSign or a string token.
* @param {string | null} deeplinkTo - Optional deeplink to redirect after authentication.
* @param {number | null} placementId - Optional placement ID forwarded as the `placementId` query param. v4+ only.
* @returns {string} The generated iframe URL.
* @throws {Error} If the arguments are invalid.
* @throws {Error} If the deeplinkTo argument is not a string or null.
* @throws {Error} If placementId is provided and the SDK is configured for an API version below v4.
* @description This method constructs a URL for the Tyrads iframe, including the authentication token
* and an optional deeplink parameter. The token can be provided as an instance of AuthenticationSign or as a string.
* If the deeplinkTo parameter is provided, it will be included in the URL as a query parameter.
*/
iframeUrl(authSignOrToken, deeplinkTo = null, placementId = null) {
let token = '';
if (typeof authSignOrToken === 'string') {
token = authSignOrToken;
}
else if (authSignOrToken instanceof authentication_sign_1.AuthenticationSign) {
token = authSignOrToken.getToken();
}
else {
throw new Error("Invalid argument: must be an instance of AuthenticationSign or a string token.");
}
if (typeof deeplinkTo !== 'string' && deeplinkTo !== null) {
throw new Error("Invalid deeplinkTo argument: must be a string or null.");
}
this.assertValidPlacementId(placementId);
let url = `${this.config.iFrameBaseUrl}?token=${encodeURIComponent(token)}`;
if (deeplinkTo) {
url += `&to=${encodeURIComponent(deeplinkTo)}`;
}
if (placementId !== null) {
url += `&placementId=${placementId}`;
}
return url;
}
/**
* Generates a URL for the premium widget iframe.
*
* @param authSignOrToken - Authentication token or AuthenticationSign instance for authorization
* @param name - Optional name parameter to be included in the URL
* @param placementId - Optional placement ID forwarded as the `placementId` query param. v4+ only.
* @returns A fully constructed URL string for the iframe widget
*
* @throws {Error} If authSignOrToken is neither a string nor an AuthenticationSign instance
* @throws {Error} If name is provided but is not a string
* @throws {Error} If placementId is provided and the SDK is configured for an API version below v4.
*
* @description This method constructs a URL for the Tyrads premium widget iframe, including the authentication token
* and an optional name parameter. The token can be provided as an instance of AuthenticationSign or as a string.
* If the name parameter is provided, it will be included in the URL as a query parameter.
*/
iframePremiumWidget(authSignOrToken, name = null, placementId = null) {
let token = '';
if (typeof authSignOrToken === 'string') {
token = authSignOrToken;
}
else if (authSignOrToken instanceof authentication_sign_1.AuthenticationSign) {
token = authSignOrToken.getToken();
}
else {
throw new Error("Invalid argument: must be an instance of AuthenticationSign or a string token.");
}
if (typeof name !== 'string' && name !== null) {
throw new Error("Invalid name argument: must be a string or null.");
}
this.assertValidPlacementId(placementId);
let url = `${this.config.iFrameBaseUrl}/widget?token=${encodeURIComponent(token)}`;
if (name) {
url += `&name=${encodeURIComponent(name)}`;
}
if (placementId !== null) {
url += `&placementId=${placementId}`;
}
return url;
}
assertValidPlacementId(placementId) {
if (placementId === null) {
return;
}
if (typeof placementId !== 'number' || !Number.isInteger(placementId) || placementId <= 0) {
throw new Error("Invalid placementId argument: must be a positive integer or null.");
}
if (!isV4OrAbove(this.config.sdkApiVersion)) {
throw new Error("placementId is only supported on iframe v4 and above.");
}
}
}
exports.TyradsSDK = TyradsSDK;