@realtek/core-theme-live 0.0.338

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authApi-Df2m5aPG.cjs","names":[],"sources":["../src/services/apiConfig.js","../src/services/authApi.js"],"sourcesContent":["// Central API base URLs.\n//\n// When CORE-THEME runs standalone (npm run dev), the values come from\n// src/services/.env (Vite VITE_* vars, baked in at build time).\n//\n// When CORE-THEME is consumed as the published @realtek/core-theme package,\n// host apps can override these values at RUNTIME by setting\n// `window.__CORE_THEME_CONFIG__` before the app renders:\n//\n// <script>\n// window.__CORE_THEME_CONFIG__ = {\n// VITE_AUTH_URL: 'http://192.168.1.66/authapi/v1',\n// VITE_SUBMISSIONS_URL: 'http://192.168.1.66/submissionsapi/v1',\n// VITE_JOBS_URL: 'http://192.168.1.66/jobsapi/v1',\n// VITE_CANDIDATES_URL: 'http://192.168.1.66/candidatesapi/v1',\n// VITE_APP_ID: 'zinnext', // sent as the `X-App-Id` header on every API call\n// VITE_ADMIN_APP_ID: 'zinnext', // optional admin override\n// };\n// </script>\n//\n// Priority: runtime window config > build-time .env fallback.\n\nconst BUILD_TIME_FALLBACK = {\n VITE_AUTH_URL: import.meta.env.VITE_AUTH_URL,\n VITE_ADMIN_API_URL: import.meta.env.VITE_ADMIN_API_URL,\n VITE_ADMIN_APP_ID: import.meta.env.VITE_ADMIN_APP_ID,\n VITE_SUBMISSIONS_URL: import.meta.env.VITE_SUBMISSIONS_URL,\n VITE_JOBS_URL: import.meta.env.VITE_JOBS_URL,\n VITE_CANDIDATES_URL: import.meta.env.VITE_CANDIDATES_URL,\n VITE_PYOPS_URL: import.meta.env.VITE_PYOPS_URL,\n VITE_APP_ID: import.meta.env.VITE_APP_ID,\n};\n\nfunction resolve(key) {\n if (\n typeof window !== 'undefined' &&\n window.__CORE_THEME_CONFIG__ &&\n window.__CORE_THEME_CONFIG__[key] != null\n ) {\n return window.__CORE_THEME_CONFIG__[key];\n }\n return BUILD_TIME_FALLBACK[key];\n}\n\nfunction runtimeValue(key, fallback = '') {\n return {\n toString: () => resolve(key) || (typeof fallback === 'function' ? fallback() : fallback),\n valueOf: () => resolve(key) || (typeof fallback === 'function' ? fallback() : fallback),\n [Symbol.toPrimitive]: () => resolve(key) || (typeof fallback === 'function' ? fallback() : fallback),\n };\n}\n\n// These are intentionally dynamic. Many service files use them inside template\n// literals (`${AUTH_URL}/path`) or pass them to helpers that later build a URL.\n// ── Three backends, one gateway ────────────────────────────────────────────────\n//\n// The frontend now talks to THREE logical services, all served by the one\n// BE-CORE-THEME gateway:\n//\n// VITE_CORE_URL → becoretheme : the common platform (auth, jobs, candidates,\n// submissions — everything both apps share)\n// VITE_ZINNEXT_URL → bezinnext : zinnext-only features\n// VITE_PYOPS_URL → pyops : the Python service (unchanged)\n//\n// A host configures these three (or just VITE_GATEWAY_URL and let them derive).\n// The four legacy per-domain constants below (AUTH_URL/JOBS_URL/SUBMISSIONS_URL/\n// CANDIDATES_URL) still exist so the many existing service files keep working —\n// they now resolve to origin sub-namespaces UNDER becoretheme. That sub-path is\n// what keeps the 6 dual-called paths (/notes via auth vs jobs, /delete via\n// candidates vs jobs, …) reaching the right backend; a flat URL could not.\n//\n// Precedence for each value: explicit VITE_*_URL > derived from CORE/ZINNEXT/\n// gateway > legacy direct fallback.\n\n// baseFrom returns the first non-empty of: explicit key, one of the fallbacks.\nfunction firstConfigured(explicitKey, ...fallbacks) {\n return runtimeValue(explicitKey, () => {\n for (const f of fallbacks) {\n const v = typeof f === 'function' ? f() : f;\n if (v) return String(v).replace(/\\/+$/, '');\n }\n return '';\n });\n}\nconst gw = () => { const g = resolve('VITE_GATEWAY_URL'); return g ? String(g).replace(/\\/+$/, '') : ''; };\n\n// The three services. becoretheme/bezinnext default to gateway sub-paths.\nexport const CORE_URL = firstConfigured('VITE_CORE_URL', () => (gw() ? gw() + '/becoretheme' : ''));\nexport const ZINNEXT_URL = firstConfigured('VITE_ZINNEXT_URL', () => (gw() ? gw() + '/bezinnext' : ''));\nexport const PYOPS_URL = firstConfigured('VITE_PYOPS_URL', () => (gw() ? gw() + '/pyops/v1' : ''), 'http://192.168.1.66/pyopsapi/v1');\nexport const GATEWAY_URL = runtimeValue('VITE_GATEWAY_URL');\n\n// Legacy per-domain constants — now origin sub-namespaces under becoretheme.\n// An explicit VITE_*_URL still overrides, for pointing one backend elsewhere.\nexport const AUTH_URL = firstConfigured('VITE_AUTH_URL',\n () => (String(CORE_URL) ? String(CORE_URL) + '/authapi/v1' : ''), 'http://192.168.1.66/authapi/v1');\nexport const JOBS_URL = firstConfigured('VITE_JOBS_URL',\n () => (String(CORE_URL) ? String(CORE_URL) + '/jobsapi/v1' : ''), 'http://192.168.1.66/jobsapi/v1');\nexport const SUBMISSIONS_URL = firstConfigured('VITE_SUBMISSIONS_URL',\n () => (String(CORE_URL) ? String(CORE_URL) + '/submissionsapi/v1' : ''), 'http://192.168.1.66/submissionsapi/v1');\nexport const CANDIDATES_URL = firstConfigured('VITE_CANDIDATES_URL',\n () => (String(CORE_URL) ? String(CORE_URL) + '/candidatesapi/v1' : ''), 'http://192.168.1.66/candidatesapi/v1');\n\n// Admin calls ride the auth namespace under becoretheme (gateway routes\n// /authapi/v1/admin/* to the auth backend), so this tracks AUTH_URL.\nexport const ADMIN_API_URL = firstConfigured('VITE_ADMIN_API_URL',\n () => resolve('VITE_AUTH_URL') || (String(CORE_URL) ? String(CORE_URL) + '/authapi/v1' : ''), 'http://localhost:9009');\nexport const ADMIN_APP_ID = runtimeValue('VITE_ADMIN_APP_ID', () => resolve('VITE_APP_ID') || 'zinnext-dev-api-v1');\n\n// App identifier sent as the `X-App-Id` header on every API request (e.g.\n// 'zinnext', 'lms'). Configured in ONE place — the host's window config (or the\n// build-time .env fallback) — and applied to all calls via the interceptor below.\nexport const APP_ID = runtimeValue('VITE_APP_ID');\n\n// Helper for code that builds headers explicitly: merges `X-App-Id` into a\n// header object without clobbering anything else. (The interceptor below already\n// covers existing calls; this is just a convenience for new code.)\nexport function withAppId(headers = {}) {\n const appId = resolve('VITE_APP_ID');\n return appId ? { 'X-App-Id': appId, ...headers } : { ...headers };\n}\n\nexport function withAdminAppId(headers = {}) {\n const appId = resolve('VITE_ADMIN_APP_ID') || resolve('VITE_APP_ID') || 'zinnext-dev-api-v1';\n return appId ? { 'X-App-Id': appId, ...headers } : { ...headers };\n}\n\n// ── X-App-Id interceptor ──────────────────────────────────────────────────────\n//\n// Rather than editing every inline `headers: {...}` across the service files\n// (and risking new calls forgetting it), we patch `fetch` ONCE so every request\n// to a configured API base URL carries `X-App-Id`. This is scoped strictly to the\n// four API origins, so third-party/asset requests are never touched, and any\n// caller that already set `X-App-Id` explicitly is left as-is.\nfunction installAppIdInterceptor() {\n if (typeof window === 'undefined' || typeof window.fetch !== 'function') return;\n // Guard against double-patching (repeated imports / Vite HMR).\n if (window.__CORE_THEME_APP_ID_PATCHED__) return;\n\n const apiBaseUrls = [AUTH_URL, ADMIN_API_URL, SUBMISSIONS_URL, JOBS_URL, CANDIDATES_URL, PYOPS_URL];\n const originalFetch = window.fetch.bind(window);\n\n const urlOf = (input) => {\n if (typeof input === 'string') return input;\n if (input instanceof URL) return input.href;\n if (input && typeof input.url === 'string') return input.url; // Request object\n return '';\n };\n const isApiRequest = (url) =>\n !!url && apiBaseUrls.some((base) => {\n const value = String(base);\n return value && url.startsWith(value);\n });\n\n window.fetch = function patchedFetch(input, init) {\n try {\n const url = urlOf(input);\n const isAdminRequest = String(ADMIN_API_URL) && url.startsWith(String(ADMIN_API_URL));\n const appId = isAdminRequest\n ? (resolve('VITE_ADMIN_APP_ID') || resolve('VITE_APP_ID') || 'zinnext-dev-api-v1')\n : resolve('VITE_APP_ID');\n if (appId && isApiRequest(url)) {\n const isRequestObj = typeof Request !== 'undefined' && input instanceof Request;\n const headers = new Headers(\n (init && init.headers) || (isRequestObj ? input.headers : undefined),\n );\n if (!headers.has('X-App-Id')) headers.set('X-App-Id', appId);\n if (isRequestObj && !(init && init.headers)) {\n return originalFetch(new Request(input, { headers }), init);\n }\n return originalFetch(input, { ...(init || {}), headers });\n }\n } catch {\n // Any unexpected argument shape: fall through to the untouched request.\n }\n return originalFetch(input, init);\n };\n\n window.__CORE_THEME_APP_ID_PATCHED__ = true;\n}\n\ninstallAppIdInterceptor();\n\n// Optional JS helper (alternative to the index.html <script>). Because the\n// exports above are resolved when this module first loads, call this BEFORE the\n// first import of @realtek/core-theme — e.g. in the host's index.html, not in\n// main.jsx (which runs after imports are evaluated). The index.html <script>\n// approach is the reliable one.\nexport function configureCoreTheme(config = {}) {\n if (typeof window === 'undefined') return;\n window.__CORE_THEME_CONFIG__ = { ...(window.__CORE_THEME_CONFIG__ || {}), ...config };\n installAppIdInterceptor();\n}\n","import { AUTH_URL, withAppId } from './apiConfig';\n\nconst AUTH_TOKEN_KEY = 'authToken';\nconst AUTH_USER_KEY = 'authUser';\nconst AUTH_LOGIN_SESSION_KEY = 'authLoginSession';\nconst CT_PROJECT_ID_KEY = 'ct_project_id';\nconst CT_PROJECT_NAME_KEY = 'ct_project_name';\nconst LOGIN_STORAGE_KEYS = [\n 'access_token', 'refresh_token', 'id_token', 'token_type', 'expires_in',\n 'refresh_expires_in', 'menu', 'footermenu', 'menuPermission', 'default_values',\n 'roleId', 'companyName', 'preferred_Username', 'user_Email', 'userName',\n 'userId', 'tenantId', 'businessId', 'businessUnitId', 'activeKey',\n 'ct_project_id', 'ct_project_name',\n];\n\nlet loginPromise = null;\nlet runtimeAuthToken = null;\n\nexport function setAuthTokenOverride(token) {\n runtimeAuthToken = typeof token === 'string' && token.trim() ? token.trim() : null;\n}\n\nexport function clearAuthTokenOverride() {\n runtimeAuthToken = null;\n}\n\nfunction extractToken(json) {\n return (\n json?.token ?? json?.access_token ?? json?.accessToken ?? json?.jwt ??\n json?.data?.token ?? json?.data?.access_token ?? json?.data?.accessToken ?? json?.data?.jwt\n );\n}\n\nfunction extractUser(json) {\n return json?.user ?? json?.data?.user ?? json?.data?.profile ?? null;\n}\n\nfunction decodeJwtPayload(token) {\n if (!token || typeof token !== 'string') return null;\n try {\n const payload = token.split('.')[1];\n if (!payload) return null;\n const normalized = payload.replace(/-/g, '+').replace(/_/g, '/');\n return JSON.parse(atob(normalized.padEnd(Math.ceil(normalized.length / 4) * 4, '=')));\n } catch {\n return null;\n }\n}\n\nfunction setLocalStorageJson(key, value) {\n if (value === undefined || value === null) return;\n localStorage.setItem(key, JSON.stringify(value));\n}\n\nfunction getLoginMenus(json, data) {\n return data?.menus ?? json?.menus ?? {\n menu: data?.menu ?? json?.menu,\n footermenu: data?.footermenu ?? json?.footermenu,\n };\n}\n\nfunction persistLoginResponse(json, token, user) {\n const data = json?.data ?? json;\n const tokenPayload = decodeJwtPayload(token) ?? {};\n const menus = getLoginMenus(json, data);\n const userName = (\n user?.userName ?? user?.name ?? data?.userName ?? data?.name ??\n tokenPayload.userName ?? tokenPayload.name ?? tokenPayload.preferred_username ?? tokenPayload.email\n );\n const preferredUsername = (\n user?.preferred_Username ?? user?.preferred_username ??\n data?.preferred_Username ?? data?.preferred_username ??\n tokenPayload.preferred_Username ?? tokenPayload.preferred_username ??\n tokenPayload.email ?? userName\n );\n const userEmail = user?.email ?? data?.email ?? tokenPayload.email ?? preferredUsername;\n\n localStorage.setItem('access_token', token);\n if (data?.refresh_token) localStorage.setItem('refresh_token', data.refresh_token);\n if (data?.id_token !== undefined) localStorage.setItem('id_token', data.id_token);\n if (data?.token_type) localStorage.setItem('token_type', data.token_type);\n if (data?.expires_in !== undefined) localStorage.setItem('expires_in', String(data.expires_in));\n if (data?.refresh_expires_in !== undefined) localStorage.setItem('refresh_expires_in', String(data.refresh_expires_in));\n if (userName) localStorage.setItem('userName', userName);\n if (preferredUsername) localStorage.setItem('preferred_Username', preferredUsername);\n if (userEmail) localStorage.setItem('user_Email', userEmail);\n if (data?.roleId ?? tokenPayload.role_id) localStorage.setItem('roleId', data?.roleId ?? tokenPayload.role_id);\n if (data?.companyName) localStorage.setItem('companyName', data.companyName);\n if (tokenPayload.userId !== undefined) localStorage.setItem('userId', String(tokenPayload.userId));\n if (tokenPayload.tenantId) localStorage.setItem('tenantId', tokenPayload.tenantId);\n if (tokenPayload.businessId) localStorage.setItem('businessId', tokenPayload.businessId);\n if (tokenPayload.businessUnitId) localStorage.setItem('businessUnitId', tokenPayload.businessUnitId);\n\n setLocalStorageJson('menu', menus.menu);\n setLocalStorageJson('footermenu', menus.footermenu);\n setLocalStorageJson('menuPermission', data?.menuPermission);\n setLocalStorageJson('default_values', data?.default_values);\n}\n\n// ── Token & Session ──────────────────────────────────────────────────────────\n\nexport function getStoredToken() {\n if (runtimeAuthToken) return runtimeAuthToken;\n const token = localStorage.getItem(AUTH_TOKEN_KEY);\n const hasSession = sessionStorage.getItem(AUTH_LOGIN_SESSION_KEY) === '1';\n return token && hasSession ? token : null;\n}\n\nexport function getStoredUser() {\n try {\n const stored = localStorage.getItem(AUTH_USER_KEY);\n if (stored) return JSON.parse(stored);\n } catch {\n // Fall through to the legacy login fields below.\n }\n return {\n userId: localStorage.getItem('userId'),\n username: localStorage.getItem('userName') || localStorage.getItem('preferred_Username'),\n email: localStorage.getItem('user_Email'),\n roleId: localStorage.getItem('roleId'),\n };\n}\n\nexport function logout() {\n // No response may outlive the session that was entitled to it.\n invalidateGetCache();\n localStorage.removeItem(AUTH_TOKEN_KEY);\n localStorage.removeItem(AUTH_USER_KEY);\n LOGIN_STORAGE_KEYS.forEach((key) => localStorage.removeItem(key));\n sessionStorage.removeItem(AUTH_LOGIN_SESSION_KEY);\n window.dispatchEvent(new Event('auth:logout'));\n}\n\n// ── Role Helpers ─────────────────────────────────────────────────────────────\n\nexport function getCurrentRoleName() {\n const stored = String(localStorage.getItem('roleId') ?? '').trim().toLowerCase();\n if (stored) return stored;\n const payload = decodeJwtPayload(getStoredToken()) ?? {};\n return String(payload.role ?? payload.roleName ?? payload.role_name ?? payload.role_id ?? payload.roleId ?? '').trim().toLowerCase();\n}\n\nexport function getUserRoles() {\n const token = getStoredToken() ?? localStorage.getItem(AUTH_TOKEN_KEY);\n const payload = decodeJwtPayload(token);\n const roles = new Set();\n const stored = getCurrentRoleName();\n if (stored) roles.add(stored);\n if (payload) {\n (payload?.realm_access?.roles ?? []).forEach((role) => roles.add(role));\n Object.values(payload?.resource_access ?? {}).forEach((client) => {\n (client?.roles ?? []).forEach((role) => roles.add(role));\n });\n [payload?.role, payload?.roleName, payload?.role_name].forEach((role) => {\n if (role) roles.add(role);\n });\n }\n return Array.from(roles).map((role) => String(role).toLowerCase());\n}\n\nexport function isTester() {\n return getCurrentRoleName() === 'tester' || getUserRoles().includes('tester');\n}\n\n// getActingIdentity returns the numeric {roleId, userId} of the logged-in user,\n// read from the auth token (falling back to the stored roleId). Used to evaluate\n// admin-configured field autoValueRules for UX only — the gateway re-evaluates\n// the same rules from the token and has the final say, so nothing here is a\n// security boundary.\nexport function getActingIdentity() {\n const payload = decodeJwtPayload(getStoredToken() ?? localStorage.getItem(AUTH_TOKEN_KEY)) ?? {};\n const num = (value) => {\n if (value === undefined || value === null || value === '') return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) ? parsed : undefined;\n };\n return {\n roleId: num(payload.role_id ?? payload.roleId) ?? num(localStorage.getItem('roleId')),\n userId: num(payload.userId ?? payload.user_id),\n };\n}\n\n// ── Project Context ───────────────────────────────────────────────────────────\n\nexport function setSelectedProject(project) {\n if (!project) return;\n localStorage.setItem(CT_PROJECT_ID_KEY, String(project.id));\n localStorage.setItem(CT_PROJECT_NAME_KEY, String(project.name));\n}\n\nexport function getSelectedProject() {\n const id = localStorage.getItem(CT_PROJECT_ID_KEY);\n const name = localStorage.getItem(CT_PROJECT_NAME_KEY);\n if (!id || !name) return null;\n return { id: Number(id), name };\n}\n\nexport function clearSelectedProject() {\n localStorage.removeItem(CT_PROJECT_ID_KEY);\n localStorage.removeItem(CT_PROJECT_NAME_KEY);\n}\n\n// ── Login ────────────────────────────────────────────────────────────────────\n\nexport async function login(credentials) {\n if (loginPromise) return loginPromise;\n\n loginPromise = fetch(`${AUTH_URL}/login`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(credentials),\n })\n .then(async (res) => {\n const json = await res.json();\n if (!res.ok) {\n const error = new Error(json?.message ?? json?.error ?? `Login failed: ${res.status}`);\n error.status = res.status;\n throw error;\n }\n const token = extractToken(json);\n if (!token) throw new Error('No token in login response');\n const user = extractUser(json);\n localStorage.setItem(AUTH_TOKEN_KEY, token);\n sessionStorage.setItem(AUTH_LOGIN_SESSION_KEY, '1');\n if (user) localStorage.setItem(AUTH_USER_KEY, JSON.stringify(user));\n persistLoginResponse(json, token, user);\n // Let any mounted AuthGuard re-check and reveal the protected content.\n window.dispatchEvent(new Event('auth:login'));\n return { token, user, response: json };\n })\n .finally(() => { loginPromise = null; });\n\n return loginPromise;\n}\n\n// ── HTTP Helpers (exported for use by other service files) ───────────────────\n\nexport async function ensureToken() {\n const token = getStoredToken();\n if (token) return token;\n const error = new Error('Authentication required');\n error.status = 401;\n throw error;\n}\n\nasync function authHeaders() {\n const token = await ensureToken();\n // Normal application API calls must always target the currently selected\n // project database. Do not let the global fetch interceptor infer this from\n // the URL because AUTH_URL and ADMIN_API_URL may point to the same service.\n // Explicit X-App-Id wins in the backend middleware and keeps runtime module\n // data/master dropdowns scoped to VITE_APP_ID.\n return withAppId({\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${token}`,\n });\n}\n\n// ── GET in-flight coalescing ────────────────────────────────────────────────\n//\n// A page routinely asks for the SAME data several times over, because the parts\n// that need it are independent and none of them can know the others exist. Six\n// form fields that look up the same collection issue six identical requests;\n// the header and the body of a detail page each fetch the same record. Measured\n// on an ORDINARY edit form: 13 requests for 8 distinct URLs, one of them fired\n// six times.\n//\n// The honest fix is not to make each caller aware of the others — that couples\n// components that have no business knowing about each other, and breaks the\n// moment a new one is added. It is to make the REQUEST idempotent: a GET that\n// is already in the air is JOINED rather than reissued.\n//\n// Deliberately in-flight ONLY, with no time-to-live:\n// • It cannot serve stale data. The answer a joiner receives is the answer to\n// a request that had not yet returned when it asked — by definition no\n// staler than issuing its own.\n// • It needs no invalidation, so a write can never be shadowed by a cache\n// entry, and no caller has to remember to clear anything.\n// A TTL would catch a few more (a child mounting just after its parent's fetch\n// resolved) at the cost of a staleness window on every endpoint in the app.\n// `formGroupsCache` already makes that trade deliberately for one endpoint it\n// understands; this layer, which knows nothing about what it is fetching,\n// should not make it for everything.\n//\n// Each joiner gets its OWN deep copy of the payload. Callers legitimately mutate\n// what they receive (dropdownApi attaches `recordMeta` to the groups array), and\n// handing several callers one shared object would turn a saved request into a\n// cross-component data bug — far worse than the duplicate it removed.\n//\n// A SHORT TIME-TO-LIVE sits on top of the coalescing, because not every\n// duplicate overlaps: a child that mounts just after its parent's fetch\n// resolved asks a moment too late to join it. That is the remaining half of the\n// \"same data, fetched again\" problem, and it is the half a pure in-flight join\n// cannot reach.\n//\n// This part CAN serve stale data, so it is bounded hard:\n// • a few seconds only — long enough to cover one page's mount burst, short\n// enough that no realistic user action fits inside it;\n// • ANY non-GET clears the whole GET cache. A write is the one event that\n// makes previously-fetched data wrong, so nothing a user saves can be\n// shadowed by a stale entry;\n// • logging out clears it too, so no response outlives the session that was\n// entitled to it.\n// This mirrors the trade `formGroupsCache` already makes deliberately for one\n// endpoint; the difference is that the invalidation here is automatic rather\n// than something each caller has to remember.\nconst GET_TTL_MS = 4000;\n\nconst inFlightGets = new Map(); // url -> Promise<json>\nconst settledGets = new Map(); // url -> { at, json }\n\n// Cleared on every write and on logout — see the note above.\nexport function invalidateGetCache() {\n settledGets.clear();\n}\n\nfunction clonePayload(json) {\n // structuredClone is present in every browser this app supports and in Node\n // 17+. Falling back to a JSON round-trip keeps older test environments\n // working; both produce a copy no other caller can observe.\n try {\n return typeof structuredClone === 'function' ? structuredClone(json) : JSON.parse(JSON.stringify(json));\n } catch {\n // Non-cloneable payload (rare). Sharing the original is still correct for\n // every caller that does not mutate, and is better than failing the call.\n return json;\n }\n}\n\nfunction isGet(options) {\n const method = (options?.method ?? 'GET').toUpperCase();\n return method === 'GET';\n}\n\nexport async function fetchJsonWithAuth(baseUrl, path = '', options = {}) {\n if (path && typeof path === 'object') {\n options = path;\n path = '';\n }\n\n const url = `${baseUrl}${path || ''}`;\n if (isGet(options)) {\n const pending = inFlightGets.get(url);\n if (pending) return clonePayload(await pending);\n const settled = settledGets.get(url);\n if (settled && Date.now() - settled.at < GET_TTL_MS) return clonePayload(settled.json);\n // Expired: drop it now rather than leaving the map to grow for the rest of\n // the session on a long-lived page.\n if (settled) settledGets.delete(url);\n }\n\n if (!isGet(options)) {\n // A write invalidates BEFORE it runs and again after it settles: before, so\n // a GET fired concurrently with the save cannot repopulate the cache from\n // pre-write state; after, so anything read during the write is dropped too.\n invalidateGetCache();\n try {\n return await performFetch(url, options);\n } finally {\n invalidateGetCache();\n }\n }\n\n const run = performFetch(url, options);\n inFlightGets.set(url, run);\n try {\n // The ORIGINATING caller is cloned too, so no caller can tell whether it\n // issued the request or joined one — otherwise a mutation would be safe or\n // unsafe depending on render order, which is the worst kind of bug.\n const json = await run;\n settledGets.set(url, { at: Date.now(), json });\n return clonePayload(json);\n } finally {\n // Cleared on success AND failure: a failed GET must not be inherited by\n // anyone who asks next, they retry for real.\n inFlightGets.delete(url);\n }\n}\n\nasync function performFetch(url, options = {}) {\n const headers = await authHeaders();\n const res = await fetch(url, {\n ...options,\n headers: { ...headers, ...options.headers },\n });\n if (res.status === 401) logout();\n const text = await res.text();\n let json = {};\n if (text) {\n try {\n json = JSON.parse(text);\n } catch {\n json = { error: text };\n }\n }\n if (!res.ok) {\n const responseError = json?.error ?? json?.message;\n const detail = typeof responseError === 'string'\n ? responseError\n : responseError && Object.keys(responseError).length > 0\n ? JSON.stringify(responseError)\n : '';\n const error = new Error(detail || `API ${res.status}: ${res.statusText}`);\n error.status = res.status;\n error.response = json;\n throw error;\n }\n return json;\n}\n\nexport async function apiGetWithAuth(baseUrl, path) {\n const json = await fetchJ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,CAAC,OAAS,EACnD,KAAK,UAAU,CAAa,EAC5B,GACA,EAAY,MAAM,GAAU,OAAO,EAAI,OAAO,IAAI,EAAI,YAAY,EAGxE,KAFA,GAAM,OAAS,EAAI,OACnB,EAAM,SAAW,EACX,CACR,CACA,OAAO,CACT,CAEA,eAAsB,EAAe,EAAS,EAAM,CAClD,IAAM,EAAO,MAAM,EAAkB,EAAS,CAAI,EAClD,OAAO,EAAK,MAAQ,CACtB"}
@@ -0,0 +1,2 @@
1
+ var e=require("./rolldown-runtime-Chgba0Kb.cjs").t({isDiceResponse:()=>g,mapDiceCandidateToInternal:()=>p,mapDiceCandidatesToInternal:()=>m,normalizeDiceSkills:()=>c,resolveDiceProfileId:()=>s,transformDiceResponseToInternalFormat:()=>h});function t(...e){return e.find(e=>e!=null&&String(e).trim()!==``)}function n(e,t){if(!(!e||!t))return Object.prototype.hasOwnProperty.call(e,t)?e[t]:String(t).split(`.`).reduce((e,t)=>e?.[t],e)}function r(e){return/^[a-f0-9]{24}$/i.test(String(e??``).trim())}function i(e){let t=String(e??``).trim();return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t)||/^[a-f0-9]{40,}$/i.test(t)}function a(e,n){let r=String(e??``).trim(),i=t(n?.candidateId,n?.customFields?.diceProfileData?.candidateId);return i&&r===String(i).trim()||/^[a-f0-9]{40,}-\d+$/i.test(r)}function o(e){let t=new Set,n=[],r=(e,a=``)=>{if(e!=null){if(typeof e==`string`||typeof e==`number`){let t=String(e).trim(),r=/(^|[._-])(dice|profile|source|external).*(id|guid|uuid)$|(^|[._-])(id|guid|uuid)$/i.test(a);t&&r&&i(t)&&n.push({path:a,value:t});return}typeof e!=`object`||t.has(e)||(t.add(e),Object.entries(e).forEach(([e,t])=>{r(t,a?`${a}.${e}`:e)}))}};return r(e),n.find(e=>/dice|profile|source|external/i.test(e.path))?.value??n[0]?.value??``}function s(e){if(!e||typeof e!=`object`)return``;let i=(()=>{let t=e?.sourceType??e?.profileSource??e?.selectedSource;return(Array.isArray(t)?t:[t]).some(e=>String(e??``).trim().toLowerCase()===`dice`)})(),s=t(...`diceId,diceID,dice_id,diceProfileId,diceProfileID,diceProfileGuid,profileId,profileID,profileGuid,sourceId,sourceProfileId,externalId,externalProfileId,customFields.diceId,customFields.diceProfileId,customFields.profileId,customFields.externalProfileId,customFields.diceProfileData.diceId,customFields.diceProfileData.diceID,customFields.diceProfileData.id,customFields.diceProfileData._id,customFields.diceProfileData.profileId,customFields.diceProfileData.profileID,customFields.diceProfileData.diceProfileId,customFields.diceProfileData.diceProfileID,customFields.diceProfileData.guid,customFields.diceProfileData.uuid,customFields.diceProfileData.externalId,customFields.diceProfileData.candidateid,customFields.diceProfileData.candidateId`.split(`,`).map(t=>n(e,t)));if(s&&!a(s,e))return String(s);let c=o(e);if(c)return c;let l=t(e.id,e._id);return l&&(i||!r(l))?String(l):``}function c(e){return e?Array.isArray(e)?e.map(e=>{if(e?.skill)return e.skill;if(typeof e==`object`&&e){if(e?.name)return e.name;if(e?.skillName)return e.skillName;if(e?.value)return e.value}return typeof e==`string`?e:null}).filter(Boolean):typeof e==`string`?e.split(`,`).map(e=>e.trim()).filter(Boolean):[]:[]}function l(e){if(Array.isArray(e.locations)&&e.locations.length>0){let t=e.locations[0];if(typeof t==`string`)return t;if(t?.region)return t.region;if(t?.city)return t.city;if(t?.name)return t.name;if(t?.location)return t.location}return e.currentLocation??e.location??e.city??e.region??``}function u(e){let t=e.totalExperience??e.experience??e.yearsOfExperience??e.exp??e.totalYearsOfExperience??e.workExperienceYears;return t!=null&&t!==``?t:null}function d(e){return e.dateLastUpdated??e.updatedAt??e.createdAt??e.createdDate??e.dateCreated??null}function f(e){let t=[e.firstName,e.middleName,e.lastName].filter(Boolean);return t.length>0?t.join(` `):e.fullName??e.name??e.candidateName??``}function p(e,t=0){if(!e||typeof e!=`object`)return{id:`dice-candidate-${t}`,diceId:``,candidateId:``,firstName:``,lastName:``,name:`-`,designation:`-`,currentLocation:``,location:``,exp:``,totalExperience:null,skills:[],createdAt:null,createdOn:`-`,sourceType:`dice`,profileSource:`dice`};let n=f(e),r=n.split(` `),i=r[0]||``,a=r.length>1?r[r.length-1]:``,o=l(e),p=u(e),m=d(e),h=s(e),g=e.candidateId??e.customFields?.diceProfileData?.candidateId??`dice-candidate-${t}`,_=e.skills??e.technicalSkills??e.primarySkills??e.keySkills??[],v=c(_);return process.env.NODE_ENV===`development`&&(console.log(`[DiceMapper] Original skills:`,_),console.log(`[DiceMapper] Mapped skills:`,v),console.log(`[DiceMapper] Dice IDs:`,{id:h,diceId:h,candidateId:g})),{...e,id:h,diceId:h,candidateId:g,firstName:i,lastName:a,middleName:e.middleName||``,name:n||`-`,fullName:n||``,designation:e.currentJobTitle??e.jobTitle??e.designation??e.currentDesignation??`-`,currentDesignation:e.currentJobTitle??e.jobTitle??e.designation??e.currentDesignation??``,jobTitle:e.currentJobTitle??e.jobTitle??e.designation??``,currentLocation:o||``,location:o||``,city:e.city??e.locations?.[0]?.city??``,region:e.region??e.locations?.[0]?.region??``,totalExperience:p,experience:p,yearsOfExperience:p,exp:p!=null&&p!==``?`${p} yrs`:``,skills:v,technicalSkills:v,primarySkills:v,createdAt:m,createdOn:m?String(m):`-`,updatedAt:m,dateLastUpdated:m,sourceType:`dice`,profileSource:`dice`,selectedSource:[`dice`],email:e.email??e.emailAddress??``,phone:e.phone??e.phoneNumber??e.mobile??``,summary:e.summary??e.bio??e.description??``,resume:e.resume??e.resumeUrl??e.cvUrl??``,isActive:!0,isDeleted:!1}}function m(e){return Array.isArray(e)?e.map((e,t)=>p(e,t)):[]}function h(e,t={}){if(!e||typeof e!=`object`)return{status:`success`,data:{fields:[],actions:[],columnActions:[],count:0,data:[]}};let n=m(Array.isArray(e)?e:e?.data?.data??e?.data?.applicant??e?.data?.candidates??e?.data?.items??e?.items??e?.candidates??e?.records??[]),r=e?.data?.count?.searchCount??e?.data?.count?.total??e?.count?.searchCount??e?.count?.total??e?.total??e?.totalCount??n.length;return{status:e?.status??`success`,data:{fields:t?.fields??e?.data?.fields??e?.fields??[],actions:t?.actions??e?.data?.actions??e?.actions??[],columnActions:t?.columnActions??e?.data?.columnActions??e?.columnActions??[],count:Number(r)||0,data:n,...e?.data?.actionRules&&{actionRules:e.data.actionRules},...e?.data?.tabs&&{tabs:e.data.tabs},...e?.data?.tabField&&{tabField:e.data.tabField}}}}function g(e){if(!e)return!1;let t=Array.isArray(e)?e:e?.data?.data??e?.data?.applicant??e?.data?.candidates??e?.data?.items??e?.items??[];if(!Array.isArray(t)||t.length===0)return!1;let n=Math.min(t.length,5);for(let e=0;e<n;e++){let n=t[e],r=n?.sourceType??n?.profileSource??``;if(String(r).toLowerCase()===`dice`)return!0}return!1}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return c}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return e}});
2
+ //# sourceMappingURL=diceCandidateMapper-BjMhHno3.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diceCandidateMapper-BjMhHno3.cjs","names":[],"sources":["../src/services/diceCandidateMapper.js"],"sourcesContent":["/**\n * Dice Candidate Response Mapper\n * \n * Transforms Dice API candidate responses into the existing Internal Candidate\n * List API format. This ensures the frontend receives an identical response\n * schema regardless of the data source.\n * \n * Reusable for additional external sources (Monster, CareerBuilder, LinkedIn, etc.)\n */\n\n/**\n * Normalizes skills from various Dice skill formats into a simple string array\n */\nfunction firstPresentValue(...values) {\n return values.find((value) => value !== undefined && value !== null && String(value).trim() !== '');\n}\n\nfunction getPathValue(record, path) {\n if (!record || !path) return undefined;\n if (Object.prototype.hasOwnProperty.call(record, path)) return record[path];\n return String(path)\n .split('.')\n .reduce((value, key) => value?.[key], record);\n}\n\nfunction isLikelyInternalRecordId(value) {\n return /^[a-f0-9]{24}$/i.test(String(value ?? '').trim());\n}\n\nfunction isLikelyDiceProfileId(value) {\n const text = String(value ?? '').trim();\n return (\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(text)\n || /^[a-f0-9]{40,}$/i.test(text)\n );\n}\n\nfunction isLikelyDiceCandidateId(value, candidate) {\n const text = String(value ?? '').trim();\n const knownCandidateId = firstPresentValue(\n candidate?.candidateId,\n candidate?.customFields?.diceProfileData?.candidateId,\n );\n\n return (\n (knownCandidateId && text === String(knownCandidateId).trim())\n || /^[a-f0-9]{40,}-\\d+$/i.test(text)\n );\n}\n\nfunction findLikelyDiceProfileId(record) {\n const seen = new Set();\n const candidates = [];\n\n const visit = (value, path = '') => {\n if (value === null || value === undefined) return;\n if (typeof value === 'string' || typeof value === 'number') {\n const text = String(value).trim();\n const keyLooksRelevant = /(^|[._-])(dice|profile|source|external).*(id|guid|uuid)$|(^|[._-])(id|guid|uuid)$/i.test(path);\n if (text && keyLooksRelevant && isLikelyDiceProfileId(text)) {\n candidates.push({ path, value: text });\n }\n return;\n }\n if (typeof value !== 'object' || seen.has(value)) return;\n seen.add(value);\n Object.entries(value).forEach(([key, child]) => {\n visit(child, path ? `${path}.${key}` : key);\n });\n };\n\n visit(record);\n\n return candidates.find((candidate) => /dice|profile|source|external/i.test(candidate.path))?.value\n ?? candidates[0]?.value\n ?? '';\n}\n\nexport function resolveDiceProfileId(candidate) {\n if (!candidate || typeof candidate !== 'object') return '';\n\n // Check if this is a Dice candidate\n const isDiceCandidate = (() => {\n const source = candidate?.sourceType\n ?? candidate?.profileSource\n ?? candidate?.selectedSource;\n const normalizedSources = Array.isArray(source) ? source : [source];\n return normalizedSources.some(\n (value) => String(value ?? '').trim().toLowerCase() === 'dice',\n );\n })();\n\n const explicitPaths = [\n 'diceId',\n 'diceID',\n 'dice_id',\n 'diceProfileId',\n 'diceProfileID',\n 'diceProfileGuid',\n 'profileId',\n 'profileID',\n 'profileGuid',\n 'sourceId',\n 'sourceProfileId',\n 'externalId',\n 'externalProfileId',\n 'customFields.diceId',\n 'customFields.diceProfileId',\n 'customFields.profileId',\n 'customFields.externalProfileId',\n 'customFields.diceProfileData.diceId',\n 'customFields.diceProfileData.diceID',\n 'customFields.diceProfileData.id',\n 'customFields.diceProfileData._id',\n 'customFields.diceProfileData.profileId',\n 'customFields.diceProfileData.profileID',\n 'customFields.diceProfileData.diceProfileId',\n 'customFields.diceProfileData.diceProfileID',\n 'customFields.diceProfileData.guid',\n 'customFields.diceProfileData.uuid',\n 'customFields.diceProfileData.externalId',\n 'customFields.diceProfileData.candidateid',\n 'customFields.diceProfileData.candidateId',\n ];\n\n const explicitDiceId = firstPresentValue(\n ...explicitPaths.map((path) => getPathValue(candidate, path)),\n );\n\n if (explicitDiceId && !isLikelyDiceCandidateId(explicitDiceId, candidate)) {\n return String(explicitDiceId);\n }\n\n const likelyNestedId = findLikelyDiceProfileId(candidate);\n if (likelyNestedId) return likelyNestedId;\n\n const genericId = firstPresentValue(candidate.id, candidate._id);\n \n // For Dice candidates, accept the ID even if it looks like an internal MongoDB ObjectId\n // For non-Dice candidates, reject IDs that look like internal record IDs\n if (genericId && (isDiceCandidate || !isLikelyInternalRecordId(genericId))) {\n return String(genericId);\n }\n \n return '';\n}\n\nexport function normalizeDiceSkills(skills) {\n if (!skills) return [];\n \n if (Array.isArray(skills)) {\n return skills\n .map(skill => {\n // Handle Dice format: {skill: \"courts\", lastUsed: 2026}\n if (skill?.skill) return skill.skill;\n // Handle other object formats\n if (typeof skill === 'object' && skill !== null) {\n if (skill?.name) return skill.name;\n if (skill?.skillName) return skill.skillName;\n if (skill?.value) return skill.value;\n }\n // Handle string skills\n if (typeof skill === 'string') return skill;\n return null;\n })\n .filter(Boolean);\n }\n \n if (typeof skills === 'string') {\n return skills.split(',').map(s => s.trim()).filter(Boolean);\n }\n \n return [];\n}\n\n/**\n * Normalizes location from various Dice location formats\n */\nfunction normalizeDiceLocation(candidate) {\n // Try locations array first (common in Dice)\n if (Array.isArray(candidate.locations) && candidate.locations.length > 0) {\n const loc = candidate.locations[0];\n if (typeof loc === 'string') return loc;\n if (loc?.region) return loc.region;\n if (loc?.city) return loc.city;\n if (loc?.name) return loc.name;\n if (loc?.location) return loc.location;\n }\n \n // Try direct location fields\n return (\n candidate.currentLocation ??\n candidate.location ??\n candidate.city ??\n candidate.region ??\n ''\n );\n}\n\n/**\n * Normalizes experience from various Dice experience formats\n */\nfunction normalizeDiceExperience(candidate) {\n const exp = (\n candidate.totalExperience ??\n candidate.experience ??\n candidate.yearsOfExperience ??\n candidate.exp ??\n candidate.totalYearsOfExperience ??\n candidate.workExperienceYears\n );\n \n return exp != null && exp !== '' ? exp : null;\n}\n\n/**\n * Normalizes date from various Dice date formats\n */\nfunction normalizeDiceDate(candidate) {\n return (\n candidate.dateLastUpdated ??\n candidate.updatedAt ??\n candidate.createdAt ??\n candidate.createdDate ??\n candidate.dateCreated ??\n null\n );\n}\n\n/**\n * Normalizes name from various Dice name formats\n */\nfunction normalizeDiceName(candidate) {\n const parts = [\n candidate.firstName,\n candidate.middleName,\n candidate.lastName,\n ].filter(Boolean);\n \n if (parts.length > 0) return parts.join(' ');\n \n return (\n candidate.fullName ??\n candidate.name ??\n candidate.candidateName ??\n ''\n );\n}\n\n/**\n * Maps a single Dice candidate to the Internal Candidate format\n * \n * @param {Object} diceCandidate - Raw Dice API candidate object\n * @param {number} index - Index for fallback ID generation\n * @returns {Object} Mapped candidate in Internal format\n */\nexport function mapDiceCandidateToInternal(diceCandidate, index = 0) {\n if (!diceCandidate || typeof diceCandidate !== 'object') {\n return {\n id: `dice-candidate-${index}`,\n diceId: '',\n candidateId: '',\n firstName: '',\n lastName: '',\n name: '-',\n designation: '-',\n currentLocation: '',\n location: '',\n exp: '',\n totalExperience: null,\n skills: [],\n createdAt: null,\n createdOn: '-',\n sourceType: 'dice',\n profileSource: 'dice',\n };\n }\n\n const fullName = normalizeDiceName(diceCandidate);\n const nameParts = fullName.split(' ');\n const firstName = nameParts[0] || '';\n const lastName = nameParts.length > 1 ? nameParts[nameParts.length - 1] : '';\n \n const location = normalizeDiceLocation(diceCandidate);\n const experience = normalizeDiceExperience(diceCandidate);\n const createdOn = normalizeDiceDate(diceCandidate);\n const diceProfileId = resolveDiceProfileId(diceCandidate);\n const candidateId = diceCandidate.candidateId\n ?? diceCandidate.customFields?.diceProfileData?.candidateId\n ?? `dice-candidate-${index}`;\n \n // Extract skills from various possible fields\n const rawSkills = diceCandidate.skills ?? \n diceCandidate.technicalSkills ?? \n diceCandidate.primarySkills ??\n diceCandidate.keySkills ??\n [];\n \n const skills = normalizeDiceSkills(rawSkills);\n \n // Debug logging to verify transformation\n if (process.env.NODE_ENV === 'development') {\n console.log('[DiceMapper] Original skills:', rawSkills);\n console.log('[DiceMapper] Mapped skills:', skills);\n console.log('[DiceMapper] Dice IDs:', {\n id: diceProfileId,\n diceId: diceProfileId,\n candidateId,\n });\n }\n\n return {\n // Preserve original Dice fields for reference\n ...diceCandidate,\n \n // Map to Internal candidate schema. Keep the Dice profile id as the primary id.\n id: diceProfileId,\n diceId: diceProfileId,\n candidateId,\n \n // Name fields\n firstName,\n lastName,\n middleName: diceCandidate.middleName || '',\n name: fullName || '-',\n fullName: fullName || '',\n \n // Professional info\n designation: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? diceCandidate.currentDesignation ?? '-',\n currentDesignation: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? diceCandidate.currentDesignation ?? '',\n jobTitle: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? '',\n \n // Location\n currentLocation: location || '',\n location: location || '',\n city: diceCandidate.city ?? diceCandidate.locations?.[0]?.city ?? '',\n region: diceCandidate.region ?? diceCandidate.locations?.[0]?.region ?? '',\n \n // Experience\n totalExperience: experience,\n experience: experience,\n yearsOfExperience: experience,\n exp: experience != null && experience !== '' ? `${experience} yrs` : '',\n \n // Skills\n skills,\n technicalSkills: skills,\n primarySkills: skills,\n \n // Dates\n createdAt: createdOn,\n createdOn: createdOn ? String(createdOn) : '-',\n updatedAt: createdOn,\n dateLastUpdated: createdOn,\n \n // Source identification\n sourceType: 'dice',\n profileSource: 'dice',\n selectedSource: ['dice'],\n \n // Additional fields with defaults\n email: diceCandidate.email ?? diceCandidate.emailAddress ?? '',\n phone: diceCandidate.phone ?? diceCandidate.phoneNumber ?? diceCandidate.mobile ?? '',\n summary: diceCandidate.summary ?? diceCandidate.bio ?? diceCandidate.description ?? '',\n resume: diceCandidate.resume ?? diceCandidate.resumeUrl ?? diceCandidate.cvUrl ?? '',\n \n // Status and metadata\n isActive: true,\n isDeleted: false,\n };\n}\n\n/**\n * Maps an array of Dice candidates to the Internal Candidate format\n * \n * @param {Array} diceCandidates - Array of raw Dice API candidate objects\n * @returns {Array} Array of mapped candidates in Internal format\n */\nexport function mapDiceCandidatesToInternal(diceCandidates) {\n if (!Array.isArray(diceCandidates)) {\n return [];\n }\n \n return diceCandidates.map((candidate, index) => \n mapDiceCandidateToInternal(candidate, index)\n );\n}\n\n/**\n * Transforms a Dice API response to match the existing Candidate List API response format\n * \n * @param {Object} diceResponse - Raw Dice API response\n * @param {Object} originalResponseStructure - The expected response structure from Internal API\n * @returns {Object} Transformed response matching Internal API format\n */\nexport function transformDiceResponseToInternalFormat(diceResponse, originalResponseStructure = {}) {\n if (!diceResponse || typeof diceResponse !== 'object') {\n return {\n status: 'success',\n data: {\n fields: [],\n actions: [],\n columnActions: [],\n count: 0,\n data: [],\n },\n };\n }\n\n // Extract candidates array from various possible response structures\n const diceCandidates = Array.isArray(diceResponse) \n ? diceResponse \n : diceResponse?.data?.data ?? \n diceResponse?.data?.applicant ?? \n diceResponse?.data?.candidates ?? \n diceResponse?.data?.items ?? \n diceResponse?.items ?? \n diceResponse?.candidates ?? \n diceResponse?.records ?? \n [];\n\n // Map Dice candidates to Internal format\n const mappedCandidates = mapDiceCandidatesToInternal(diceCandidates);\n\n // Extract count from various possible locations\n const count = (\n diceResponse?.data?.count?.searchCount ??\n diceResponse?.data?.count?.total ??\n diceResponse?.count?.searchCount ??\n diceResponse?.count?.total ??\n diceResponse?.total ??\n diceResponse?.totalCount ??\n mappedCandidates.length\n );\n\n // Preserve existing metadata from the original response structure\n return {\n status: diceResponse?.status ?? 'success',\n data: {\n // Preserve fields, actions, columnActions from original structure\n fields: originalResponseStructure?.fields ?? diceResponse?.data?.fields ?? diceResponse?.fields ?? [],\n actions: originalResponseStructure?.actions ?? diceResponse?.data?.actions ?? diceResponse?.actions ?? [],\n columnActions: originalResponseStructure?.columnActions ?? diceResponse?.data?.columnActions ?? diceResponse?.columnActions ?? [],\n \n // Count and mapped data\n count: Number(count) || 0,\n data: mappedCandidates,\n \n // Preserve any additional metadata\n ...(diceResponse?.data?.actionRules && { actionRules: diceResponse.data.actionRules }),\n ...(diceResponse?.data?.tabs && { tabs: diceResponse.data.tabs }),\n ...(diceResponse?.data?.tabField && { tabField: diceResponse.data.tabField }),\n },\n };\n}\n\n/**\n * Checks if a response contains Dice candidates\n * \n * @param {Array|Object} response - API response to check\n * @returns {boolean} True if response contains Dice candidates\n */\nexport function isDiceResponse(response) {\n if (!response) return false;\n \n const candidates = Array.isArray(response) \n ? response \n : response?.data?.data ?? \n response?.data?.applicant ?? \n response?.data?.candidates ?? \n response?.data?.items ?? \n response?.items ?? \n [];\n \n if (!Array.isArray(candidates) || candidates.length === 0) {\n return false;\n }\n \n // Check first few candidates for Dice source indicators\n const sampleSize = Math.min(candidates.length, 5);\n for (let i = 0; i < sampleSize; i++) {\n const candidate = candidates[i];\n const sourceType = candidate?.sourceType ?? candidate?.profileSource ?? '';\n if (String(sourceType).toLowerCase() === 'dice') {\n return true;\n }\n }\n \n return false;\n}\n\nexport default {\n mapDiceCandidateToInternal,\n mapDiceCandidatesToInternal,\n transformDiceResponseToInternalFormat,\n isDiceResponse,\n};\n"],"mappings":"+OAaA,SAAS,EAAkB,GAAG,EAAQ,CACpC,OAAO,EAAO,KAAM,GAAU,GAAiC,MAAQ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,CAAE,YAAa,EAAa,KAAK,WAAY,EACpF,GAAI,GAAc,MAAM,MAAQ,CAAE,KAAM,EAAa,KAAK,IAAK,EAC/D,GAAI,GAAc,MAAM,UAAY,CAAE,SAAU,EAAa,KAAK,QAAS,CAC7E,CACF,CACF,CAQA,SAAgB,EAAe,EAAU,CACvC,GAAI,CAAC,EAAU,MAAO,GAEtB,IAAM,EAAa,MAAM,QAAQ,CAAQ,EACrC,EACA,GAAU,MAAM,MAChB,GAAU,MAAM,WAChB,GAAU,MAAM,YAChB,GAAU,MAAM,OAChB,GAAU,OACV,CAAC,EAEL,GAAI,CAAC,MAAM,QAAQ,CAAU,GAAK,EAAW,SAAW,EACtD,MAAO,GAIT,IAAM,EAAa,KAAK,IAAI,EAAW,OAAQ,CAAC,EAChD,IAAK,IAAI,EAAI,EAAG,EAAI,EAAY,IAAK,CACnC,IAAM,EAAY,EAAW,GACvB,EAAa,GAAW,YAAc,GAAW,eAAiB,GACxE,GAAI,OAAO,CAAU,CAAC,CAAC,YAAY,IAAM,OACvC,MAAO,EAEX,CAEA,MAAO,EACT"}
@@ -0,0 +1,201 @@
1
+ import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
+ //#region src/services/diceCandidateMapper.js
3
+ var t = /* @__PURE__ */ e({
4
+ isDiceResponse: () => _,
5
+ mapDiceCandidateToInternal: () => m,
6
+ mapDiceCandidatesToInternal: () => h,
7
+ normalizeDiceSkills: () => l,
8
+ resolveDiceProfileId: () => c,
9
+ transformDiceResponseToInternalFormat: () => g
10
+ });
11
+ function n(...e) {
12
+ return e.find((e) => e != null && String(e).trim() !== "");
13
+ }
14
+ function r(e, t) {
15
+ if (!(!e || !t)) return Object.prototype.hasOwnProperty.call(e, t) ? e[t] : String(t).split(".").reduce((e, t) => e?.[t], e);
16
+ }
17
+ function i(e) {
18
+ return /^[a-f0-9]{24}$/i.test(String(e ?? "").trim());
19
+ }
20
+ function a(e) {
21
+ let t = String(e ?? "").trim();
22
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t) || /^[a-f0-9]{40,}$/i.test(t);
23
+ }
24
+ function o(e, t) {
25
+ let r = String(e ?? "").trim(), i = n(t?.candidateId, t?.customFields?.diceProfileData?.candidateId);
26
+ return i && r === String(i).trim() || /^[a-f0-9]{40,}-\d+$/i.test(r);
27
+ }
28
+ function s(e) {
29
+ let t = /* @__PURE__ */ new Set(), n = [], r = (e, i = "") => {
30
+ if (e != null) {
31
+ if (typeof e == "string" || typeof e == "number") {
32
+ let t = String(e).trim(), r = /(^|[._-])(dice|profile|source|external).*(id|guid|uuid)$|(^|[._-])(id|guid|uuid)$/i.test(i);
33
+ t && r && a(t) && n.push({
34
+ path: i,
35
+ value: t
36
+ });
37
+ return;
38
+ }
39
+ typeof e != "object" || t.has(e) || (t.add(e), Object.entries(e).forEach(([e, t]) => {
40
+ r(t, i ? `${i}.${e}` : e);
41
+ }));
42
+ }
43
+ };
44
+ return r(e), n.find((e) => /dice|profile|source|external/i.test(e.path))?.value ?? n[0]?.value ?? "";
45
+ }
46
+ function c(e) {
47
+ if (!e || typeof e != "object") return "";
48
+ let t = (() => {
49
+ let t = e?.sourceType ?? e?.profileSource ?? e?.selectedSource;
50
+ return (Array.isArray(t) ? t : [t]).some((e) => String(e ?? "").trim().toLowerCase() === "dice");
51
+ })(), a = n(...(/* @__PURE__ */ "diceId,diceID,dice_id,diceProfileId,diceProfileID,diceProfileGuid,profileId,profileID,profileGuid,sourceId,sourceProfileId,externalId,externalProfileId,customFields.diceId,customFields.diceProfileId,customFields.profileId,customFields.externalProfileId,customFields.diceProfileData.diceId,customFields.diceProfileData.diceID,customFields.diceProfileData.id,customFields.diceProfileData._id,customFields.diceProfileData.profileId,customFields.diceProfileData.profileID,customFields.diceProfileData.diceProfileId,customFields.diceProfileData.diceProfileID,customFields.diceProfileData.guid,customFields.diceProfileData.uuid,customFields.diceProfileData.externalId,customFields.diceProfileData.candidateid,customFields.diceProfileData.candidateId".split(",")).map((t) => r(e, t)));
52
+ if (a && !o(a, e)) return String(a);
53
+ let c = s(e);
54
+ if (c) return c;
55
+ let l = n(e.id, e._id);
56
+ return l && (t || !i(l)) ? String(l) : "";
57
+ }
58
+ function l(e) {
59
+ return e ? Array.isArray(e) ? e.map((e) => {
60
+ if (e?.skill) return e.skill;
61
+ if (typeof e == "object" && e) {
62
+ if (e?.name) return e.name;
63
+ if (e?.skillName) return e.skillName;
64
+ if (e?.value) return e.value;
65
+ }
66
+ return typeof e == "string" ? e : null;
67
+ }).filter(Boolean) : typeof e == "string" ? e.split(",").map((e) => e.trim()).filter(Boolean) : [] : [];
68
+ }
69
+ function u(e) {
70
+ if (Array.isArray(e.locations) && e.locations.length > 0) {
71
+ let t = e.locations[0];
72
+ if (typeof t == "string") return t;
73
+ if (t?.region) return t.region;
74
+ if (t?.city) return t.city;
75
+ if (t?.name) return t.name;
76
+ if (t?.location) return t.location;
77
+ }
78
+ return e.currentLocation ?? e.location ?? e.city ?? e.region ?? "";
79
+ }
80
+ function d(e) {
81
+ let t = e.totalExperience ?? e.experience ?? e.yearsOfExperience ?? e.exp ?? e.totalYearsOfExperience ?? e.workExperienceYears;
82
+ return t != null && t !== "" ? t : null;
83
+ }
84
+ function f(e) {
85
+ return e.dateLastUpdated ?? e.updatedAt ?? e.createdAt ?? e.createdDate ?? e.dateCreated ?? null;
86
+ }
87
+ function p(e) {
88
+ let t = [
89
+ e.firstName,
90
+ e.middleName,
91
+ e.lastName
92
+ ].filter(Boolean);
93
+ return t.length > 0 ? t.join(" ") : e.fullName ?? e.name ?? e.candidateName ?? "";
94
+ }
95
+ function m(e, t = 0) {
96
+ if (!e || typeof e != "object") return {
97
+ id: `dice-candidate-${t}`,
98
+ diceId: "",
99
+ candidateId: "",
100
+ firstName: "",
101
+ lastName: "",
102
+ name: "-",
103
+ designation: "-",
104
+ currentLocation: "",
105
+ location: "",
106
+ exp: "",
107
+ totalExperience: null,
108
+ skills: [],
109
+ createdAt: null,
110
+ createdOn: "-",
111
+ sourceType: "dice",
112
+ profileSource: "dice"
113
+ };
114
+ let n = p(e), r = n.split(" "), i = r[0] || "", a = r.length > 1 ? r[r.length - 1] : "", o = u(e), s = d(e), m = f(e), h = c(e), g = e.candidateId ?? e.customFields?.diceProfileData?.candidateId ?? `dice-candidate-${t}`, _ = e.skills ?? e.technicalSkills ?? e.primarySkills ?? e.keySkills ?? [], v = l(_);
115
+ return process.env.NODE_ENV === "development" && (console.log("[DiceMapper] Original skills:", _), console.log("[DiceMapper] Mapped skills:", v), console.log("[DiceMapper] Dice IDs:", {
116
+ id: h,
117
+ diceId: h,
118
+ candidateId: g
119
+ })), {
120
+ ...e,
121
+ id: h,
122
+ diceId: h,
123
+ candidateId: g,
124
+ firstName: i,
125
+ lastName: a,
126
+ middleName: e.middleName || "",
127
+ name: n || "-",
128
+ fullName: n || "",
129
+ designation: e.currentJobTitle ?? e.jobTitle ?? e.designation ?? e.currentDesignation ?? "-",
130
+ currentDesignation: e.currentJobTitle ?? e.jobTitle ?? e.designation ?? e.currentDesignation ?? "",
131
+ jobTitle: e.currentJobTitle ?? e.jobTitle ?? e.designation ?? "",
132
+ currentLocation: o || "",
133
+ location: o || "",
134
+ city: e.city ?? e.locations?.[0]?.city ?? "",
135
+ region: e.region ?? e.locations?.[0]?.region ?? "",
136
+ totalExperience: s,
137
+ experience: s,
138
+ yearsOfExperience: s,
139
+ exp: s != null && s !== "" ? `${s} yrs` : "",
140
+ skills: v,
141
+ technicalSkills: v,
142
+ primarySkills: v,
143
+ createdAt: m,
144
+ createdOn: m ? String(m) : "-",
145
+ updatedAt: m,
146
+ dateLastUpdated: m,
147
+ sourceType: "dice",
148
+ profileSource: "dice",
149
+ selectedSource: ["dice"],
150
+ email: e.email ?? e.emailAddress ?? "",
151
+ phone: e.phone ?? e.phoneNumber ?? e.mobile ?? "",
152
+ summary: e.summary ?? e.bio ?? e.description ?? "",
153
+ resume: e.resume ?? e.resumeUrl ?? e.cvUrl ?? "",
154
+ isActive: !0,
155
+ isDeleted: !1
156
+ };
157
+ }
158
+ function h(e) {
159
+ return Array.isArray(e) ? e.map((e, t) => m(e, t)) : [];
160
+ }
161
+ function g(e, t = {}) {
162
+ if (!e || typeof e != "object") return {
163
+ status: "success",
164
+ data: {
165
+ fields: [],
166
+ actions: [],
167
+ columnActions: [],
168
+ count: 0,
169
+ data: []
170
+ }
171
+ };
172
+ let n = h(Array.isArray(e) ? e : e?.data?.data ?? e?.data?.applicant ?? e?.data?.candidates ?? e?.data?.items ?? e?.items ?? e?.candidates ?? e?.records ?? []), r = e?.data?.count?.searchCount ?? e?.data?.count?.total ?? e?.count?.searchCount ?? e?.count?.total ?? e?.total ?? e?.totalCount ?? n.length;
173
+ return {
174
+ status: e?.status ?? "success",
175
+ data: {
176
+ fields: t?.fields ?? e?.data?.fields ?? e?.fields ?? [],
177
+ actions: t?.actions ?? e?.data?.actions ?? e?.actions ?? [],
178
+ columnActions: t?.columnActions ?? e?.data?.columnActions ?? e?.columnActions ?? [],
179
+ count: Number(r) || 0,
180
+ data: n,
181
+ ...e?.data?.actionRules && { actionRules: e.data.actionRules },
182
+ ...e?.data?.tabs && { tabs: e.data.tabs },
183
+ ...e?.data?.tabField && { tabField: e.data.tabField }
184
+ }
185
+ };
186
+ }
187
+ function _(e) {
188
+ if (!e) return !1;
189
+ let t = Array.isArray(e) ? e : e?.data?.data ?? e?.data?.applicant ?? e?.data?.candidates ?? e?.data?.items ?? e?.items ?? [];
190
+ if (!Array.isArray(t) || t.length === 0) return !1;
191
+ let n = Math.min(t.length, 5);
192
+ for (let e = 0; e < n; e++) {
193
+ let n = t[e], r = n?.sourceType ?? n?.profileSource ?? "";
194
+ if (String(r).toLowerCase() === "dice") return !0;
195
+ }
196
+ return !1;
197
+ }
198
+ //#endregion
199
+ export { l as n, c as r, t };
200
+
201
+ //# sourceMappingURL=diceCandidateMapper-DqBO4EhL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"diceCandidateMapper-DqBO4EhL.js","names":[],"sources":["../src/services/diceCandidateMapper.js"],"sourcesContent":["/**\n * Dice Candidate Response Mapper\n * \n * Transforms Dice API candidate responses into the existing Internal Candidate\n * List API format. This ensures the frontend receives an identical response\n * schema regardless of the data source.\n * \n * Reusable for additional external sources (Monster, CareerBuilder, LinkedIn, etc.)\n */\n\n/**\n * Normalizes skills from various Dice skill formats into a simple string array\n */\nfunction firstPresentValue(...values) {\n return values.find((value) => value !== undefined && value !== null && String(value).trim() !== '');\n}\n\nfunction getPathValue(record, path) {\n if (!record || !path) return undefined;\n if (Object.prototype.hasOwnProperty.call(record, path)) return record[path];\n return String(path)\n .split('.')\n .reduce((value, key) => value?.[key], record);\n}\n\nfunction isLikelyInternalRecordId(value) {\n return /^[a-f0-9]{24}$/i.test(String(value ?? '').trim());\n}\n\nfunction isLikelyDiceProfileId(value) {\n const text = String(value ?? '').trim();\n return (\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(text)\n || /^[a-f0-9]{40,}$/i.test(text)\n );\n}\n\nfunction isLikelyDiceCandidateId(value, candidate) {\n const text = String(value ?? '').trim();\n const knownCandidateId = firstPresentValue(\n candidate?.candidateId,\n candidate?.customFields?.diceProfileData?.candidateId,\n );\n\n return (\n (knownCandidateId && text === String(knownCandidateId).trim())\n || /^[a-f0-9]{40,}-\\d+$/i.test(text)\n );\n}\n\nfunction findLikelyDiceProfileId(record) {\n const seen = new Set();\n const candidates = [];\n\n const visit = (value, path = '') => {\n if (value === null || value === undefined) return;\n if (typeof value === 'string' || typeof value === 'number') {\n const text = String(value).trim();\n const keyLooksRelevant = /(^|[._-])(dice|profile|source|external).*(id|guid|uuid)$|(^|[._-])(id|guid|uuid)$/i.test(path);\n if (text && keyLooksRelevant && isLikelyDiceProfileId(text)) {\n candidates.push({ path, value: text });\n }\n return;\n }\n if (typeof value !== 'object' || seen.has(value)) return;\n seen.add(value);\n Object.entries(value).forEach(([key, child]) => {\n visit(child, path ? `${path}.${key}` : key);\n });\n };\n\n visit(record);\n\n return candidates.find((candidate) => /dice|profile|source|external/i.test(candidate.path))?.value\n ?? candidates[0]?.value\n ?? '';\n}\n\nexport function resolveDiceProfileId(candidate) {\n if (!candidate || typeof candidate !== 'object') return '';\n\n // Check if this is a Dice candidate\n const isDiceCandidate = (() => {\n const source = candidate?.sourceType\n ?? candidate?.profileSource\n ?? candidate?.selectedSource;\n const normalizedSources = Array.isArray(source) ? source : [source];\n return normalizedSources.some(\n (value) => String(value ?? '').trim().toLowerCase() === 'dice',\n );\n })();\n\n const explicitPaths = [\n 'diceId',\n 'diceID',\n 'dice_id',\n 'diceProfileId',\n 'diceProfileID',\n 'diceProfileGuid',\n 'profileId',\n 'profileID',\n 'profileGuid',\n 'sourceId',\n 'sourceProfileId',\n 'externalId',\n 'externalProfileId',\n 'customFields.diceId',\n 'customFields.diceProfileId',\n 'customFields.profileId',\n 'customFields.externalProfileId',\n 'customFields.diceProfileData.diceId',\n 'customFields.diceProfileData.diceID',\n 'customFields.diceProfileData.id',\n 'customFields.diceProfileData._id',\n 'customFields.diceProfileData.profileId',\n 'customFields.diceProfileData.profileID',\n 'customFields.diceProfileData.diceProfileId',\n 'customFields.diceProfileData.diceProfileID',\n 'customFields.diceProfileData.guid',\n 'customFields.diceProfileData.uuid',\n 'customFields.diceProfileData.externalId',\n 'customFields.diceProfileData.candidateid',\n 'customFields.diceProfileData.candidateId',\n ];\n\n const explicitDiceId = firstPresentValue(\n ...explicitPaths.map((path) => getPathValue(candidate, path)),\n );\n\n if (explicitDiceId && !isLikelyDiceCandidateId(explicitDiceId, candidate)) {\n return String(explicitDiceId);\n }\n\n const likelyNestedId = findLikelyDiceProfileId(candidate);\n if (likelyNestedId) return likelyNestedId;\n\n const genericId = firstPresentValue(candidate.id, candidate._id);\n \n // For Dice candidates, accept the ID even if it looks like an internal MongoDB ObjectId\n // For non-Dice candidates, reject IDs that look like internal record IDs\n if (genericId && (isDiceCandidate || !isLikelyInternalRecordId(genericId))) {\n return String(genericId);\n }\n \n return '';\n}\n\nexport function normalizeDiceSkills(skills) {\n if (!skills) return [];\n \n if (Array.isArray(skills)) {\n return skills\n .map(skill => {\n // Handle Dice format: {skill: \"courts\", lastUsed: 2026}\n if (skill?.skill) return skill.skill;\n // Handle other object formats\n if (typeof skill === 'object' && skill !== null) {\n if (skill?.name) return skill.name;\n if (skill?.skillName) return skill.skillName;\n if (skill?.value) return skill.value;\n }\n // Handle string skills\n if (typeof skill === 'string') return skill;\n return null;\n })\n .filter(Boolean);\n }\n \n if (typeof skills === 'string') {\n return skills.split(',').map(s => s.trim()).filter(Boolean);\n }\n \n return [];\n}\n\n/**\n * Normalizes location from various Dice location formats\n */\nfunction normalizeDiceLocation(candidate) {\n // Try locations array first (common in Dice)\n if (Array.isArray(candidate.locations) && candidate.locations.length > 0) {\n const loc = candidate.locations[0];\n if (typeof loc === 'string') return loc;\n if (loc?.region) return loc.region;\n if (loc?.city) return loc.city;\n if (loc?.name) return loc.name;\n if (loc?.location) return loc.location;\n }\n \n // Try direct location fields\n return (\n candidate.currentLocation ??\n candidate.location ??\n candidate.city ??\n candidate.region ??\n ''\n );\n}\n\n/**\n * Normalizes experience from various Dice experience formats\n */\nfunction normalizeDiceExperience(candidate) {\n const exp = (\n candidate.totalExperience ??\n candidate.experience ??\n candidate.yearsOfExperience ??\n candidate.exp ??\n candidate.totalYearsOfExperience ??\n candidate.workExperienceYears\n );\n \n return exp != null && exp !== '' ? exp : null;\n}\n\n/**\n * Normalizes date from various Dice date formats\n */\nfunction normalizeDiceDate(candidate) {\n return (\n candidate.dateLastUpdated ??\n candidate.updatedAt ??\n candidate.createdAt ??\n candidate.createdDate ??\n candidate.dateCreated ??\n null\n );\n}\n\n/**\n * Normalizes name from various Dice name formats\n */\nfunction normalizeDiceName(candidate) {\n const parts = [\n candidate.firstName,\n candidate.middleName,\n candidate.lastName,\n ].filter(Boolean);\n \n if (parts.length > 0) return parts.join(' ');\n \n return (\n candidate.fullName ??\n candidate.name ??\n candidate.candidateName ??\n ''\n );\n}\n\n/**\n * Maps a single Dice candidate to the Internal Candidate format\n * \n * @param {Object} diceCandidate - Raw Dice API candidate object\n * @param {number} index - Index for fallback ID generation\n * @returns {Object} Mapped candidate in Internal format\n */\nexport function mapDiceCandidateToInternal(diceCandidate, index = 0) {\n if (!diceCandidate || typeof diceCandidate !== 'object') {\n return {\n id: `dice-candidate-${index}`,\n diceId: '',\n candidateId: '',\n firstName: '',\n lastName: '',\n name: '-',\n designation: '-',\n currentLocation: '',\n location: '',\n exp: '',\n totalExperience: null,\n skills: [],\n createdAt: null,\n createdOn: '-',\n sourceType: 'dice',\n profileSource: 'dice',\n };\n }\n\n const fullName = normalizeDiceName(diceCandidate);\n const nameParts = fullName.split(' ');\n const firstName = nameParts[0] || '';\n const lastName = nameParts.length > 1 ? nameParts[nameParts.length - 1] : '';\n \n const location = normalizeDiceLocation(diceCandidate);\n const experience = normalizeDiceExperience(diceCandidate);\n const createdOn = normalizeDiceDate(diceCandidate);\n const diceProfileId = resolveDiceProfileId(diceCandidate);\n const candidateId = diceCandidate.candidateId\n ?? diceCandidate.customFields?.diceProfileData?.candidateId\n ?? `dice-candidate-${index}`;\n \n // Extract skills from various possible fields\n const rawSkills = diceCandidate.skills ?? \n diceCandidate.technicalSkills ?? \n diceCandidate.primarySkills ??\n diceCandidate.keySkills ??\n [];\n \n const skills = normalizeDiceSkills(rawSkills);\n \n // Debug logging to verify transformation\n if (process.env.NODE_ENV === 'development') {\n console.log('[DiceMapper] Original skills:', rawSkills);\n console.log('[DiceMapper] Mapped skills:', skills);\n console.log('[DiceMapper] Dice IDs:', {\n id: diceProfileId,\n diceId: diceProfileId,\n candidateId,\n });\n }\n\n return {\n // Preserve original Dice fields for reference\n ...diceCandidate,\n \n // Map to Internal candidate schema. Keep the Dice profile id as the primary id.\n id: diceProfileId,\n diceId: diceProfileId,\n candidateId,\n \n // Name fields\n firstName,\n lastName,\n middleName: diceCandidate.middleName || '',\n name: fullName || '-',\n fullName: fullName || '',\n \n // Professional info\n designation: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? diceCandidate.currentDesignation ?? '-',\n currentDesignation: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? diceCandidate.currentDesignation ?? '',\n jobTitle: diceCandidate.currentJobTitle ?? diceCandidate.jobTitle ?? diceCandidate.designation ?? '',\n \n // Location\n currentLocation: location || '',\n location: location || '',\n city: diceCandidate.city ?? diceCandidate.locations?.[0]?.city ?? '',\n region: diceCandidate.region ?? diceCandidate.locations?.[0]?.region ?? '',\n \n // Experience\n totalExperience: experience,\n experience: experience,\n yearsOfExperience: experience,\n exp: experience != null && experience !== '' ? `${experience} yrs` : '',\n \n // Skills\n skills,\n technicalSkills: skills,\n primarySkills: skills,\n \n // Dates\n createdAt: createdOn,\n createdOn: createdOn ? String(createdOn) : '-',\n updatedAt: createdOn,\n dateLastUpdated: createdOn,\n \n // Source identification\n sourceType: 'dice',\n profileSource: 'dice',\n selectedSource: ['dice'],\n \n // Additional fields with defaults\n email: diceCandidate.email ?? diceCandidate.emailAddress ?? '',\n phone: diceCandidate.phone ?? diceCandidate.phoneNumber ?? diceCandidate.mobile ?? '',\n summary: diceCandidate.summary ?? diceCandidate.bio ?? diceCandidate.description ?? '',\n resume: diceCandidate.resume ?? diceCandidate.resumeUrl ?? diceCandidate.cvUrl ?? '',\n \n // Status and metadata\n isActive: true,\n isDeleted: false,\n };\n}\n\n/**\n * Maps an array of Dice candidates to the Internal Candidate format\n * \n * @param {Array} diceCandidates - Array of raw Dice API candidate objects\n * @returns {Array} Array of mapped candidates in Internal format\n */\nexport function mapDiceCandidatesToInternal(diceCandidates) {\n if (!Array.isArray(diceCandidates)) {\n return [];\n }\n \n return diceCandidates.map((candidate, index) => \n mapDiceCandidateToInternal(candidate, index)\n );\n}\n\n/**\n * Transforms a Dice API response to match the existing Candidate List API response format\n * \n * @param {Object} diceResponse - Raw Dice API response\n * @param {Object} originalResponseStructure - The expected response structure from Internal API\n * @returns {Object} Transformed response matching Internal API format\n */\nexport function transformDiceResponseToInternalFormat(diceResponse, originalResponseStructure = {}) {\n if (!diceResponse || typeof diceResponse !== 'object') {\n return {\n status: 'success',\n data: {\n fields: [],\n actions: [],\n columnActions: [],\n count: 0,\n data: [],\n },\n };\n }\n\n // Extract candidates array from various possible response structures\n const diceCandidates = Array.isArray(diceResponse) \n ? diceResponse \n : diceResponse?.data?.data ?? \n diceResponse?.data?.applicant ?? \n diceResponse?.data?.candidates ?? \n diceResponse?.data?.items ?? \n diceResponse?.items ?? \n diceResponse?.candidates ?? \n diceResponse?.records ?? \n [];\n\n // Map Dice candidates to Internal format\n const mappedCandidates = mapDiceCandidatesToInternal(diceCandidates);\n\n // Extract count from various possible locations\n const count = (\n diceResponse?.data?.count?.searchCount ??\n diceResponse?.data?.count?.total ??\n diceResponse?.count?.searchCount ??\n diceResponse?.count?.total ??\n diceResponse?.total ??\n diceResponse?.totalCount ??\n mappedCandidates.length\n );\n\n // Preserve existing metadata from the original response structure\n return {\n status: diceResponse?.status ?? 'success',\n data: {\n // Preserve fields, actions, columnActions from original structure\n fields: originalResponseStructure?.fields ?? diceResponse?.data?.fields ?? diceResponse?.fields ?? [],\n actions: originalResponseStructure?.actions ?? diceResponse?.data?.actions ?? diceResponse?.actions ?? [],\n columnActions: originalResponseStructure?.columnActions ?? diceResponse?.data?.columnActions ?? diceResponse?.columnActions ?? [],\n \n // Count and mapped data\n count: Number(count) || 0,\n data: mappedCandidates,\n \n // Preserve any additional metadata\n ...(diceResponse?.data?.actionRules && { actionRules: diceResponse.data.actionRules }),\n ...(diceResponse?.data?.tabs && { tabs: diceResponse.data.tabs }),\n ...(diceResponse?.data?.tabField && { tabField: diceResponse.data.tabField }),\n },\n };\n}\n\n/**\n * Checks if a response contains Dice candidates\n * \n * @param {Array|Object} response - API response to check\n * @returns {boolean} True if response contains Dice candidates\n */\nexport function isDiceResponse(response) {\n if (!response) return false;\n \n const candidates = Array.isArray(response) \n ? response \n : response?.data?.data ?? \n response?.data?.applicant ?? \n response?.data?.candidates ?? \n response?.data?.items ?? \n response?.items ?? \n [];\n \n if (!Array.isArray(candidates) || candidates.length === 0) {\n return false;\n }\n \n // Check first few candidates for Dice source indicators\n const sampleSize = Math.min(candidates.length, 5);\n for (let i = 0; i < sampleSize; i++) {\n const candidate = candidates[i];\n const sourceType = candidate?.sourceType ?? candidate?.profileSource ?? '';\n if (String(sourceType).toLowerCase() === 'dice') {\n return true;\n }\n }\n \n return false;\n}\n\nexport default {\n mapDiceCandidateToInternal,\n mapDiceCandidatesToInternal,\n transformDiceResponseToInternalFormat,\n isDiceResponse,\n};\n"],"mappings":";;;;;;;;;;AAaA,SAAS,EAAkB,GAAG,GAAQ;CACpC,OAAO,EAAO,MAAM,MAAU,KAAiC,QAAQ,OAAO,CAAK,CAAC,CAAC,KAAK,MAAM,EAAE;AACpG;AAEA,SAAS,EAAa,GAAQ,GAAM;CAC9B,OAAC,KAAU,CAAC,IAEhB,OADI,OAAO,UAAU,eAAe,KAAK,GAAQ,CAAI,IAAU,EAAO,KAC/D,OAAO,CAAI,CAAC,CAChB,MAAM,GAAG,CAAC,CACV,QAAQ,GAAO,MAAQ,IAAQ,IAAM,CAAM;AAChD;AAEA,SAAS,EAAyB,GAAO;CACvC,OAAO,kBAAkB,KAAK,OAAO,KAAS,EAAE,CAAC,CAAC,KAAK,CAAC;AAC1D;AAEA,SAAS,EAAsB,GAAO;CACpC,IAAM,IAAO,OAAO,KAAS,EAAE,CAAC,CAAC,KAAK;CACtC,OACE,kEAAkE,KAAK,CAAI,KACxE,mBAAmB,KAAK,CAAI;AAEnC;AAEA,SAAS,EAAwB,GAAO,GAAW;CACjD,IAAM,IAAO,OAAO,KAAS,EAAE,CAAC,CAAC,KAAK,GAChC,IAAmB,EACvB,GAAW,aACX,GAAW,cAAc,iBAAiB,WAC5C;CAEA,OACG,KAAoB,M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CAEX;CAEA,OAAO;AACT"}
@@ -0,0 +1,2 @@
1
+ var e=require("./rolldown-runtime-Chgba0Kb.cjs").t({fetchFormGroupsCached:()=>a,invalidateFormGroupsCache:()=>i}),t=4e3,n=new Map,r=t;function i(){n.clear()}function a(e,t){let i=Date.now(),a=n.get(e);if(a&&(a.pending||i-a.at<r))return a.promise;let o={at:i,pending:!0};return o.promise=Promise.resolve().then(t).then(e=>(o.pending=!1,o.at=Date.now(),e)).catch(t=>{throw n.get(e)===o&&n.delete(e),t}),n.set(e,o),o.promise}Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
2
+ //# sourceMappingURL=formGroupsCache-Bbz-28ws.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formGroupsCache-Bbz-28ws.cjs","names":[],"sources":["../src/services/formGroupsCache.js"],"sourcesContent":["// formGroupsCache — one network request per distinct form-groups query.\n//\n// WHY\n// A single page routinely asks for the SAME form-groups payload several times\n// over, because the parts that need it are independent of each other and none\n// of them can know the others exist: on Quick Submit the job header card, the\n// form's cross-module prefill and a job-source lookup each fetch the same job,\n// and the submission config is fetched once unscoped and again client-scoped.\n// Those payloads are large (60 kB for a submission config), so the duplicates\n// are the expensive kind — a measured 245-request, ~4.8 s load with several\n// identical 60 kB and 15 kB responses in it.\n//\n// The honest fix is not to make each caller aware of the others — that couples\n// components that have no business knowing about each other, and breaks the\n// moment a new one is added. It is to make the REQUEST idempotent: identical\n// queries fired close together share one response.\n//\n// TWO MECHANISMS, deliberately:\n//\n// • in-flight coalescing — a query that is already running is joined rather\n// than reissued. Always safe: the answer cannot be staler than the request\n// that is still in the air.\n// • a SHORT time-to-live — covers the common case where the duplicates are\n// sequential rather than overlapping (a child mounts after its parent's\n// fetch has already resolved). This is the part that can serve stale data,\n// so it is kept to a few seconds and any write invalidates the whole cache.\n//\n// Errors are never cached: a failed fetch removes its entry so the next caller\n// retries for real instead of inheriting the failure.\n//\n// Nothing here knows a module or a field. The cache key is the request URL, so\n// scopes that differ in any way (id, clientId, view, group, action) are\n// different entries and can never be served each other's data.\n\n// Long enough to cover one page's mount burst, short enough that no realistic\n// user action fits inside it. Writes invalidate regardless — see below.\nconst DEFAULT_TTL_MS = 4000;\n\nconst entries = new Map(); // url -> { at, promise }\n\nlet ttlMs = DEFAULT_TTL_MS;\n\n/** Test/host hook: change the window, or set 0 to keep only in-flight coalescing. */\nexport function setFormGroupsCacheTtl(ms) {\n ttlMs = Math.max(0, Number(ms) || 0);\n}\n\n/**\n * Drop everything. Called after any module write: a save is exactly the moment\n * a cached payload stops describing the record, and a stale read here would\n * show the user their own change missing.\n */\nexport function invalidateFormGroupsCache() {\n entries.clear();\n}\n\n/**\n * fetchFormGroupsCached — run `loader()` for `url`, or join/replay a recent\n * identical run.\n *\n * `loader` returns the RAW payload, so every caller shares one request no\n * matter which shape it goes on to read out of it (the groups array, or the\n * whole envelope with recordMeta).\n */\nexport function fetchFormGroupsCached(url, loader) {\n const now = Date.now();\n const hit = entries.get(url);\n // A pending entry is always joinable; a settled one only within the window.\n if (hit && (hit.pending || now - hit.at < ttlMs)) return hit.promise;\n\n const entry = { at: now, pending: true };\n entry.promise = Promise.resolve()\n .then(loader)\n .then((value) => {\n entry.pending = false;\n // Stamp on COMPLETION, not on start: a slow request must not begin life\n // already half-expired, or a burst behind it would reissue immediately.\n entry.at = Date.now();\n return value;\n })\n .catch((err) => {\n // Never cache a failure — the next caller must get a real attempt.\n if (entries.get(url) === entry) entries.delete(url);\n throw err;\n });\n entries.set(url, entry);\n return entry.promise;\n}\n\nexport default { fetchFormGroupsCached, invalidateFormGroupsCache, setFormGroupsCacheTtl };\n"],"mappings":"kHAoCM,EAAiB,IAEjB,EAAU,IAAI,IAEhB,EAAQ,EAYZ,SAAgB,GAA4B,CAC1C,EAAQ,MAAM,CAChB,CAUA,SAAgB,EAAsB,EAAK,EAAQ,CACjD,IAAM,EAAM,KAAK,IAAI,EACf,EAAM,EAAQ,IAAI,CAAG,EAE3B,GAAI,IAAQ,EAAI,SAAW,EAAM,EAAI,GAAK,GAAQ,OAAO,EAAI,QAE7D,IAAM,EAAQ,CAAE,GAAI,EAAK,QAAS,EAAK,EAgBvC,MAfA,GAAM,QAAU,QAAQ,QAAQ,CAAC,CAC9B,KAAK,CAAM,CAAC,CACZ,KAAM,IACL,EAAM,QAAU,GAGhB,EAAM,GAAK,KAAK,IAAI,EACb,EACR,CAAC,CACD,MAAO,GAAQ,CAGd,MADI,EAAQ,IAAI,CAAG,IAAM,GAAO,EAAQ,OAAO,CAAG,EAC5C,CACR,CAAC,EACH,EAAQ,IAAI,EAAK,CAAK,EACf,EAAM,OACf"}
@@ -0,0 +1,24 @@
1
+ import { t as e } from "./rolldown-runtime-Dy4uBu1J.js";
2
+ //#region src/services/formGroupsCache.js
3
+ var t = /* @__PURE__ */ e({
4
+ fetchFormGroupsCached: () => o,
5
+ invalidateFormGroupsCache: () => a
6
+ }), n = 4e3, r = /* @__PURE__ */ new Map(), i = n;
7
+ function a() {
8
+ r.clear();
9
+ }
10
+ function o(e, t) {
11
+ let n = Date.now(), a = r.get(e);
12
+ if (a && (a.pending || n - a.at < i)) return a.promise;
13
+ let o = {
14
+ at: n,
15
+ pending: !0
16
+ };
17
+ return o.promise = Promise.resolve().then(t).then((e) => (o.pending = !1, o.at = Date.now(), e)).catch((t) => {
18
+ throw r.get(e) === o && r.delete(e), t;
19
+ }), r.set(e, o), o.promise;
20
+ }
21
+ //#endregion
22
+ export { t as n, a as r, o as t };
23
+
24
+ //# sourceMappingURL=formGroupsCache-JeC59oNe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"formGroupsCache-JeC59oNe.js","names":[],"sources":["../src/services/formGroupsCache.js"],"sourcesContent":["// formGroupsCache — one network request per distinct form-groups query.\n//\n// WHY\n// A single page routinely asks for the SAME form-groups payload several times\n// over, because the parts that need it are independent of each other and none\n// of them can know the others exist: on Quick Submit the job header card, the\n// form's cross-module prefill and a job-source lookup each fetch the same job,\n// and the submission config is fetched once unscoped and again client-scoped.\n// Those payloads are large (60 kB for a submission config), so the duplicates\n// are the expensive kind — a measured 245-request, ~4.8 s load with several\n// identical 60 kB and 15 kB responses in it.\n//\n// The honest fix is not to make each caller aware of the others — that couples\n// components that have no business knowing about each other, and breaks the\n// moment a new one is added. It is to make the REQUEST idempotent: identical\n// queries fired close together share one response.\n//\n// TWO MECHANISMS, deliberately:\n//\n// • in-flight coalescing — a query that is already running is joined rather\n// than reissued. Always safe: the answer cannot be staler than the request\n// that is still in the air.\n// • a SHORT time-to-live — covers the common case where the duplicates are\n// sequential rather than overlapping (a child mounts after its parent's\n// fetch has already resolved). This is the part that can serve stale data,\n// so it is kept to a few seconds and any write invalidates the whole cache.\n//\n// Errors are never cached: a failed fetch removes its entry so the next caller\n// retries for real instead of inheriting the failure.\n//\n// Nothing here knows a module or a field. The cache key is the request URL, so\n// scopes that differ in any way (id, clientId, view, group, action) are\n// different entries and can never be served each other's data.\n\n// Long enough to cover one page's mount burst, short enough that no realistic\n// user action fits inside it. Writes invalidate regardless — see below.\nconst DEFAULT_TTL_MS = 4000;\n\nconst entries = new Map(); // url -> { at, promise }\n\nlet ttlMs = DEFAULT_TTL_MS;\n\n/** Test/host hook: change the window, or set 0 to keep only in-flight coalescing. */\nexport function setFormGroupsCacheTtl(ms) {\n ttlMs = Math.max(0, Number(ms) || 0);\n}\n\n/**\n * Drop everything. Called after any module write: a save is exactly the moment\n * a cached payload stops describing the record, and a stale read here would\n * show the user their own change missing.\n */\nexport function invalidateFormGroupsCache() {\n entries.clear();\n}\n\n/**\n * fetchFormGroupsCached — run `loader()` for `url`, or join/replay a recent\n * identical run.\n *\n * `loader` returns the RAW payload, so every caller shares one request no\n * matter which shape it goes on to read out of it (the groups array, or the\n * whole envelope with recordMeta).\n */\nexport function fetchFormGroupsCached(url, loader) {\n const now = Date.now();\n const hit = entries.get(url);\n // A pending entry is always joinable; a settled one only within the window.\n if (hit && (hit.pending || now - hit.at < ttlMs)) return hit.promise;\n\n const entry = { at: now, pending: true };\n entry.promise = Promise.resolve()\n .then(loader)\n .then((value) => {\n entry.pending = false;\n // Stamp on COMPLETION, not on start: a slow request must not begin life\n // already half-expired, or a burst behind it would reissue immediately.\n entry.at = Date.now();\n return value;\n })\n .catch((err) => {\n // Never cache a failure — the next caller must get a real attempt.\n if (entries.get(url) === entry) entries.delete(url);\n throw err;\n });\n entries.set(url, entry);\n return entry.promise;\n}\n\nexport default { fetchFormGroupsCached, invalidateFormGroupsCache, setFormGroupsCacheTtl };\n"],"mappings":";;;;;IAoCM,IAAiB,KAEjB,oBAAU,IAAI,IAAI,GAEpB,IAAQ;AAYZ,SAAgB,IAA4B;CAC1C,EAAQ,MAAM;AAChB;AAUA,SAAgB,EAAsB,GAAK,GAAQ;CACjD,IAAM,IAAM,KAAK,IAAI,GACf,IAAM,EAAQ,IAAI,CAAG;CAE3B,IAAI,MAAQ,EAAI,WAAW,IAAM,EAAI,KAAK,IAAQ,OAAO,EAAI;CAE7D,IAAM,IAAQ;EAAE,IAAI;EAAK,SAAS;CAAK;CAgBvC,OAfA,EAAM,UAAU,QAAQ,QAAQ,CAAC,CAC9B,KAAK,CAAM,CAAC,CACZ,MAAM,OACL,EAAM,UAAU,IAGhB,EAAM,KAAK,KAAK,IAAI,GACb,EACR,CAAC,CACD,OAAO,MAAQ;EAGd,MADI,EAAQ,IAAI,CAAG,MAAM,KAAO,EAAQ,OAAO,CAAG,GAC5C;CACR,CAAC,GACH,EAAQ,IAAI,GAAK,CAAK,GACf,EAAM;AACf"}