sms-extension-1777535448/client/src/utils/runtimeContext.js

90 lines
2.1 KiB
JavaScript

const COMPANY_ID_QUERY_KEYS = [
'blt-gtw-fc-cid',
];
const COMPANY_ID_STORAGE_KEY = 'sms_runtime_company_id';
function getRuntimeUrl() {
if (typeof window === 'undefined') return null;
try {
return new URL(window.location.href);
} catch {
return null;
}
}
function getReferrerUrl() {
if (typeof document === 'undefined' || !document.referrer) return null;
try {
return new URL(document.referrer);
} catch {
return null;
}
}
function getPathMatch(pathname, regex) {
const match = pathname.match(regex);
return match?.[1] || '';
}
function readStoredCompanyId() {
if (typeof sessionStorage === 'undefined') return '';
try {
return (sessionStorage.getItem(COMPANY_ID_STORAGE_KEY) || '').trim();
} catch {
return '';
}
}
function persistCompanyId(companyId) {
if (!companyId || typeof sessionStorage === 'undefined') return;
try {
sessionStorage.setItem(COMPANY_ID_STORAGE_KEY, companyId);
} catch {
// Ignore storage errors; URL/referrer extraction still works for the current request.
}
}
function getFirstSearchParam(url, keys) {
if (!url) return '';
for (const key of keys) {
const value = url.searchParams.get(key);
if (value) return value.trim();
}
return '';
}
export function getRuntimeCompanyId() {
const runtimeUrl = getRuntimeUrl();
const referrerUrl = getReferrerUrl();
const companyId = (
getFirstSearchParam(runtimeUrl, COMPANY_ID_QUERY_KEYS)
|| getPathMatch(runtimeUrl?.pathname || '', /\/company\/([^/]+)/i)
|| getFirstSearchParam(referrerUrl, COMPANY_ID_QUERY_KEYS)
|| getPathMatch(referrerUrl?.pathname || '', /\/company\/([^/]+)/i)
|| readStoredCompanyId()
|| ''
);
persistCompanyId(companyId);
return companyId;
}
export function getRuntimeApplicationId() {
const runtimeUrl = getRuntimeUrl();
if (!runtimeUrl) return '';
return (
runtimeUrl.searchParams.get('applicationId')
|| runtimeUrl.searchParams.get('application_id')
|| getPathMatch(runtimeUrl.pathname, /\/application\/([^/]+)/i)
|| getPathMatch(runtimeUrl.pathname, /\/applications\/([^/]+)/i)
|| ''
).trim();
}