@habit.analytics/habit-smartlink-reactcomponent
Version:
A React component for Habit SmartLink integration.
158 lines (157 loc) • 8.82 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());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var react_1 = require("react");
var useSmartlinkParentMessaging_1 = require("./messaging/useSmartlinkParentMessaging");
var types_1 = require("./messaging/types");
var helpers_1 = require("./helpers");
/**
* String announcement sent to the iframe so the child can detect that this
* parent speaks the structured SMARTLINK_* protocol.
*
* Sent as a plain string so legacy children (if any) survive it.
* Repeated on a short interval until the child responds with SMARTLINK_READY,
* which proves it received the announcement and is proceeding with the
* structured handshake.
*
* ── LEGACY DEPRECATION: delete the announcement effect ──
*/
var STRUCTURED_ANNOUNCEMENT = "SMARTLINK_STRUCTURED";
var ANNOUNCEMENT_INTERVAL_MS = 500;
var ANNOUNCEMENT_MAX_ATTEMPTS = 10;
var useSmartlinkComponent = function (prePaymentMethod, onPaymentSuccess, env) {
var _a, _b;
var iframeRef = (0, react_1.useRef)(null);
var enviroment = env !== null && env !== void 0 ? env : (0, helpers_1.getEnviroment)((_b = (_a = window === null || window === void 0 ? void 0 : window.location) === null || _a === void 0 ? void 0 : _a.href) !== null && _b !== void 0 ? _b : "");
var pluginUrl = helpers_1.SMARTLINK_BASE_URL[enviroment];
var pluginOrigin = pluginUrl ? new URL(pluginUrl).origin : null;
var _c = (0, useSmartlinkParentMessaging_1.useSmartlinkParentMessaging)({
pluginUrl: pluginUrl,
iframeRef: iframeRef,
}), sendInit = _c.sendInit, sendMessage = _c.sendMessage, subscribeTo = _c.subscribeTo;
/*
* ── LEGACY DEPRECATION: delete this effect ──
*
* Announce to the child that this parent is structured.
* Repeats until SMARTLINK_READY arrives (proving the child heard us)
* or max attempts are exhausted.
*/
(0, react_1.useEffect)(function () {
var _a, _b;
if (!pluginOrigin)
return;
var attempts = 0;
var interval = setInterval(function () {
var _a, _b;
attempts++;
(_b = (_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow) === null || _b === void 0 ? void 0 : _b.postMessage(STRUCTURED_ANNOUNCEMENT, pluginOrigin);
if (attempts >= ANNOUNCEMENT_MAX_ATTEMPTS)
clearInterval(interval);
}, ANNOUNCEMENT_INTERVAL_MS);
// Also fire one immediately (interval waits one tick before first call).
(_b = (_a = iframeRef.current) === null || _a === void 0 ? void 0 : _a.contentWindow) === null || _b === void 0 ? void 0 : _b.postMessage(STRUCTURED_ANNOUNCEMENT, pluginOrigin);
var unsubscribe = subscribeTo("SMARTLINK_READY", function () {
clearInterval(interval);
});
return function () {
clearInterval(interval);
unsubscribe();
};
}, [pluginOrigin, subscribeTo]);
(0, react_1.useEffect)(function () {
return subscribeTo("SMARTLINK_READY", function (_a, _event, isValid) {
var requestId = _a.requestId;
if (!isValid) {
console.warn("[SMARTLINK_HANDSHAKE] Origin validation failed — not sending SMARTLINK_INIT");
return;
}
sendInit(requestId);
});
}, [subscribeTo, sendInit]);
(0, react_1.useEffect)(function () {
return subscribeTo("SMARTLINK_STEP_COMPLETE", function (message, _event, isValid) {
var _a;
if (!isValid) {
console.warn("[SMARTLINK_STEP_COMPLETE] Origin validation failed — not sending SMARTLINK_STEP_COMPLETE");
return;
}
var _b = (_a = message === null || message === void 0 ? void 0 : message.payload) !== null && _a !== void 0 ? _a : {}, success = _b.success, source = _b.source, payment_data = _b.payment_data, _consent = _b.consent_data, _uploader = _b.uploader_data;
if (!success || source !== "payments")
return;
onPaymentSuccess(payment_data || JSON.stringify({}));
});
}, [subscribeTo, onPaymentSuccess]);
(0, react_1.useEffect)(function () {
return subscribeTo("SMARTLINK_PREPAYMENT_METHOD", function (message, _event, isValid) { return __awaiter(void 0, void 0, void 0, function () {
var requestId, payload, quote_id, _a, success, payment_id, err_1;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!isValid) {
console.warn("[SMARTLINK_PREPAYMENT_METHOD] Origin validation failed — not sending SMARTLINK_PREPAYMENT_METHOD_COMPLETE");
return [2 /*return*/];
}
requestId = message.requestId, payload = message.payload;
quote_id = (payload !== null && payload !== void 0 ? payload : {}).quote_id;
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, prePaymentMethod(quote_id !== null && quote_id !== void 0 ? quote_id : "")];
case 2:
_a = _b.sent(), success = _a.success, payment_id = _a.payment_id;
sendMessage((0, types_1.createSmartlinkMessage)("SMARTLINK_PREPAYMENT_METHOD_COMPLETE", { success: success, payment_id: payment_id }, requestId));
return [3 /*break*/, 4];
case 3:
err_1 = _b.sent();
sendMessage((0, types_1.createSmartlinkMessage)("SMARTLINK_PREPAYMENT_METHOD_COMPLETE", {
success: false,
payment_id: "",
error: err_1 instanceof Error ? err_1.message : String(err_1),
}, requestId));
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); });
}, [subscribeTo, sendMessage, prePaymentMethod]);
return {
iframeRef: iframeRef,
enviroment: enviroment,
};
};
exports.default = useSmartlinkComponent;