@first-to-fly/crm-sdk 1.9.0 → 1.11.0
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.
- package/README.md +264 -7
- package/dist/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +4 -4
- package/dist/api.d.ts +4 -4
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/{crm-contracts-BiR0JbKC.d.cts → crm-contracts-BeC2pzgj.d.cts} +102 -5
- package/dist/{crm-contracts-BiR0JbKC.d.ts → crm-contracts-BeC2pzgj.d.ts} +102 -5
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +61 -2
- package/dist/embed-host.d.ts +61 -2
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +1 -1
- package/dist/embed-react.cjs.map +1 -1
- package/dist/embed-react.d.cts +44 -1
- package/dist/embed-react.d.ts +44 -1
- package/dist/embed-react.js +1 -1
- package/dist/embed-react.js.map +1 -1
- package/dist/partner.cjs +1 -1
- package/dist/partner.cjs.map +1 -1
- package/dist/partner.d.cts +186 -11
- package/dist/partner.d.ts +186 -11
- package/dist/partner.js +1 -1
- package/dist/partner.js.map +1 -1
- package/package.json +6 -1
package/dist/embed-react.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n hostContextQuery,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmHostBrand,\n type CrmHostTheme,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport {\n crmSession, type CrmSessionResult, type CrmHostTheme, type CrmHostBrand,\n};\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /**\n * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).\n * The first value rides on the iframe URL as `?theme=`; a later change is posted to\n * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies\n * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps\n * its default (light) look.\n */\n theme?: CrmHostTheme;\n /**\n * Language for the embedded CRM as a BCP 47 tag, e.g. \"en\" or \"zh-CN\". Sent like `theme`\n * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.\n */\n locale?: string;\n /**\n * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of\n * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes\n * are posted over the channel without a reload. Invalid fields are dropped. Pass the\n * tokens for your CURRENT theme and change the object when the theme toggles. See\n * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.\n */\n brand?: CrmHostBrand;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n theme,\n locale,\n brand,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n // Latest theme/locale. The first values seed the iframe URL and the host; later changes\n // are pushed through the channel by the effect below, never by rebuilding the iframe.\n const hostContextRef = useRef({ theme, locale, brand });\n hostContextRef.current = { theme, locale, brand };\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const path = initialPathRef.current ?? '';\n const query = [...(hostProvidesNav ? ['hostnav=1'] : []), ...hostContextQuery(hostContextRef.current)];\n const separator = path.includes('?') ? '&' : '?';\n const url = base + path + (query.length > 0 ? separator + query.join('&') : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n hostContext: hostContextRef.current,\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n // Phase 3: a theme/locale change after mount is sent to the frame, not a reload.\n // Compared by content, so an inline `brand={{...}}` does not re-send on every render.\n const brandKey = JSON.stringify(brand ?? null);\n const hadBrandRef = useRef(false);\n useEffect(() => {\n // Clear the frame's brand only if one was sent before; otherwise leave the field out.\n const brandUpdate = brand ? { brand } : (hadBrandRef.current ? { brand: null } : {});\n hadBrandRef.current = !!brand;\n hostRef.current?.setContext({ theme, locale, ...brandUpdate });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- brandKey stands in for brand\n }, [theme, locale, brandKey]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /** Initial theme/locale, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || (context.theme === undefined && context.locale === undefined && context.brand === undefined)) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,GAAY,eAAAC,GAAa,aAAAC,EAAW,uBAAAC,GAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QCwDP,IAAMC,GAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,GAAa,4CAEbC,GAAY,kCACZC,GAAY,8BACZC,GAAa,uBAInB,IAAMC,GAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GAAI,GAACC,GAAKA,EAAE,OAAS,KAAY,CAACC,GAAW,KAAKD,CAAC,IAC9C,GAAAA,EAAE,MAAM,IAAI,GAAG,QAAU,GAAK,IAAM,IAAMA,EAAE,MAAM,IAAI,GAAG,QAAU,G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AAG,SAAAxC,EAAcA,EAAYrB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5EuB,EAKH1B,EAAC,UACC,IAAKwB,EACL,IAAKE,EACL,MAAOb,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,GAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAA+D,EAAA,CAAG,SAAAzC,EAAgBA,EAAc,EAAIvB,GAAe,EAAE,CAYjE,CACF,EAEOiE,GAAQ3D","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","hostContextQuery","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","next","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","theme","locale","brand","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","hostContextRef","useCallback","n","cancelled","session","base","buildCrmEmbedUrl","query","hostContextQuery","separator","url","e","iframe","host","createCrmEmbedHost","primed","brandKey","hadBrandRef","brandUpdate","Fragment","embed_react_default"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-react.tsx","../src/embed-host.ts"],"sourcesContent":["/**\n * Drop-in React component that embeds the First To Fly CRM as a cross-origin\n * iframe, authenticated WITHOUT cookies.\n *\n * This wraps the low-level {@link ./embed-host | embed-host} helpers into a\n * single component. You supply a `getSession()` that returns a CRM bearer plus\n * the workspace to embed (typically by calling your own backend endpoint that\n * runs `createEmbedSessionWithKey`), and the component handles:\n * - resolving the session and building the iframe URL,\n * - rendering the iframe and running the MessageChannel handshake,\n * - reusing the initial bearer (no double-mint) and re-minting on expiry,\n * - loading / error / retry states.\n *\n * A host (e.g. an app shell) can drive the embedded CRM's section navigation\n * imperatively via a ref (`navigate(path)`), observe the CRM's own navigation\n * via `onRouteChange`, deep-link an `initialPath` on first load, and hide the\n * CRM's in-iframe nav via `hostProvidesNav` (when the host supplies its own).\n *\n * `react` is an OPTIONAL peer dependency — only pull in this entry if you use\n * React. Non-React consumers can keep using `./embed-host` directly.\n *\n * @packageDocumentation\n */\n\nimport {\n forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState,\n} from 'react';\nimport type { CSSProperties, ReactNode } from 'react';\n\nimport {\n buildCrmEmbedUrl,\n createCrmEmbedHost,\n crmSession,\n hostContextQuery,\n type CrmBearer,\n type CrmEmbedHost,\n type CrmHostBrand,\n type CrmHostCapability,\n type CrmHostActionRequest,\n type CrmHostTheme,\n type CrmSessionResult,\n} from './embed-host';\n\n// Re-export the session-fetch helper so React users can get it from one entry:\n// import { CrmEmbed, crmSession } from '@first-to-fly/crm-sdk/embed-react';\nexport {\n crmSession, type CrmSessionResult, type CrmHostTheme, type CrmHostBrand,\n type CrmHostCapability, type CrmHostActionRequest,\n};\n\n/**\n * What a partner's `getSession()` must resolve to. Alias of {@link CrmSessionResult}\n * (the browser-side session shape) — kept as a named export for back-compat; both\n * are `{ accessToken, workspaceId, expiresIn? }`.\n */\nexport type CrmEmbedSession = CrmSessionResult;\n\n/**\n * Imperative handle exposed via `ref`. Lets a host drive the embedded CRM's\n * navigation without re-rendering the iframe.\n */\nexport interface CrmEmbedHandle {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n}\n\nexport interface CrmEmbedProps {\n /**\n * Resolves a CRM bearer + the workspace to embed. Called once on mount (and\n * again on retry / session expiry). Typically calls your own backend endpoint\n * that runs `createEmbedSessionWithKey`.\n */\n getSession: () => Promise<CrmEmbedSession>;\n /**\n * The CRM embed base origin, e.g. \"https://crm.example.com\". The iframe URL\n * is `buildCrmEmbedUrl(crmEmbedOrigin, workspaceId)` and this origin is also\n * used as the postMessage targetOrigin.\n */\n crmEmbedOrigin: string;\n /** Class applied to the iframe. */\n className?: string;\n /** Inline style merged onto the iframe (overrides the fill-container default). */\n style?: CSSProperties;\n /** Iframe title (accessibility). Defaults to \"CRM\". */\n title?: string;\n /** Called after the iframe URL is built and mounted. */\n onReady?: (info: { workspaceId: string }) => void;\n /** Called on any session / handshake error. */\n onError?: (error: Error) => void;\n /**\n * Called when the CRM navigates internally (e.g. \"/contacts\"). Use this to\n * keep a host-supplied nav in sync with the embedded CRM's current section.\n */\n onRouteChange?: (path: string) => void;\n /**\n * When true, the CRM hides its own in-iframe nav (the host supplies it).\n * Signalled to the CRM by appending `?hostnav=1` to the iframe URL. Drive\n * navigation yourself via the ref's `navigate()`.\n */\n hostProvidesNav?: boolean;\n /**\n * Initial CRM sub-path to deep-link on FIRST load (e.g. \"/contacts\").\n * Only applied to the initial iframe URL — later changes do NOT reload the\n * iframe; use the ref's `navigate()` for in-session navigation.\n */\n initialPath?: string;\n /**\n * Theme for the embedded CRM: `light`, `dark`, or `system` (follow the visitor's OS).\n * The first value rides on the iframe URL as `?theme=`; a later change is posted to\n * the frame over the channel (`crm:host-context`) without reloading it. The CRM applies\n * it for the embed only and never saves it to the user's account. Omitted: the CRM keeps\n * its default (light) look.\n */\n theme?: CrmHostTheme;\n /**\n * Language for the embedded CRM as a BCP 47 tag, e.g. \"en\" or \"zh-CN\". Sent like `theme`\n * (`?locale=`, then `crm:host-context`). Omitted: the CRM keeps its own language.\n */\n locale?: string;\n /**\n * Brand tokens (accent, surfaces, border, radius, fonts) so the CRM looks like part of\n * your app. First value rides on the iframe URL as `?brand=` (base64url JSON); changes\n * are posted over the channel without a reload. Invalid fields are dropped. Pass the\n * tokens for your CURRENT theme and change the object when the theme toggles. See\n * {@link CrmHostBrand}. Omitted: the CRM keeps its own look.\n */\n brand?: CrmHostBrand;\n /**\n * Host actions the CRM may offer its users (\"create-lead\", \"open-person\"). List only what\n * `onHostAction` really handles. Sent over the channel, never in the URL. Gates the CRM's\n * UI only: authorise every action on your server too.\n */\n capabilities?: CrmHostCapability[];\n /** Short name of your app (max 40 chars), used on CRM buttons and cards, e.g. \"myEdu\". */\n hostName?: string;\n /** The user asked for a host action (create an enquiry, open a person). See `capabilities`. */\n onHostAction?: (request: CrmHostActionRequest) => void;\n /** Custom loading UI. Defaults to a minimal message. */\n renderLoading?: () => ReactNode;\n /** Custom error UI. Defaults to the message + a Retry button. */\n renderError?: (error: Error, retry: () => void) => ReactNode;\n}\n\nconst DEFAULT_IFRAME_STYLE: CSSProperties = {\n width: '100%',\n height: '100%',\n border: 0,\n};\n\nfunction toError(err: unknown): Error {\n return err instanceof Error ? err : new Error(String(err));\n}\n\nfunction DefaultLoading(): ReactNode {\n return <div>Loading CRM…</div>;\n}\n\nfunction DefaultError(error: Error, retry: () => void): ReactNode {\n return (\n <div>\n <p>Couldn’t load the CRM: {error.message}</p>\n <button type=\"button\" onClick={retry}>Try again</button>\n </div>\n );\n}\n\n/**\n * Embed the First To Fly CRM in a React app. See {@link CrmEmbedProps}.\n *\n * Accepts a `ref` of type {@link CrmEmbedHandle} exposing `navigate(path)` so a\n * host can drive the embedded CRM's section navigation.\n */\nexport const CrmEmbed = forwardRef<CrmEmbedHandle, CrmEmbedProps>(\n function CrmEmbed(props, ref): ReactNode {\n const {\n getSession,\n crmEmbedOrigin,\n className,\n style,\n title = 'CRM',\n onReady,\n onError,\n onRouteChange,\n hostProvidesNav,\n initialPath,\n theme,\n locale,\n brand,\n capabilities,\n hostName,\n onHostAction,\n renderLoading,\n renderError,\n } = props;\n\n const iframeRef = useRef<HTMLIFrameElement>(null);\n const [embedUrl, setEmbedUrl] = useState<string | null>(null);\n const [workspaceId, setWorkspaceId] = useState<string | null>(null);\n const [error, setError] = useState<Error | null>(null);\n const [attempt, setAttempt] = useState(0);\n\n // Bearer minted during session resolution — reused for the host's first\n // getBearer() so a single getSession() call covers both phases (no double-mint).\n const primedBearerRef = useRef<CrmBearer | null>(null);\n\n // The created host, so the imperative `navigate()` can reach it.\n const hostRef = useRef<CrmEmbedHost | null>(null);\n\n // Expose the imperative navigate(). No-ops safely before the host is wired.\n useImperativeHandle(ref, () => ({\n navigate: (path: string) => { hostRef.current?.navigate(path); },\n }), []);\n\n // Keep the latest callbacks in refs so the effects DON'T depend on their\n // identity. Partners routinely pass inline `getSession`/`onReady`/`onError`/\n // `onRouteChange`; depending on them directly would re-run Phase 1 (re-fetch\n // the session) and tear down + recreate the host on every parent re-render.\n const getSessionRef = useRef(getSession);\n const onReadyRef = useRef(onReady);\n const onErrorRef = useRef(onError);\n const onRouteChangeRef = useRef(onRouteChange);\n const onHostActionRef = useRef(onHostAction);\n useEffect(() => {\n getSessionRef.current = getSession;\n onReadyRef.current = onReady;\n onErrorRef.current = onError;\n onRouteChangeRef.current = onRouteChange;\n onHostActionRef.current = onHostAction;\n });\n\n // Capture initialPath ONCE — it only seeds the first load. Later changes go\n // through the imperative navigate() and must NOT rebuild/reload the iframe.\n const initialPathRef = useRef(initialPath);\n\n // Latest theme/locale. The first values seed the iframe URL and the host; later changes\n // are pushed through the channel by the effect below, never by rebuilding the iframe.\n const hostContextRef = useRef({\n theme, locale, brand, capabilities, hostName,\n });\n hostContextRef.current = {\n theme, locale, brand, capabilities, hostName,\n };\n\n const retry = useCallback(() => {\n primedBearerRef.current = null;\n setError(null);\n setEmbedUrl(null);\n setWorkspaceId(null);\n setAttempt((n) => n + 1);\n }, []);\n\n // Phase 1: resolve the session, prime the bearer, and build the iframe URL.\n // Re-runs only on retry (`attempt`) or a changed origin/hostnav — never on\n // unrelated parent re-renders (callbacks + initialPath are read from refs).\n useEffect(() => {\n let cancelled = false;\n\n void (async () => {\n try {\n const session = await getSessionRef.current();\n if (cancelled) return;\n primedBearerRef.current = { accessToken: session.accessToken };\n setWorkspaceId(session.workspaceId);\n const base = buildCrmEmbedUrl(crmEmbedOrigin, session.workspaceId);\n const path = initialPathRef.current ?? '';\n const query = [...(hostProvidesNav ? ['hostnav=1'] : []), ...hostContextQuery(hostContextRef.current)];\n const separator = path.includes('?') ? '&' : '?';\n const url = base + path + (query.length > 0 ? separator + query.join('&') : '');\n setEmbedUrl(url);\n } catch (err) {\n if (cancelled) return;\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n }\n })();\n\n return () => { cancelled = true; };\n }, [crmEmbedOrigin, hostProvidesNav, attempt]);\n\n // Phase 2: once the iframe URL is known, wire the MessageChannel host.\n useEffect(() => {\n const iframe = iframeRef.current;\n if (!iframe || !embedUrl || !workspaceId) return undefined;\n\n let host: CrmEmbedHost | null = null;\n try {\n host = createCrmEmbedHost({\n iframe,\n crmOrigin: crmEmbedOrigin,\n getBearer: async () => {\n const primed = primedBearerRef.current;\n if (primed) {\n primedBearerRef.current = null;\n return primed;\n }\n const session = await getSessionRef.current();\n return { accessToken: session.accessToken };\n },\n hostContext: hostContextRef.current,\n onRouteChange: (path) => { onRouteChangeRef.current?.(path); },\n onHostAction: (request) => { onHostActionRef.current?.(request); },\n onError: (err) => {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n },\n });\n } catch (err) {\n const e = toError(err);\n setError(e);\n onErrorRef.current?.(e);\n return undefined;\n }\n\n hostRef.current = host;\n\n // Only signal ready once the host is actually wired.\n onReadyRef.current?.({ workspaceId });\n\n return () => {\n host?.dispose();\n hostRef.current = null;\n };\n }, [embedUrl, workspaceId, crmEmbedOrigin]);\n\n // Phase 3: a theme/locale change after mount is sent to the frame, not a reload.\n // Compared by content, so an inline `brand={{...}}` does not re-send on every render.\n const brandKey = JSON.stringify(brand ?? null);\n const capabilitiesKey = JSON.stringify(capabilities ?? null);\n const hadBrandRef = useRef(false);\n useEffect(() => {\n // Clear the frame's brand only if one was sent before; otherwise leave the field out.\n const brandUpdate = brand ? { brand } : (hadBrandRef.current ? { brand: null } : {});\n hadBrandRef.current = !!brand;\n hostRef.current?.setContext({\n theme, locale, capabilities, hostName, ...brandUpdate,\n });\n // eslint-disable-next-line react-hooks/exhaustive-deps -- brandKey and capabilitiesKey stand in for the objects\n }, [theme, locale, brandKey, capabilitiesKey, hostName]);\n\n if (error) {\n return <>{renderError ? renderError(error, retry) : DefaultError(error, retry)}</>;\n }\n\n if (!embedUrl) {\n return <>{renderLoading ? renderLoading() : DefaultLoading()}</>;\n }\n\n return (\n <iframe\n ref={iframeRef}\n src={embedUrl}\n title={title}\n className={className}\n style={{ ...DEFAULT_IFRAME_STYLE, ...style }}\n />\n );\n },\n);\n\nexport default CrmEmbed;\n","/**\n * CRM Embed Host SDK (browser side).\n *\n * Use this in YOUR SaaS to embed the First To Fly CRM as a cross-origin iframe,\n * authenticated WITHOUT cookies. You render an <iframe> pointing at the CRM's\n * embed URL, and this helper runs the MessageChannel handshake that hands the\n * CRM a short-lived bearer token you mint server-side (see ./embed-server).\n *\n * Handshake (this side is the HOST/parent):\n * 1. CRM iframe posts { source: 'crm-embed', type: 'ready' }\n * 2. host replies { type: 'channel-init', nonce } + a MessagePort\n * 3. CRM iframe replies { type: 'channel-ack', nonce } on that port\n * 4. host sends { type: 'auth-tokens', accessToken } (your CRM bearer)\n * 5. CRM iframe streams { type: 'route-change' | 'resize' | 'session-expired' }\n * - on 'session-expired' the host re-fetches a bearer and re-sends it.\n * 6. host sends { type: 'crm:host-context', theme?, locale?, brand? } on the same port,\n * right after the bearer and again whenever {@link CrmEmbedHost.setContext} is called.\n * The first values also ride on the iframe URL (`?theme=`, `?locale=` and `?brand=`), so the\n * frame paints in the right theme before the handshake finishes.\n * The same message carries `capabilities` (which host actions the CRM may offer) and\n * `hostName` (a label for the host app). Those two ride on the channel only, never the URL.\n * 7. CRM iframe sends { type: 'crm:host-action', requestId, action: ... } when the user asks for\n * something only the host can do (see {@link CrmHostAction}). Delivered to `onHostAction`.\n *\n * @packageDocumentation\n */\n\n/** A CRM bearer (from the credential exchange). refreshToken is unused today. */\nexport interface CrmBearer {\n accessToken: string;\n refreshToken?: string;\n}\n\n/** Theme the host asks the embedded CRM to use. `system` follows the visitor's OS setting. */\nexport type CrmHostTheme = 'light' | 'dark' | 'system';\n\n/**\n * Brand tokens that make the embedded CRM look like part of the host. All optional.\n * Colours are `#rgb` or `#rrggbb`; invalid values are dropped, never sent.\n * Pass the values for the host's CURRENT theme and send a new brand when it toggles.\n * No remote font is loaded: a family the visitor's system lacks falls back to the CRM's.\n */\nexport interface CrmHostBrand {\n /** Buttons, selected tabs, focus rings, chart accent. */\n accent?: string;\n /** Text on the accent. Defaults to white or near-black, whichever reads better. */\n accentForeground?: string;\n /** Page background. */\n background?: string;\n /** Cards, popovers and inputs. Defaults to `background`. */\n surface?: string;\n /** Hairlines and input borders. Derived from background and foreground when omitted. */\n border?: string;\n /** Body text. */\n foreground?: string;\n /** Secondary text. Derived when omitted. */\n mutedForeground?: string;\n /** Corner radius for controls, `0px` to `24px`, e.g. `\"6px\"`. Larger surfaces scale from it. */\n radius?: string;\n /** UI font family list, e.g. `\"Inter, system-ui\"`. Letters, digits, spaces, commas, quotes, hyphens, underscores; max 160 chars. */\n fontFamily?: string;\n /** Font for page titles, same rules as `fontFamily`, e.g. `\"Fraunces, Georgia, serif\"`. */\n displayFontFamily?: string;\n}\n\n/** Host actions the CRM may offer. The host lists the ones it implements in `capabilities`. */\nexport type CrmHostCapability = 'create-lead' | 'open-person';\n\n/** Who the user is acting on, as the CRM shows it. Only what the user can see is sent. */\nexport interface CrmHostActionContact {\n /** The CRM contact id. */\n crmContactId: string;\n name?: string;\n phone?: string;\n email?: string;\n}\n\n/**\n * Something the user asked the host to do from inside the embedded CRM.\n * Capabilities gate the CRM's UI only: the host MUST re-authorise every action server-side\n * and treat every field as untrusted input.\n */\nexport type CrmHostAction =\n | {\n action: 'create-lead';\n contact: CrmHostActionContact;\n conversationId: string;\n /** Channel of the conversation, e.g. \"whatsapp\". */\n channel?: string;\n /** The last inbound message text, at most 280 characters. */\n messageSnippet?: string;\n }\n | { action: 'open-person'; contact: { crmContactId: string } };\n\n/** A {@link CrmHostAction} as delivered to `onHostAction`, with the CRM's request id. */\nexport type CrmHostActionRequest = CrmHostAction & { requestId: string };\n\n/**\n * Look and language the host passes to the embedded CRM. Both are optional; an omitted\n * field leaves the CRM's own behaviour unchanged. The CRM applies them for the embed only\n * and never saves them to the user's account.\n */\nexport interface CrmHostContext {\n theme?: CrmHostTheme;\n /** BCP 47 language tag, e.g. \"en\" or \"zh-CN\". */\n locale?: string;\n /**\n * Host brand tokens. A new brand REPLACES the previous one; `null` (setContext only)\n * returns the CRM to its own look. Omitted: unchanged.\n */\n brand?: CrmHostBrand | null;\n /**\n * Host actions the CRM may offer. Channel only (never in the URL). Known values only,\n * de-duplicated, at most 8. A new list REPLACES the old one; `[]` turns every action off.\n * Omitted: unchanged (none before the first value).\n */\n capabilities?: CrmHostCapability[];\n /** Short name of the host app (max 40 chars), shown on buttons and cards, e.g. \"myEdu\". Channel only. */\n hostName?: string;\n}\n\n/** The message the host posts on the channel port to update {@link CrmHostContext}. */\nexport interface CrmHostContextMessage extends CrmHostContext {\n type: 'crm:host-context';\n}\n\nconst HOST_CAPABILITIES: readonly string[] = ['create-lead', 'open-person'];\nconst CAPABILITIES_MAX = 8;\nconst HOST_NAME_MAX = 40;\nconst ACTION_REQUEST_ID_MAX = 64;\nconst ACTION_ID_MAX = 100;\nconst ACTION_NAME_MAX = 200;\nconst ACTION_EMAIL_MAX = 320;\nconst ACTION_PHONE_MAX = 40;\nconst ACTION_CHANNEL_MAX = 40;\n/** Longest `messageSnippet` the CRM sends and the host accepts. */\nexport const HOST_ACTION_SNIPPET_MAX = 280;\n\nconst HOST_THEMES: readonly string[] = ['light', 'dark', 'system'];\nconst BCP47_LIKE = /^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8}){0,3}$/;\n\nconst HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;\nconst RADIUS_PX = /^(\\d{1,2}(?:\\.\\d{1,2})?)px$/;\nconst FONT_CHARS = /^[A-Za-z0-9 ,'\"_-]+$/;\nconst FONT_MAX = 160;\n/** The encoded `?brand=` value never exceeds this; a longer one would be ignored by the CRM. */\nconst BRAND_PARAM_MAX = 1500;\nconst BRAND_COLOR_KEYS = [\n 'accent', 'accentForeground', 'background', 'surface', 'border', 'foreground', 'mutedForeground',\n] as const;\n\nfunction cleanFont(value: unknown): string | undefined {\n if (typeof value !== 'string') return undefined;\n const v = value.trim();\n if (!v || v.length > FONT_MAX || !FONT_CHARS.test(v)) return undefined;\n if ((v.match(/\"/g)?.length ?? 0) % 2 !== 0 || (v.match(/'/g)?.length ?? 0) % 2 !== 0) return undefined;\n return v;\n}\n\n/**\n * Keeps only valid brand fields: hex colours (lower-cased `#rrggbb`), a `0-24px` radius and\n * safe font-family lists. Returns undefined when nothing valid is left.\n */\nexport function normalizeHostBrand(brand: CrmHostBrand | undefined | null): CrmHostBrand | undefined {\n if (!brand || typeof brand !== 'object' || Array.isArray(brand)) return undefined;\n const out: CrmHostBrand = {};\n for (const key of BRAND_COLOR_KEYS) {\n const raw = brand[key];\n if (typeof raw === 'string' && HEX_COLOR.test(raw.trim())) {\n let hex = raw.trim().toLowerCase();\n if (hex.length === 4) hex = `#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`;\n out[key] = hex;\n }\n }\n if (typeof brand.radius === 'string') {\n const m = RADIUS_PX.exec(brand.radius.trim());\n if (m && Number(m[1]) <= 24) out.radius = `${Number(m[1])}px`;\n }\n const fontFamily = cleanFont(brand.fontFamily);\n if (fontFamily) out.fontFamily = fontFamily;\n const displayFontFamily = cleanFont(brand.displayFontFamily);\n if (displayFontFamily) out.displayFontFamily = displayFontFamily;\n return Object.keys(out).length > 0 ? out : undefined;\n}\n\n/** Encodes a brand for the `?brand=` query value (base64url JSON), or null when empty or too long. */\nexport function encodeHostBrand(brand: CrmHostBrand | undefined | null): string | null {\n const clean = normalizeHostBrand(brand);\n if (!clean) return null;\n const bytes = new TextEncoder().encode(JSON.stringify(clean));\n let bin = '';\n bytes.forEach((b) => { bin += String.fromCharCode(b); });\n const encoded = btoa(bin).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n return encoded.length <= BRAND_PARAM_MAX ? encoded : null;\n}\n\n/**\n * Keeps only values the CRM understands: a known theme, a well-formed language tag and a\n * valid brand. Anything else is dropped, so a bad value can never reach the iframe URL or\n * the message. `brand: null` is kept so a message can clear an earlier brand.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\n if (ctx?.brand === null) out.brand = null;\n else {\n const brand = normalizeHostBrand(ctx?.brand);\n if (brand) out.brand = brand;\n }\n if (ctx?.theme && HOST_THEMES.includes(ctx.theme)) out.theme = ctx.theme;\n if (typeof ctx?.locale === 'string' && BCP47_LIKE.test(ctx.locale.trim())) out.locale = ctx.locale.trim();\n if (Array.isArray(ctx?.capabilities)) {\n const known = ctx.capabilities.filter((c): c is CrmHostCapability => HOST_CAPABILITIES.includes(c));\n out.capabilities = [...new Set(known)].slice(0, CAPABILITIES_MAX);\n }\n if (typeof ctx?.hostName === 'string') {\n const name = ctx.hostName.trim();\n if (name && name.length <= HOST_NAME_MAX && !/[\\u0000-\\u001f\\u007f]/.test(name)) out.hostName = name;\n }\n return out;\n}\n\nfunction boundedString(value: unknown, max: number, required: boolean): string | undefined | null {\n if (value === undefined) return required ? null : undefined;\n if (typeof value !== 'string') return null;\n const v = value.trim();\n if (v.length > max) return null;\n if (!v) return required ? null : undefined;\n return v;\n}\n\n/**\n * Validates a `crm:host-action` port message. Returns a clean request, or null when the\n * message is malformed, has an unknown action, or any field is too long. Unknown fields are\n * dropped. Never throws.\n */\nexport function parseHostActionMessage(data: unknown): CrmHostActionRequest | null {\n if (!data || typeof data !== 'object') return null;\n const m = data as Record<string, unknown>;\n if (m.type !== 'crm:host-action') return null;\n const requestId = boundedString(m.requestId, ACTION_REQUEST_ID_MAX, true);\n if (!requestId) return null;\n const c = m.contact;\n if (!c || typeof c !== 'object' || Array.isArray(c)) return null;\n const rc = c as Record<string, unknown>;\n const crmContactId = boundedString(rc.crmContactId, ACTION_ID_MAX, true);\n if (!crmContactId) return null;\n\n if (m.action === 'open-person') {\n return { requestId, action: 'open-person', contact: { crmContactId } };\n }\n if (m.action !== 'create-lead') return null;\n\n const name = boundedString(rc.name, ACTION_NAME_MAX, false);\n const phone = boundedString(rc.phone, ACTION_PHONE_MAX, false);\n const email = boundedString(rc.email, ACTION_EMAIL_MAX, false);\n const conversationId = boundedString(m.conversationId, ACTION_ID_MAX, true);\n const channel = boundedString(m.channel, ACTION_CHANNEL_MAX, false);\n const messageSnippet = boundedString(m.messageSnippet, HOST_ACTION_SNIPPET_MAX, false);\n if ([name, phone, email, channel, messageSnippet].some((v) => v === null) || !conversationId) return null;\n\n const contact: CrmHostActionContact = { crmContactId };\n if (name) contact.name = name;\n if (phone) contact.phone = phone;\n if (email) contact.email = email;\n const out: CrmHostActionRequest = {\n requestId, action: 'create-lead', contact, conversationId,\n };\n if (channel) out.channel = channel;\n if (messageSnippet) out.messageSnippet = messageSnippet;\n return out;\n}\n\n/** `theme`, `locale` and `brand` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\", \"brand=eyJ...\"]`). */\nexport function hostContextQuery(ctx: CrmHostContext | undefined): string[] {\n const clean = normalizeHostContext(ctx);\n const pairs: string[] = [];\n if (clean.theme) pairs.push(`theme=${encodeURIComponent(clean.theme)}`);\n if (clean.locale) pairs.push(`locale=${encodeURIComponent(clean.locale)}`);\n const brand = clean.brand ? encodeHostBrand(clean.brand) : null;\n if (brand) pairs.push(`brand=${brand}`);\n return pairs;\n}\n\nexport interface CrmEmbedHostOptions {\n /** The <iframe> element that loads the CRM embed URL. */\n iframe: HTMLIFrameElement;\n /**\n * Origin the CRM is served from — the postMessage targetOrigin, e.g.\n * \"https://app.crm.example.com\". Must match the iframe's origin exactly.\n */\n crmOrigin: string;\n /**\n * Returns a fresh CRM bearer. Called once on connect and again whenever the\n * CRM reports its session expired. Typically calls your own backend endpoint\n * that runs createEmbedSessionWithKey() (see ./embed-server) — the {@link crmSession}\n * helper wraps that fetch for you.\n */\n getBearer: () => Promise<CrmBearer>;\n /** Called when the CRM navigates internally (e.g. \"/contacts\"). */\n onRouteChange?: (path: string) => void;\n /** Called when the CRM reports its content height (for iframe auto-resize). */\n onResize?: (height: number) => void;\n /** Called on any handshake/bearer error. */\n onError?: (err: unknown) => void;\n /**\n * Called when the user asks for something only the host can do (a {@link CrmHostAction}).\n * Messages that are malformed, oversize or of an unknown action never reach it, and nothing\n * is delivered before the handshake completes. Re-authorise every action on your server.\n */\n onHostAction?: (request: CrmHostActionRequest) => void;\n /** Initial theme/locale/capabilities, sent to the CRM once the channel is up. Change it with `setContext()`. */\n hostContext?: CrmHostContext;\n /**\n * DEV ONLY: accept the CRM's `ready` from any origin (cross-port localhost).\n * NEVER enable in production — it disables the origin check.\n */\n devAllowAnyOrigin?: boolean;\n /** Test seam — defaults to the global MessageChannel. */\n createChannel?: () => MessageChannel;\n /** Test seam — defaults to `window` as the message-event target. */\n windowTarget?: Pick<Window, 'addEventListener' | 'removeEventListener'>;\n}\n\nexport interface CrmEmbedHost {\n /** Tell the CRM to navigate to a sub-path, e.g. \"/contacts\" or \"/leads/123\". */\n navigate: (path: string) => void;\n /**\n * Update the theme and/or language of the embedded CRM. Sent over the established\n * channel only, never broadcast with a wildcard origin. Fields you leave out keep\n * their last value; before the channel is up the latest values go out on connect.\n */\n setContext: (ctx: CrmHostContext) => void;\n /** Tear down the channel and listeners. Call on unmount. */\n dispose: () => void;\n}\n\ninterface CrmReadyMessage { source: 'crm-embed'; type: 'ready' }\ntype ChildMessage =\n | { type: 'channel-ack'; nonce: string }\n | { type: 'route-change'; path: string }\n | { type: 'resize'; height: number }\n | { type: 'session-expired' }\n | { type: 'crm:host-action'; requestId: string };\n\nfunction isReady(data: unknown): data is CrmReadyMessage {\n return !!data && typeof data === 'object'\n && (data as CrmReadyMessage).source === 'crm-embed'\n && (data as CrmReadyMessage).type === 'ready';\n}\n\n/** What your `/session` endpoint returns (matches `createCrmSessionHandler`). */\nexport interface CrmSessionResult {\n accessToken: string;\n workspaceId: string;\n expiresIn?: number;\n}\n\n/**\n * Build a `getSession()` that POSTs to your own session endpoint and returns\n * `{ accessToken, workspaceId, expiresIn? }`. Pairs with `createCrmSessionHandler`\n * on the server, so you don't hand-write the fetch/parse.\n *\n * <CrmEmbed crmEmbedOrigin={...} getSession={crmSession('/api/crm/session')} />\n *\n * On a non-2xx response it throws an Error carrying the server's `error` code.\n * Pass `init` to add headers/credentials (e.g. `{ credentials: 'include' }`).\n */\nexport function crmSession(\n url: string,\n init?: RequestInit,\n): () => Promise<CrmSessionResult> {\n return async (): Promise<CrmSessionResult> => {\n const res = await fetch(url, { method: 'POST', ...init });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = (body as { error?: string })?.error;\n throw new Error(\n code ? `CRM session failed: ${code}` : `CRM session failed (HTTP ${res.status})`,\n );\n }\n const result = body as Partial<CrmSessionResult>;\n // A malformed 2xx (e.g. `{}`) would otherwise cast cleanly and later build an\n // `/embed/undefined` URL — fail at the boundary with a clear message instead.\n if (typeof result?.accessToken !== 'string' || typeof result?.workspaceId !== 'string') {\n throw new Error('CRM session response is missing accessToken/workspaceId');\n }\n return result as CrmSessionResult;\n };\n}\n\n/**\n * Build the CRM embed iframe URL. The CRM resolves the tenant from the bearer,\n * so the workspaceId segment is only a routing hint.\n *\n * buildCrmEmbedUrl('https://app.crm.example.com', 'ws_123')\n * => 'https://app.crm.example.com/embed/ws_123'\n */\nexport function buildCrmEmbedUrl(crmOrigin: string, workspaceId: string): string {\n return `${crmOrigin.replace(/\\/$/, '')}/embed/${encodeURIComponent(workspaceId)}`;\n}\n\n/**\n * Wire the host side of the CRM embed. Attach this once the iframe is in the DOM.\n * Returns a handle with `navigate()` and `dispose()`.\n */\nexport function createCrmEmbedHost(opts: CrmEmbedHostOptions): CrmEmbedHost {\n const target = opts.windowTarget ?? window;\n const makeChannel = opts.createChannel ?? (() => new MessageChannel());\n const targetOrigin = opts.devAllowAnyOrigin ? '*' : opts.crmOrigin;\n\n let port: MessagePort | null = null;\n let nonce = '';\n let acked = false;\n let disposed = false;\n let context: CrmHostContext = normalizeHostContext(opts.hostContext);\n\n function sendContext(extra?: { brand: null }): void {\n if (extra) {\n port?.postMessage({ type: 'crm:host-context', ...context, ...extra } satisfies CrmHostContextMessage);\n return;\n }\n if (!port || Object.keys(context).length === 0) return;\n const msg: CrmHostContextMessage = { type: 'crm:host-context', ...context };\n port.postMessage(msg);\n }\n\n async function deliverBearer(): Promise<boolean> {\n try {\n const bearer = await opts.getBearer();\n port?.postMessage({\n type: 'auth-tokens',\n accessToken: bearer.accessToken,\n refreshToken: bearer.refreshToken ?? '',\n });\n sendContext();\n return true;\n } catch (err) {\n opts.onError?.(err);\n return false;\n }\n }\n\n function onPortMessage(e: MessageEvent<ChildMessage>): void {\n const data = e.data;\n if (!data) return;\n if (data.type === 'channel-ack') {\n if (data.nonce !== nonce) return; // stale/forged ack\n acked = true;\n void deliverBearer();\n } else if (data.type === 'route-change') {\n opts.onRouteChange?.(data.path);\n } else if (data.type === 'crm:host-action') {\n if (!acked) return; // nothing counts before the handshake completes\n const request = parseHostActionMessage(data);\n if (request) opts.onHostAction?.(request);\n } else if (data.type === 'resize') {\n opts.onResize?.(data.height);\n } else if (data.type === 'session-expired') {\n // Embed sessions renew by re-minting (no refresh-token flow). Only tell the\n // CRM the session refreshed once a fresh bearer was ACTUALLY delivered —\n // otherwise a failed re-mint leaves the iframe believing it's authenticated.\n void deliverBearer().then((ok) => {\n if (ok) port?.postMessage({ type: 'session-refreshed' });\n });\n }\n }\n\n function startHandshake(): void {\n port?.close();\n acked = false;\n const channel = makeChannel();\n port = channel.port1;\n nonce = globalThis.crypto?.randomUUID?.() ?? `n-${String(Math.random()).slice(2)}`;\n port.onmessage = onPortMessage;\n port.start?.();\n opts.iframe.contentWindow?.postMessage(\n { type: 'channel-init', nonce },\n targetOrigin,\n [channel.port2],\n );\n }\n\n function onWindowMessage(event: MessageEvent): void {\n if (disposed) return;\n if (event.source !== opts.iframe.contentWindow) return;\n if (!opts.devAllowAnyOrigin && event.origin !== opts.crmOrigin) return;\n if (isReady(event.data)) startHandshake();\n }\n\n target.addEventListener('message', onWindowMessage as EventListener);\n\n return {\n navigate(path: string): void {\n port?.postMessage({ type: 'navigate', path });\n },\n setContext(ctx: CrmHostContext): void {\n const next = normalizeHostContext(ctx);\n context = { ...context, ...next };\n if (next.brand === null) delete context.brand; // cleared: send null once, then forget it\n sendContext(next.brand === null ? { brand: null } : undefined);\n },\n dispose(): void {\n disposed = true;\n target.removeEventListener('message', onWindowMessage as EventListener);\n port?.close();\n port = null;\n },\n };\n}\n"],"mappings":"AAwBA,OACE,cAAAA,GAAY,eAAAC,GAAa,aAAAC,EAAW,uBAAAC,GAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QCoGP,IAAMC,GAAuC,CAAC,cAAe,aAAa,EAY1E,IAAMC,GAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,GAAa,4CAEbC,GAAY,kCACZC,GAAY,8BACZC,GAAa,uBAInB,IAAMC,GAAmB,CACvB,SAAU,mBAAoB,aAAc,UAAW,SAAU,aAAc,iBACjF,EAEA,SAASC,EAAUC,EAAoC,CACrD,GAAI,OAAOA,GAAU,SAAU,OAC/B,IAAMC,EAAID,EAAM,KAAK,EACrB,GA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AQ,CAAC,EAEnDrB,EACKF,EAAAqE,GAAA,CAAG,SAAA3C,EAAcA,EAAYxB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5E0B,EAKH7B,EAAC,UACC,IAAK2B,EACL,IAAKE,EACL,MAAOhB,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,GAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAAqE,GAAA,CAAG,SAAA5C,EAAgBA,EAAc,EAAI1B,GAAe,EAAE,CAYjE,CACF,EAEOuE,GAAQjE","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","HOST_CAPABILITIES","HOST_THEMES","BCP47_LIKE","HEX_COLOR","RADIUS_PX","FONT_CHARS","BRAND_COLOR_KEYS","cleanFont","value","v","FONT_CHARS","normalizeHostBrand","brand","out","key","raw","HEX_COLOR","hex","m","RADIUS_PX","fontFamily","displayFontFamily","encodeHostBrand","clean","bytes","bin","b","encoded","normalizeHostContext","ctx","HOST_THEMES","BCP47_LIKE","known","c","HOST_CAPABILITIES","name","boundedString","max","required","parseHostActionMessage","data","requestId","rc","crmContactId","phone","email","conversationId","channel","messageSnippet","contact","hostContextQuery","pairs","isReady","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","acked","disposed","context","sendContext","extra","msg","deliverBearer","bearer","err","onPortMessage","e","request","ok","startHandshake","onWindowMessage","event","path","next","Fragment","jsx","jsxs","DEFAULT_IFRAME_STYLE","toError","err","DefaultLoading","jsx","DefaultError","error","retry","jsxs","CrmEmbed","forwardRef","props","ref","getSession","crmEmbedOrigin","className","style","title","onReady","onError","onRouteChange","hostProvidesNav","initialPath","theme","locale","brand","capabilities","hostName","onHostAction","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","onHostActionRef","useEffect","initialPathRef","hostContextRef","useCallback","n","cancelled","session","base","buildCrmEmbedUrl","query","hostContextQuery","separator","url","e","iframe","host","createCrmEmbedHost","primed","request","brandKey","capabilitiesKey","hadBrandRef","brandUpdate","Fragment","embed_react_default"]}
|
package/dist/partner.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var b=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var O=Object.prototype.hasOwnProperty;var N=(e,a)=>{for(var d in a)b(e,d,{get:a[d],enumerable:!0})},F=(e,a,d,g)=>{if(a&&typeof a=="object"||typeof a=="function")for(let y of M(a))!O.call(e,y)&&y!==d&&b(e,y,{get:()=>a[y],enumerable:!(g=D(a,y))||g.enumerable});return e};var L=e=>F(b({},"__esModule",{value:!0}),e);var Z={};N(Z,{AI_MONTHLY_CAP_MAX_CREDITS:()=>j,CONTACT_CHANGES_MAX_LIMIT:()=>$,CONTACT_REF_PATTERN:()=>I,CrmPartnerError:()=>f,EXTERNAL_REF_PATTERN:()=>S,createCrmPartnerClient:()=>K});module.exports=L(Z);function R(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function x(e,a){let d=e??globalThis.fetch;if(typeof d!="function")throw new Error(`${a}: no fetch implementation available. Pass \`fetch\` explicitly.`);return d}async function A(e,a,d,g){let y=new AbortController,c=!1,u=setTimeout(()=>{c=!0,y.abort()},a);try{let m={Accept:"application/json",...g.headers},C=g.body!==void 0;C&&(m["Content-Type"]="application/json");let s=await e(d,{method:g.method,headers:m,body:C?JSON.stringify(g.body):void 0,signal:y.signal}),n=await s.json().catch(()=>null);return c?{ok:!1,kind:"timeout"}:{ok:!0,status:s.status,json:n}}catch{return{ok:!1,kind:c?"timeout":"network"}}finally{clearTimeout(u)}}var q=/^[A-Za-z0-9_.:-]{1,60}$/;function E(e,a,d){let g=`HTTP_${a}`,y=c=>typeof c!="string"||!q.test(c)||d.some(u=>u&&c.includes(u))?null:c;if(e&&typeof e=="object"){let c=e,u=c.error;return y(c.code)??y(u)??(u&&typeof u=="object"?y(u.code):null)??g}return g}var k=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var f=class e extends Error{constructor(a,d){super(a===0?`CRM partner API unreachable (${d})`:`CRM partner API ${a} ${d}`),this.name="CrmPartnerError",this.status=a,this.code=d,Object.setPrototypeOf(this,e.prototype)}},S=/^[A-Za-z0-9_-]{1,64}$/,I=/^[A-Za-z0-9._:-]{1,200}$/,$=200,j=1e8,w=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null}),G=/^\d{4}-\d{2}-\d{2}$/;function T(e){let a=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof a!="string"||!G.test(a)||Number.isNaN(Date.parse(`${a}T00:00:00Z`))||new Date(`${a}T00:00:00Z`).toISOString().slice(0,10)!==a)throw new f(400,"invalid_date");return a}function B(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>j)throw new f(400,"invalid_cap");return e}var U=e=>e===null||typeof e=="string";function W(e){return k(e)&&typeof e.external_ref=="string"&&U(e.workspace_id)&&U(e.embed_app_id)&&typeof e.enabled=="boolean"}function K(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let a=x(e.fetch,"createCrmPartnerClient"),d=e.timeoutMs??15e3,g=`${R(e.crmBaseUrl)}/api/partner/v1/workspaces`,y=[e.partnerKey];function c(s){if(typeof s!="string"||!S.test(s))throw new f(400,"invalid_external_ref");return s}async function u(s,n,i){let t=await A(a,d,`${g}/${n}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!t.ok)throw new f(0,t.kind);if(t.status<200||t.status>=300)throw new f(t.status,E(t.json,t.status,y));return{status:t.status,json:t.json}}let m=s=>new f(s,"bad_response");function C(s){if(typeof s!="string"||!I.test(s))throw new f(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,n){let i=c(s),{aiMonthlyCapCredits:t,...r}=n,o=B(t),p=o===void 0?r:{...r,ai_monthly_cap_credits:o},{status:h,json:P}=await u("PUT",i,p);if(!W(P))throw m(h);let l=P;if(l.created===!0){let _=l.embed_app_secret;if(typeof _!="string"||!_)throw m(h);return{...w(l),created:!0,embedAppSecret:_}}if(l.created===!1)return{...w(l),created:!1};throw m(h)},async getWorkspace(s){let n=c(s);try{let{status:i,json:t}=await u("GET",n);if(!W(t)||typeof t.state!="string")throw m(i);let r=t.ai;return{...w(t),state:t.state,ai:k(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(i){if(i instanceof f&&i.status===404)return null;throw i}},async updateWorkspace(s,n){let i=c(s),t={};n.enabled!==void 0&&(t.enabled=n.enabled),n.name!==void 0&&(t.name=n.name);let r=B(n.aiMonthlyCapCredits);r!==void 0&&(t.ai_monthly_cap_credits=r);let{status:o,json:p}=await u("PATCH",i,t);if(!W(p))throw m(o);return w(p)},async getWorkspaceUsage(s,n){let i=c(s),t=new URLSearchParams({from:T(n.from),to:T(n.to)});try{let{status:r,json:o}=await u("GET",`${i}/usage?${t.toString()}`);if(!k(o)||!k(o.totals)||!k(o.cap)||!Array.isArray(o.by_operation))throw m(r);return o}catch(r){if(r instanceof f&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let n=c(s),{status:i,json:t}=await u("POST",`${n}/rotate-secret`),r=t;if(!k(t)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw m(i);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,n,i){let t=c(s),r=C(n),{status:o,json:p}=await u("PUT",`${t}/contacts/${encodeURIComponent(r)}`,i);if(!k(p)||!k(p.contact)||typeof p.created!="boolean"||typeof p.consent_applied!="boolean")throw m(o);return p},async eraseContact(s,n){let i=c(s),t=C(n);try{let{status:r,json:o}=await u("DELETE",`${i}/contacts/${encodeURIComponent(t)}`);if(!k(o)||o.erased!==!0||typeof o.contact_id!="string")throw m(r);return o}catch(r){if(r instanceof f&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,n){let i=c(s),t=typeof n?.phone=="string"?n.phone.trim():void 0,r=typeof n?.email=="string"?n.email.trim():void 0,o=t!==void 0&&/\d/.test(t),p=r!==void 0&&r.includes("@");if(n?.phone!==void 0&&!o||n?.email!==void 0&&!p||!o&&!p)throw new f(400,"invalid_identity");n.ref!==void 0&&C(n.ref);let h={};o&&(h.phone=t),p&&(h.email=r),n.ref!==void 0&&(h.ref=n.ref);try{let{status:P,json:l}=await u("POST",`${i}/contacts/erase-by-identity`,h);if(!k(l)||typeof l.erased!="number"||!Array.isArray(l.contact_ids)||typeof l.skipped_linked_elsewhere!="number")throw m(P);return l}catch(P){if(P instanceof f&&P.status===404)return null;throw P}},async listContactChanges(s,n={}){let i=c(s),{since:t,cursor:r,limit:o}=n;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>$))throw new f(400,"invalid_limit");let p=new URLSearchParams;t!==void 0&&p.set("since",t),r!==void 0&&p.set("cursor",r),o!==void 0&&p.set("limit",String(o));let h=p.toString(),{status:P,json:l}=await u("GET",`${i}/contacts/changes${h?`?${h}`:""}`);if(!k(l)||!Array.isArray(l.items)||!(l.next_cursor===null||typeof l.next_cursor=="string"))throw m(P);return l}}}0&&(module.exports={AI_MONTHLY_CAP_MAX_CREDITS,CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,createCrmPartnerClient});
|
|
1
|
+
"use strict";var I=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var z=Object.getOwnPropertyNames;var K=Object.prototype.hasOwnProperty;var X=(e,n)=>{for(var c in n)I(e,c,{get:n[c],enumerable:!0})},Z=(e,n,c,f)=>{if(n&&typeof n=="object"||typeof n=="function")for(let p of z(n))!K.call(e,p)&&p!==c&&I(e,p,{get:()=>n[p],enumerable:!(f=V(n,p))||f.enumerable});return e};var J=e=>Z(I({},"__esModule",{value:!0}),e);var ce={};X(ce,{AI_MONTHLY_CAP_MAX_CREDITS:()=>H,CONTACT_CHANGES_MAX_LIMIT:()=>G,CONTACT_REF_PATTERN:()=>T,CrmPartnerError:()=>g,EXTERNAL_REF_PATTERN:()=>F,PARTNER_MESSAGE_CHANGES_MAX_LIMIT:()=>q,PartnerWebhookVerificationError:()=>_,createCrmPartnerClient:()=>ie,verifyPartnerWebhook:()=>j});module.exports=J(ce);function B(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function M(e,n){let c=e??globalThis.fetch;if(typeof c!="function")throw new Error(`${n}: no fetch implementation available. Pass \`fetch\` explicitly.`);return c}async function $(e,n,c,f){let p=new AbortController,h=!1,u=setTimeout(()=>{h=!0,p.abort()},n);try{let m={Accept:"application/json",...f.headers},l=f.body!==void 0;l&&(m["Content-Type"]="application/json");let R=await e(c,{method:f.method,headers:m,body:l?JSON.stringify(f.body):void 0,signal:p.signal}),s=await R.json().catch(()=>null);return h?{ok:!1,kind:"timeout"}:{ok:!0,status:R.status,json:s}}catch{return{ok:!1,kind:h?"timeout":"network"}}finally{clearTimeout(u)}}var Q=/^[A-Za-z0-9_.:-]{1,60}$/;function v(e,n,c){let f=`HTTP_${n}`,p=h=>typeof h!="string"||!Q.test(h)||c.some(u=>u&&h.includes(u))?null:h;if(e&&typeof e=="object"){let h=e,u=h.error;return p(h.code)??p(u)??(u&&typeof u=="object"?p(u.code):null)??f}return f}var y=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var W=require("crypto"),_=class e extends Error{constructor(n){super(`Partner webhook verification failed (${n})`),this.name="PartnerWebhookVerificationError",this.reason=n,Object.setPrototypeOf(this,e.prototype)}},Y=300,ee=/^[0-9a-fA-F]{64}$/,te=/^[0-9]{1,15}$/;function N(e,n){if(typeof e.get=="function")return e.get(n)||void 0;let c=e;for(let f of Object.keys(c)){if(f.toLowerCase()!==n)continue;let p=c[f],h=Array.isArray(p)?p[0]:p;if(typeof h=="string"&&h!=="")return h}}var C=e=>typeof e=="string",D=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function re(e){let n;try{n=JSON.parse(e)}catch{throw new _("bad_payload")}if(!D(n)||n.event!=="partner_message.sent")throw new _("bad_payload");let{sender:c}=n;if(!C(n.delivery_id)||!C(n.external_ref)||!C(n.thread_ref)||!C(n.conversation_id)||!C(n.message_id)||!C(n.body)||!C(n.sent_at)||!D(c)||!C(c.name)||!(c.user_ref===null||C(c.user_ref)))throw new _("bad_payload");return{event:"partner_message.sent",deliveryId:n.delivery_id,externalRef:n.external_ref,threadRef:n.thread_ref,conversationId:n.conversation_id,messageId:n.message_id,body:n.body,sentAt:n.sent_at,sender:{userRef:c.user_ref,name:c.name}}}function j(e){if(typeof e.secret!="string"||e.secret==="")throw new TypeError("verifyPartnerWebhook: secret must be a non-empty string");if(typeof e.rawBody!="string")throw new TypeError("verifyPartnerWebhook: rawBody must be a string (the body exactly as received)");if(e.toleranceSeconds!==void 0&&!(Number.isFinite(e.toleranceSeconds)&&e.toleranceSeconds>=0))throw new TypeError("verifyPartnerWebhook: toleranceSeconds must be a finite number of at least 0");let n=N(e.headers,"x-crm-timestamp"),c=N(e.headers,"x-crm-signature");if(n===void 0||c===void 0)throw new _("missing_headers");let f=e.toleranceSeconds??Y,p=(e.now??Date.now)()/1e3;if(!te.test(n)||!Number.isFinite(p)||Math.abs(p-Number(n))>f)throw new _("stale_timestamp");if(!ee.test(c))throw new _("bad_signature");let h=(0,W.createHmac)("sha256",e.secret).update(`${n}.${e.rawBody}`).digest();if(!(0,W.timingSafeEqual)(h,Buffer.from(c,"hex")))throw new _("bad_signature");return re(e.rawBody)}var g=class e extends Error{constructor(n,c){super(n===0?`CRM partner API unreachable (${c})`:`CRM partner API ${n} ${c}`),this.name="CrmPartnerError",this.status=n,this.code=c,Object.setPrototypeOf(this,e.prototype)}},F=/^[A-Za-z0-9_-]{1,64}$/,T=/^[A-Za-z0-9._:-]{1,200}$/,G=200,q=500,H=1e8,E=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled,aiMonthlyCapCredits:typeof e.ai_monthly_cap_credits=="number"?e.ai_monthly_cap_credits:null,partnerChannelEnabled:e.partner_channel_enabled===!0,webhookUrl:typeof e.webhook_url=="string"?e.webhook_url:null});function se(e){if(e instanceof Date){if(Number.isNaN(e.getTime()))throw new g(400,"invalid_date");return e.toISOString()}if(typeof e!="string")throw new g(400,"invalid_date");return e}function ae(e){return y(e)&&typeof e.delivery_id=="string"&&typeof e.external_ref=="string"&&typeof e.thread_ref=="string"&&typeof e.conversation_id=="string"&&typeof e.message_id=="string"&&typeof e.body=="string"&&typeof e.sent_at=="string"&&y(e.sender)&&U(e.sender.user_ref)&&typeof e.sender.name=="string"&&(e.delivery_status==="pending"||e.delivery_status==="delivered"||e.delivery_status==="failed")}var oe=/^\d{4}-\d{2}-\d{2}$/;function O(e){let n=e instanceof Date&&!Number.isNaN(e.getTime())?e.toISOString().slice(0,10):e;if(typeof n!="string"||!oe.test(n)||Number.isNaN(Date.parse(`${n}T00:00:00Z`))||new Date(`${n}T00:00:00Z`).toISOString().slice(0,10)!==n)throw new g(400,"invalid_date");return n}function L(e){if(e==null)return e;if(typeof e!="number"||!Number.isInteger(e)||e<0||e>H)throw new g(400,"invalid_cap");return e}var U=e=>e===null||typeof e=="string";function A(e){return y(e)&&typeof e.external_ref=="string"&&U(e.workspace_id)&&U(e.embed_app_id)&&typeof e.enabled=="boolean"}function ie(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let n=M(e.fetch,"createCrmPartnerClient"),c=e.timeoutMs??15e3,f=`${B(e.crmBaseUrl)}/api/partner/v1`,p=`${f}/workspaces`,h=[e.partnerKey];function u(s){if(typeof s!="string"||!F.test(s))throw new g(400,"invalid_external_ref");return s}async function m(s,t,i,a=p){let r=await $(n,c,`${a}/${t}`,{method:s,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!r.ok)throw new g(0,r.kind);if(r.status<200||r.status>=300)throw new g(r.status,v(r.json,r.status,h));return{status:r.status,json:r.json}}let l=s=>new g(s,"bad_response");function R(s){if(typeof s!="string"||!T.test(s))throw new g(400,"invalid_contact_ref");return s}return{async upsertWorkspace(s,t){let i=u(s),{aiMonthlyCapCredits:a,partnerChannelEnabled:r,webhookUrl:o,...d}=t,w=L(a),b={...d};w!==void 0&&(b.ai_monthly_cap_credits=w),r!==void 0&&(b.partner_channel_enabled=r),o!==void 0&&(b.webhook_url=o);let{status:P,json:x}=await m("PUT",i,b);if(!A(x))throw l(P);let k=x;if(k.created===!0){let S=k.embed_app_secret;if(typeof S!="string"||!S)throw l(P);return{...E(k),created:!0,embedAppSecret:S}}if(k.created===!1)return{...E(k),created:!1};throw l(P)},async getWorkspace(s){let t=u(s);try{let{status:i,json:a}=await m("GET",t);if(!A(a)||typeof a.state!="string")throw l(i);let r=a.ai;return{...E(a),state:a.state,ai:y(r)&&typeof r.period=="string"&&typeof r.used_credits=="number"?{period:r.period,usedCredits:r.used_credits}:null}}catch(i){if(i instanceof g&&i.status===404)return null;throw i}},async updateWorkspace(s,t){let i=u(s),a={};t.enabled!==void 0&&(a.enabled=t.enabled),t.name!==void 0&&(a.name=t.name);let r=L(t.aiMonthlyCapCredits);r!==void 0&&(a.ai_monthly_cap_credits=r),t.partnerChannelEnabled!==void 0&&(a.partner_channel_enabled=t.partnerChannelEnabled),t.webhookUrl!==void 0&&(a.webhook_url=t.webhookUrl);let{status:o,json:d}=await m("PATCH",i,a);if(!A(d))throw l(o);return E(d)},async getWorkspaceUsage(s,t){let i=u(s),a=new URLSearchParams({from:O(t.from),to:O(t.to)});try{let{status:r,json:o}=await m("GET",`${i}/usage?${a.toString()}`);if(!y(o)||!y(o.totals)||!y(o.cap)||!Array.isArray(o.by_operation))throw l(r);return o}catch(r){if(r instanceof g&&r.status===404)return null;throw r}},async rotateWorkspaceSecret(s){let t=u(s),{status:i,json:a}=await m("POST",`${t}/rotate-secret`),r=a;if(!y(a)||typeof r?.embed_app_id!="string"||typeof r.embed_app_secret!="string"||!r.embed_app_secret)throw l(i);return{embedAppId:r.embed_app_id,embedAppSecret:r.embed_app_secret}},async upsertContact(s,t,i){let a=u(s),r=R(t),{status:o,json:d}=await m("PUT",`${a}/contacts/${encodeURIComponent(r)}`,i);if(!y(d)||!y(d.contact)||typeof d.created!="boolean"||typeof d.consent_applied!="boolean")throw l(o);return d},async eraseContact(s,t){let i=u(s),a=R(t);try{let{status:r,json:o}=await m("DELETE",`${i}/contacts/${encodeURIComponent(a)}`);if(!y(o)||o.erased!==!0||typeof o.contact_id!="string")throw l(r);return o}catch(r){if(r instanceof g&&r.status===404)return null;throw r}},async eraseContactsByIdentity(s,t){let i=u(s),a=typeof t?.phone=="string"?t.phone.trim():void 0,r=typeof t?.email=="string"?t.email.trim():void 0,o=a!==void 0&&/\d/.test(a),d=r!==void 0&&r.includes("@");if(t?.phone!==void 0&&!o||t?.email!==void 0&&!d||!o&&!d)throw new g(400,"invalid_identity");t.ref!==void 0&&R(t.ref);let w={};o&&(w.phone=a),d&&(w.email=r),t.ref!==void 0&&(w.ref=t.ref);try{let{status:b,json:P}=await m("POST",`${i}/contacts/erase-by-identity`,w);if(!y(P)||typeof P.erased!="number"||!Array.isArray(P.contact_ids)||typeof P.skipped_linked_elsewhere!="number")throw l(b);return P}catch(b){if(b instanceof g&&b.status===404)return null;throw b}},async listContactChanges(s,t={}){let i=u(s),{since:a,cursor:r,limit:o}=t;if(o!==void 0&&(!Number.isInteger(o)||o<1||o>G))throw new g(400,"invalid_limit");let d=new URLSearchParams;a!==void 0&&d.set("since",a),r!==void 0&&d.set("cursor",r),o!==void 0&&d.set("limit",String(o));let w=d.toString(),{status:b,json:P}=await m("GET",`${i}/contacts/changes${w?`?${w}`:""}`);if(!y(P)||!Array.isArray(P.items)||!(P.next_cursor===null||typeof P.next_cursor=="string"))throw l(b);return P},async sendPartnerMessage(s,t){let i=u(s),a={contact_ref:R(t.contactRef),thread_ref:t.threadRef,message_ref:t.messageRef,body:t.body,sent_at:se(t.sentAt)};t.title!==void 0&&(a.title=t.title),t.teamRef!==void 0&&(a.team_ref=t.teamRef);let{status:r,json:o}=await m("POST",`${i}/messages`,a);if(!y(o)||typeof o.conversation_id!="string"||typeof o.message_id!="string"||typeof o.created!="boolean")throw l(r);let d=o;return{conversationId:d.conversation_id,messageId:d.message_id,created:d.created}},async deletePartnerConversation(s,t){let i=u(s);if(typeof t!="string"||!T.test(t)||t==="."||t==="..")throw new g(400,"invalid_thread_ref");let{status:a,json:r}=await m("DELETE",`${i}/conversations/${encodeURIComponent(t)}`);if(!y(r)||typeof r.deleted!="boolean")throw l(a);return{deleted:r.deleted}},async listPartnerMessageChanges(s,t={}){let i=u(s),{cursor:a,limit:r}=t;if(r!==void 0&&(!Number.isInteger(r)||r<1||r>q))throw new g(400,"invalid_limit");let o=new URLSearchParams;a!==void 0&&o.set("cursor",a),r!==void 0&&o.set("limit",String(r));let d=o.toString(),{status:w,json:b}=await m("GET",`${i}/messages/changes${d?`?${d}`:""}`);if(!y(b)||!Array.isArray(b.items)||!(b.next_cursor===null||typeof b.next_cursor=="string"))throw l(w);let P=b;return{items:P.items.map(k=>{if(!ae(k))throw l(w);return{deliveryId:k.delivery_id,externalRef:k.external_ref,threadRef:k.thread_ref,conversationId:k.conversation_id,messageId:k.message_id,body:k.body,sentAt:k.sent_at,sender:{userRef:k.sender.user_ref,name:k.sender.name},deliveryStatus:k.delivery_status}}),nextCursor:P.next_cursor}},async setWebhook(s){let t={url:s.url},{status:i,json:a}=await m("PUT","webhook",t,f);if(!y(a)||typeof a.url!="string")throw l(i);if(i===201){let r=a.secret;if(typeof r!="string"||!r)throw l(i);return{url:a.url,secret:r}}return{url:a.url}},async getWebhook(){try{let{status:s,json:t}=await m("GET","webhook",void 0,f);if(!y(t)||typeof t.url!="string"||t.has_secret!==!0)throw l(s);return{url:t.url,hasSecret:!0}}catch(s){if(s instanceof g&&s.status===404)return null;throw s}},async rotateWebhookSecret(){let{status:s,json:t}=await m("POST","webhook/rotate-secret",void 0,f),i=y(t)?t.secret:void 0;if(typeof i!="string"||!i)throw l(s);return{secret:i}},async deleteWebhook(){await m("DELETE","webhook",void 0,f)}}}0&&(module.exports={AI_MONTHLY_CAP_MAX_CREDITS,CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,PARTNER_MESSAGE_CHANGES_MAX_LIMIT,PartnerWebhookVerificationError,createCrmPartnerClient,verifyPartnerWebhook});
|
|
2
2
|
//# sourceMappingURL=partner.cjs.map
|
package/dist/partner.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/partner.ts","../src/server-http.ts"],"sourcesContent":["/**\n * CRM Partner SDK (server side ONLY).\n *\n * A product that embeds the CRM (a \"partner\") provisions one CRM workspace per\n * customer of its own, keyed by the customer's id in the product (`externalRef`).\n * The call authenticates with ONE platform key (`ptk_...`) that can create and\n * manage workspaces for every customer of the partner.\n *\n * **Never run this in a browser, a mobile app or any client bundle.** The partner\n * key is a platform-wide secret and the responses carry per-workspace embed\n * secrets. Keep both in server-side configuration and never log them.\n *\n * ```ts\n * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';\n *\n * const partner = createCrmPartnerClient({\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * partnerKey: process.env.CRM_PARTNER_KEY!,\n * });\n * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });\n * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once\n * ```\n *\n * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a\n * network failure or timeout), `code` is the CRM's short error code (or\n * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /\n * `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).\n * The message never contains the key, a secret or a response body.\n *\n * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a\n * provisioned workspace as your product, with the same partner key. A disabled\n * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still\n * erases and lists.\n *\n * AI for the workspace is metered in credits (1 credit = US$0.001). `aiMonthlyCapCredits` is\n * the monthly cap you set per workspace: `null` = no cap, `0` = AI off, N = N credits per UTC\n * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use\n * over a date range.\n *\n * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is\n * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends\n * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.\n * 500 and status 0 are also safe to repeat.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_TIMEOUT_MS,\n errorCodeFrom,\n isRecord,\n normalizeBase,\n resolveFetch,\n sendJson,\n type FetchLike,\n} from './server-http';\nimport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerWorkspaceCreated,\n PartnerWorkspaceDetail as WirePartnerWorkspaceDetail,\n PartnerWorkspaceExisting,\n PartnerWorkspacePatchBody as WirePartnerWorkspacePatchBody,\n PartnerWorkspaceSecret,\n PartnerWorkspaceStatus,\n PartnerWorkspaceUpsertBody as WirePartnerWorkspaceUpsertBody,\n PartnerWorkspaceUsage,\n} from './generated/crm-contracts';\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** A failed partner API call. The message never includes the key, secrets or response bodies. */\nexport class CrmPartnerError extends Error {\n /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */\n readonly status: number;\n /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */\n readonly code: string;\n\n constructor(status: number, code: string) {\n super(status === 0 ? `CRM partner API unreachable (${code})` : `CRM partner API ${status} ${code}`);\n this.name = 'CrmPartnerError';\n this.status = status;\n this.code = code;\n Object.setPrototypeOf(this, CrmPartnerError.prototype);\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Same pattern the CRM enforces on `externalRef`. */\nexport const EXTERNAL_REF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Same pattern the CRM enforces on a `contactRef`. */\nexport const CONTACT_REF_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;\nexport const CONTACT_CHANGES_MAX_LIMIT = 200;\n\nexport interface CrmPartnerClientOptions {\n /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */\n crmBaseUrl: string;\n /** Partner key (`ptk_...`). Server-side secret. */\n partnerKey: string;\n /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Per-request timeout in ms. Default 15000. */\n timeoutMs?: number;\n}\n\n/** Upper bound the CRM accepts for `aiMonthlyCapCredits` (100 million credits). */\nexport const AI_MONTHLY_CAP_MAX_CREDITS = 100_000_000;\n\n/** Fields every workspace response carries. */\nexport interface PartnerWorkspace {\n externalRef: string;\n /** Null until provisioning has created the workspace. */\n workspaceId: string | null;\n /** Null until provisioning has created the embed app. */\n embedAppId: string | null;\n enabled: boolean;\n /**\n * Monthly AI cap in credits: `null` = no cap (also what an older CRM that does not report it\n * returns), `0` = AI off, N = N credits per UTC calendar month.\n */\n aiMonthlyCapCredits: number | null;\n}\n\n/** Body of {@link CrmPartnerClient.upsertWorkspace}. */\nexport type PartnerWorkspaceUpsertBody = Omit<WirePartnerWorkspaceUpsertBody, 'ai_monthly_cap_credits'> & {\n /**\n * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).\n * Omit on create for the default of 5000; omit on a later call to leave it unchanged.\n */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */\nexport type PartnerWorkspacePatchBody = Omit<WirePartnerWorkspacePatchBody, 'ai_monthly_cap_credits'> & {\n /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Query of {@link CrmPartnerClient.getWorkspaceUsage}: UTC calendar dates, `to` inclusive. */\nexport interface PartnerUsageRange {\n /** `YYYY-MM-DD` (UTC), or a `Date` whose UTC date is used. */\n from: string | Date;\n /** `YYYY-MM-DD` (UTC) or a `Date`; the whole day is included. At most 12 months after `from`. */\n to: string | Date;\n}\n\n/**\n * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)\n * is the one call that carries `embedAppSecret`, shown once: store it. A repeat\n * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`\n * if it was lost.\n */\nexport type PartnerWorkspaceUpsertResult =\n | (PartnerWorkspace & { created: true; embedAppSecret: string })\n | (PartnerWorkspace & { created: false; embedAppSecret?: undefined });\n\n/** Result of {@link CrmPartnerClient.getWorkspace}. */\nexport interface PartnerWorkspaceDetail extends PartnerWorkspace {\n /** Provisioning progress; `active` once the workspace is ready for sessions. */\n state: WirePartnerWorkspaceDetail['state'];\n /**\n * AI credits used in the current UTC month (`period` is `YYYY-MM`); null until the workspace\n * exists, or when talking to a CRM that does not report it.\n */\n ai: { period: string; usedCredits: number } | null;\n}\n\n/** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */\nexport interface PartnerRotatedSecret {\n embedAppId: string;\n embedAppSecret: string;\n}\n\nexport interface CrmPartnerClient {\n /**\n * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional\n * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that\n * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.\n * `aiMonthlyCapCredits` sets the monthly AI cap (see {@link PartnerWorkspaceUpsertBody}).\n */\n upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;\n /** Provisioning status, or `null` when the CRM does not know this ref (404). */\n getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;\n /** Enable/disable the embed app, rename the workspace or set its monthly AI cap. At least one field is required. */\n updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;\n /**\n * AI usage of the workspace from `from` to `to` (UTC dates, `to` inclusive, at most 12 months):\n * totals, then the same figures by operation, model and day, plus the current month's cap and\n * the embedded assistant's tokens (which are recorded but not capped). Returned as the CRM\n * sends it (snake_case). `cost_usd` is the provider cost; credits are what the cap counts.\n * Resolves `null` for a ref the CRM does not know or that has no workspace yet (404).\n */\n getWorkspaceUsage(externalRef: string, range: PartnerUsageRange): Promise<PartnerWorkspaceUsage | null>;\n /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */\n rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;\n /**\n * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the\n * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`\n * only applies when its `recorded_at` is newer than the stored one and the parent has\n * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file\n * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the\n * workspace is disabled and 404 for an unknown workspace.\n */\n upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;\n /**\n * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.\n * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already\n * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it\n * also resolves `null`; use `getWorkspace` to tell them apart.\n */\n eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;\n /**\n * PDPA erasure of the contacts that match a person's phone (E.164) or email (case-insensitive)\n * and that your product never linked by ref, such as a parent who wrote first on WhatsApp.\n * Send `ref` (the erased person's own `contactRef`) so a contact linked only to that ref is\n * erased too. A matched contact with any other ref (another person of yours, or another\n * product) is left alone and counted in `skipped_linked_elsewhere`, so a shared family number\n * survives. At least one of `phone` or `email` is required (a client-side 400\n * `invalid_identity` otherwise). Works while the workspace is disabled. No match resolves\n * `erased: 0`. Resolves `null` for an unknown workspace (404).\n */\n eraseContactsByIdentity(externalRef: string, identity: PartnerContactEraseByIdentityBody): Promise<PartnerContactEraseByIdentityResult | null>;\n /**\n * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`\n * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1\n * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.\n */\n listContactChanges(externalRef: string, query?: { since?: string; cursor?: string; limit?: number }): Promise<ContactChanges>;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\nconst fromStatus = (w: PartnerWorkspaceStatus): PartnerWorkspace => ({\n externalRef: w.external_ref,\n workspaceId: w.workspace_id,\n embedAppId: w.embed_app_id,\n enabled: w.enabled,\n // Absent on a CRM from before the AI cap: reported as no cap.\n aiMonthlyCapCredits: typeof w.ai_monthly_cap_credits === 'number' ? w.ai_monthly_cap_credits : null,\n});\n\nconst USAGE_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** `YYYY-MM-DD` as given, or the UTC date of a `Date`; anything else is a 400 `invalid_date`. */\nfunction usageDate(value: string | Date): string {\n const text = value instanceof Date && !Number.isNaN(value.getTime()) ? value.toISOString().slice(0, 10) : value;\n if (typeof text !== 'string' || !USAGE_DATE.test(text)\n || Number.isNaN(Date.parse(`${text}T00:00:00Z`))\n || new Date(`${text}T00:00:00Z`).toISOString().slice(0, 10) !== text) {\n throw new CrmPartnerError(400, 'invalid_date');\n }\n return text;\n}\n\n/** Throws a 400 `invalid_cap` for anything the CRM would refuse, so a typo never leaves the process. */\nfunction checkCap(cap: number | null | undefined): number | null | undefined {\n if (cap === undefined || cap === null) return cap;\n if (typeof cap !== 'number' || !Number.isInteger(cap) || cap < 0 || cap > AI_MONTHLY_CAP_MAX_CREDITS) {\n throw new CrmPartnerError(400, 'invalid_cap');\n }\n return cap;\n}\n\nconst isNullableString = (v: unknown): v is string | null => v === null || typeof v === 'string';\n\nfunction isStatus(v: unknown): v is PartnerWorkspaceStatus {\n return isRecord(v)\n && typeof v.external_ref === 'string'\n && isNullableString(v.workspace_id)\n && isNullableString(v.embed_app_id)\n && typeof v.enabled === 'boolean';\n}\n\nexport function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient {\n if (!opts.crmBaseUrl) throw new Error('createCrmPartnerClient: `crmBaseUrl` is required.');\n if (!opts.partnerKey) throw new Error('createCrmPartnerClient: `partnerKey` is required.');\n const fetchImpl = resolveFetch(opts.fetch, 'createCrmPartnerClient');\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const base = `${normalizeBase(opts.crmBaseUrl)}/api/partner/v1/workspaces`;\n const redact = [opts.partnerKey];\n\n function checkRef(externalRef: string): string {\n if (typeof externalRef !== 'string' || !EXTERNAL_REF_PATTERN.test(externalRef)) {\n throw new CrmPartnerError(400, 'invalid_external_ref');\n }\n return externalRef;\n }\n\n async function call(method: string, path: string, body?: unknown): Promise<{ status: number; json: unknown }> {\n const res = await sendJson(fetchImpl, timeoutMs, `${base}/${path}`, {\n method,\n headers: { Authorization: `Bearer ${opts.partnerKey}` },\n body,\n });\n if (!res.ok) throw new CrmPartnerError(0, res.kind);\n if (res.status < 200 || res.status >= 300) {\n throw new CrmPartnerError(res.status, errorCodeFrom(res.json, res.status, redact));\n }\n return { status: res.status, json: res.json };\n }\n\n const bad = (status: number) => new CrmPartnerError(status, 'bad_response');\n\n function checkContactRef(contactRef: string): string {\n if (typeof contactRef !== 'string' || !CONTACT_REF_PATTERN.test(contactRef)) {\n throw new CrmPartnerError(400, 'invalid_contact_ref');\n }\n return contactRef;\n }\n\n return {\n async upsertWorkspace(externalRef, body) {\n const ref = checkRef(externalRef);\n const { aiMonthlyCapCredits, ...rest } = body;\n const cap = checkCap(aiMonthlyCapCredits);\n const wireBody: WirePartnerWorkspaceUpsertBody = cap === undefined ? rest : { ...rest, ai_monthly_cap_credits: cap };\n const { status, json } = await call('PUT', ref, wireBody);\n if (!isStatus(json)) throw bad(status);\n const wire = json as PartnerWorkspaceCreated | PartnerWorkspaceExisting;\n if (wire.created === true) {\n const secret = (wire as PartnerWorkspaceCreated).embed_app_secret;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { ...fromStatus(wire), created: true, embedAppSecret: secret };\n }\n if (wire.created === false) return { ...fromStatus(wire), created: false };\n throw bad(status);\n },\n\n async getWorkspace(externalRef) {\n const ref = checkRef(externalRef);\n try {\n const { status, json } = await call('GET', ref);\n if (!isStatus(json) || typeof (json as Record<string, unknown>).state !== 'string') throw bad(status);\n const ai = (json as unknown as WirePartnerWorkspaceDetail).ai;\n return {\n ...fromStatus(json),\n state: (json as unknown as WirePartnerWorkspaceDetail).state,\n ai: isRecord(ai) && typeof ai.period === 'string' && typeof ai.used_credits === 'number'\n ? { period: ai.period, usedCredits: ai.used_credits }\n : null,\n };\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async updateWorkspace(externalRef, patch) {\n const ref = checkRef(externalRef);\n const body: WirePartnerWorkspacePatchBody = {};\n if (patch.enabled !== undefined) body.enabled = patch.enabled;\n if (patch.name !== undefined) body.name = patch.name;\n const cap = checkCap(patch.aiMonthlyCapCredits);\n if (cap !== undefined) body.ai_monthly_cap_credits = cap;\n const { status, json } = await call('PATCH', ref, body);\n if (!isStatus(json)) throw bad(status);\n return fromStatus(json);\n },\n\n async getWorkspaceUsage(externalRef, range) {\n const ref = checkRef(externalRef);\n const qs = new URLSearchParams({ from: usageDate(range.from), to: usageDate(range.to) });\n try {\n const { status, json } = await call('GET', `${ref}/usage?${qs.toString()}`);\n if (!isRecord(json) || !isRecord(json.totals) || !isRecord(json.cap) || !Array.isArray(json.by_operation)) throw bad(status);\n return json as unknown as PartnerWorkspaceUsage;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async rotateWorkspaceSecret(externalRef) {\n const ref = checkRef(externalRef);\n const { status, json } = await call('POST', `${ref}/rotate-secret`);\n const w = json as Partial<PartnerWorkspaceSecret> | null;\n if (!isRecord(json) || typeof w?.embed_app_id !== 'string' || typeof w.embed_app_secret !== 'string' || !w.embed_app_secret) {\n throw bad(status);\n }\n return { embedAppId: w.embed_app_id, embedAppSecret: w.embed_app_secret };\n },\n\n async upsertContact(externalRef, contactRef, body) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n const { status, json } = await call('PUT', `${ref}/contacts/${encodeURIComponent(cref)}`, body);\n if (!isRecord(json) || !isRecord(json.contact) || typeof json.created !== 'boolean' || typeof json.consent_applied !== 'boolean') {\n throw bad(status);\n }\n return json as unknown as ContactRefUpsertResult;\n },\n\n async eraseContact(externalRef, contactRef) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n try {\n const { status, json } = await call('DELETE', `${ref}/contacts/${encodeURIComponent(cref)}`);\n if (!isRecord(json) || json.erased !== true || typeof json.contact_id !== 'string') throw bad(status);\n return json as unknown as PartnerContactEraseResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async eraseContactsByIdentity(externalRef, identity) {\n const ref = checkRef(externalRef);\n const phone = typeof identity?.phone === 'string' ? identity.phone.trim() : undefined;\n const email = typeof identity?.email === 'string' ? identity.email.trim() : undefined;\n const hasPhone = phone !== undefined && /\\d/.test(phone);\n const hasEmail = email !== undefined && email.includes('@');\n if ((identity?.phone !== undefined && !hasPhone) || (identity?.email !== undefined && !hasEmail) || (!hasPhone && !hasEmail)) {\n throw new CrmPartnerError(400, 'invalid_identity');\n }\n if (identity.ref !== undefined) checkContactRef(identity.ref);\n const body: PartnerContactEraseByIdentityBody = {};\n if (hasPhone) body.phone = phone;\n if (hasEmail) body.email = email;\n if (identity.ref !== undefined) body.ref = identity.ref;\n try {\n const { status, json } = await call('POST', `${ref}/contacts/erase-by-identity`, body);\n if (\n !isRecord(json)\n || typeof json.erased !== 'number'\n || !Array.isArray(json.contact_ids)\n || typeof json.skipped_linked_elsewhere !== 'number'\n ) {\n throw bad(status);\n }\n return json as unknown as PartnerContactEraseByIdentityResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async listContactChanges(externalRef, query = {}) {\n const ref = checkRef(externalRef);\n const { since, cursor, limit } = query;\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > CONTACT_CHANGES_MAX_LIMIT)) {\n throw new CrmPartnerError(400, 'invalid_limit');\n }\n const qs = new URLSearchParams();\n if (since !== undefined) qs.set('since', since);\n if (cursor !== undefined) qs.set('cursor', cursor);\n if (limit !== undefined) qs.set('limit', String(limit));\n const q = qs.toString();\n const { status, json } = await call('GET', `${ref}/contacts/changes${q ? `?${q}` : ''}`);\n if (!isRecord(json) || !Array.isArray(json.items) || !(json.next_cursor === null || typeof json.next_cursor === 'string')) {\n throw bad(status);\n }\n return json as unknown as ContactChanges;\n },\n };\n}\n\n// Re-exported so partner code can type its inputs without importing the contracts module.\nexport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerWorkspaceUsage,\n};\n","/**\n * Internal HTTP helper for the server-side `partner` entry point. Not part of the\n * public API (no package export points here).\n *\n * It never puts a request header, a request body or a response body into an\n * error: callers get the HTTP status, a short sanitized error code, or a\n * transport failure kind, and nothing else.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\nexport type Transport =\n | { ok: true; status: number; json: unknown }\n | { ok: false; kind: 'timeout' | 'network' };\n\n/** Strip trailing slashes and a trailing `/api`, so callers can pass either form. */\nexport function normalizeBase(crmBaseUrl: string): string {\n return crmBaseUrl.replace(/\\/+$/, '').replace(/\\/api$/, '');\n}\n\nexport function resolveFetch(fetchImpl: FetchLike | undefined, who: string): FetchLike {\n const f = fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error(`${who}: no fetch implementation available. Pass \\`fetch\\` explicitly.`);\n }\n return f;\n}\n\n/**\n * One request with a hard timeout covering headers AND body. Returns the parsed\n * JSON (null when the body is empty or not JSON) or a transport failure kind.\n */\nexport async function sendJson(\n fetchImpl: FetchLike,\n timeoutMs: number,\n url: string,\n init: { method: string; headers: Record<string, string>; body?: unknown },\n): Promise<Transport> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: 'application/json', ...init.headers };\n const hasBody = init.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n const res = await fetchImpl(url, {\n method: init.method,\n headers,\n body: hasBody ? JSON.stringify(init.body) : undefined,\n signal: controller.signal,\n });\n const json: unknown = await res.json().catch(() => null);\n if (timedOut) return { ok: false, kind: 'timeout' };\n return { ok: true, status: res.status, json };\n } catch {\n return { ok: false, kind: timedOut ? 'timeout' : 'network' };\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst SAFE_CODE = /^[A-Za-z0-9_.:-]{1,60}$/;\n\n/**\n * A short machine code from an error body, or `HTTP_<status>`. Accepts\n * `{ error: { code } }`, `{ error: \"code\" }` and `{ code }`. A value that is not\n * a short identifier (a sentence, a long string) or that contains one of the\n * `redact` strings (credentials) is dropped, so a code is always safe to log.\n */\nexport function errorCodeFrom(json: unknown, status: number, redact: readonly string[]): string {\n const fallback = `HTTP_${status}`;\n const pick = (v: unknown): string | null => {\n if (typeof v !== 'string' || !SAFE_CODE.test(v)) return null;\n return redact.some((r) => r && v.includes(r)) ? null : v;\n };\n if (json && typeof json === 'object') {\n const o = json as Record<string, unknown>;\n const err = o.error;\n return (\n pick(o.code)\n ?? pick(err)\n ?? (err && typeof err === 'object' ? pick((err as Record<string, unknown>).code) : null)\n ?? fallback\n );\n }\n return fallback;\n}\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,gCAAAE,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,oBAAAC,EAAA,yBAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAR,GCkBO,SAASS,EAAcC,EAA4B,CACxD,OAAOA,EAAW,QAAQ,OAAQ,EAAE,EAAE,QAAQ,SAAU,EAAE,CAC5D,CAEO,SAASC,EAAaC,EAAkCC,EAAwB,CACrF,IAAMC,EAAIF,GAAa,WAAW,MAClC,GAAI,OAAOE,GAAM,WACf,MAAM,IAAI,MAAM,GAAGD,CAAG,iEAAiE,EAEzF,OAAOC,CACT,CAMA,eAAsBC,EACpBH,EACAI,EACAC,EACAC,EACoB,CACpB,IAAMC,EAAa,IAAI,gBACnBC,EAAW,GACTC,EAAQ,WAAW,IAAM,CAC7BD,EAAW,GACXD,EAAW,MAAM,CACnB,EAAGH,CAAS,EACZ,GAAI,CACF,IAAMM,EAAkC,CAAE,OAAQ,mBAAoB,GAAGJ,EAAK,OAAQ,EAChFK,EAAUL,EAAK,OAAS,OAC1BK,IAASD,EAAQ,cAAc,EAAI,oBACvC,IAAME,EAAM,MAAMZ,EAAUK,EAAK,CAC/B,OAAQC,EAAK,OACb,QAAAI,EACA,KAAMC,EAAU,KA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,EAElB,OAAO0C,CACT,CACF,CACF","names":["partner_exports","__export","AI_MONTHLY_CAP_MAX_CREDITS","CONTACT_CHANGES_MAX_LIMIT","CONTACT_REF_PATTERN","CrmPartnerError","EXTERNAL_REF_PATTERN","createCrmPartnerClient","__toCommonJS","normalizeBase","crmBaseUrl","resolveFetch","fetchImpl","who","f","sendJson","timeoutMs","url","init","controller","timedOut","timer","headers","hasBody","res","json","SAFE_CODE","errorCodeFrom","status","redact","fallback","pick","v","r","o","err","isRecord","CrmPartnerError","_CrmPartnerError","status","code","EXTERNAL_REF_PATTERN","CONTACT_REF_PATTERN","CONTACT_CHANGES_MAX_LIMIT","AI_MONTHLY_CAP_MAX_CREDITS","fromStatus","w","USAGE_DATE","usageDate","value","text","checkCap","cap","isNullableString","v","isStatus","isRecord","createCrmPartnerClient","opts","fetchImpl","resolveFetch","timeoutMs","base","normalizeBase","redact","checkRef","externalRef","call","method","path","body","res","sendJson","errorCodeFrom","bad","checkContactRef","contactRef","ref","aiMonthlyCapCredits","rest","wireBody","json","wire","secret","ai","err","patch","range","qs","cref","identity","phone","email","hasPhone","hasEmail","query","since","cursor","limit","q"]}
|
|
1
|
+
{"version":3,"sources":["../src/partner.ts","../src/server-http.ts","../src/partner-webhook.ts"],"sourcesContent":["/**\n * CRM Partner SDK (server side ONLY).\n *\n * A product that embeds the CRM (a \"partner\") provisions one CRM workspace per\n * customer of its own, keyed by the customer's id in the product (`externalRef`).\n * The call authenticates with ONE platform key (`ptk_...`) that can create and\n * manage workspaces for every customer of the partner.\n *\n * **Never run this in a browser, a mobile app or any client bundle.** The partner\n * key is a platform-wide secret and the responses carry per-workspace embed\n * secrets. Keep both in server-side configuration and never log them.\n *\n * ```ts\n * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';\n *\n * const partner = createCrmPartnerClient({\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * partnerKey: process.env.CRM_PARTNER_KEY!,\n * });\n * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });\n * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once\n * ```\n *\n * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a\n * network failure or timeout), `code` is the CRM's short error code (or\n * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /\n * `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).\n * The message never contains the key, a secret or a response body.\n *\n * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a\n * provisioned workspace as your product, with the same partner key. A disabled\n * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still\n * erases and lists.\n *\n * AI for the workspace is metered in credits (1 credit = US$0.001). `aiMonthlyCapCredits` is\n * the monthly cap you set per workspace: `null` = no cap, `0` = AI off, N = N credits per UTC\n * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use\n * over a date range.\n *\n * Partner message channel (`sendPartnerMessage`, `deletePartnerConversation`,\n * `listPartnerMessageChanges`, and the webhook methods `setWebhook`, `getWebhook`,\n * `rotateWebhookSecret`, `deleteWebhook`): customer messages go in, staff replies come back\n * through the change feed or a signed webhook. Turn the channel on per workspace with\n * `partnerChannelEnabled`. Codes the message endpoint can return, besides the common ones:\n * `NOT_FOUND`, `CONTACT_NOT_FOUND`, `WORKSPACE_DISABLED`, `PARTNER_CHANNEL_DISABLED`,\n * `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `RATE_LIMITED`, `VALIDATION_ERROR`\n * and `SERVICE_BUSY`.\n *\n * Retryable: 409 only for `PROVISIONING_IN_PROGRESS` (another call for the ref is running),\n * 429 (`RATE_LIMITED`) and 503 (`SERVICE_BUSY`). Wait (the CRM sends `Retry-After`: 5 seconds\n * for 503 and 409, the 60-second window for 429) and repeat the same call; provisioning resumes\n * where it stopped. Other 409s (`MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`,\n * `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes and carry no\n * `Retry-After`.\n * 500 and status 0 are also safe to repeat.\n *\n * @packageDocumentation\n */\n\nimport {\n DEFAULT_TIMEOUT_MS,\n errorCodeFrom,\n isRecord,\n normalizeBase,\n resolveFetch,\n sendJson,\n type FetchLike,\n} from './server-http';\nimport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerInboundMessageBody,\n PartnerInboundMessageResult,\n PartnerMessageChange as WirePartnerMessageChange,\n PartnerMessageChanges as WirePartnerMessageChanges,\n PartnerThreadDeleteResult,\n PartnerWebhookCreated,\n PartnerWebhookGet,\n PartnerWebhookPutBody,\n PartnerWebhookRotate,\n PartnerWebhookUpdated,\n PartnerWorkspaceCreated,\n PartnerWorkspaceDetail as WirePartnerWorkspaceDetail,\n PartnerWorkspaceExisting,\n PartnerWorkspacePatchBody as WirePartnerWorkspacePatchBody,\n PartnerWorkspaceSecret,\n PartnerWorkspaceStatus,\n PartnerWorkspaceUpsertBody as WirePartnerWorkspaceUpsertBody,\n PartnerWorkspaceUsage,\n} from './generated/crm-contracts';\n\nexport { PartnerWebhookVerificationError, verifyPartnerWebhook } from './partner-webhook';\nexport type {\n PartnerMessageSentEvent, PartnerWebhookVerificationReason, VerifyPartnerWebhookInput,\n} from './partner-webhook';\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** A failed partner API call. The message never includes the key, secrets or response bodies. */\nexport class CrmPartnerError extends Error {\n /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 `PROVISIONING_IN_PROGRESS`, 429 and 503 are retryable; other 409s (for example `MESSAGE_REF_CONFLICT`, `THREAD_CONTACT_MISMATCH`, `PARTNER_CHANNEL_DISABLED`, `WORKSPACE_DISABLED`) last until something changes, so do not retry them unchanged. */\n readonly status: number;\n /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_thread_ref` / `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`. */\n readonly code: string;\n\n constructor(status: number, code: string) {\n super(status === 0 ? `CRM partner API unreachable (${code})` : `CRM partner API ${status} ${code}`);\n this.name = 'CrmPartnerError';\n this.status = status;\n this.code = code;\n Object.setPrototypeOf(this, CrmPartnerError.prototype);\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** Same pattern the CRM enforces on `externalRef`. */\nexport const EXTERNAL_REF_PATTERN = /^[A-Za-z0-9_-]{1,64}$/;\n\n/** Same pattern the CRM enforces on a `contactRef`. */\nexport const CONTACT_REF_PATTERN = /^[A-Za-z0-9._:-]{1,200}$/;\nexport const CONTACT_CHANGES_MAX_LIMIT = 200;\n/** Upper bound the CRM accepts for the `limit` of {@link CrmPartnerClient.listPartnerMessageChanges}. */\nexport const PARTNER_MESSAGE_CHANGES_MAX_LIMIT = 500;\n\nexport interface CrmPartnerClientOptions {\n /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */\n crmBaseUrl: string;\n /** Partner key (`ptk_...`). Server-side secret. */\n partnerKey: string;\n /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */\n fetch?: FetchLike;\n /** Per-request timeout in ms. Default 15000. */\n timeoutMs?: number;\n}\n\n/** Upper bound the CRM accepts for `aiMonthlyCapCredits` (100 million credits). */\nexport const AI_MONTHLY_CAP_MAX_CREDITS = 100_000_000;\n\n/** Fields every workspace response carries. */\nexport interface PartnerWorkspace {\n externalRef: string;\n /** Null until provisioning has created the workspace. */\n workspaceId: string | null;\n /** Null until provisioning has created the embed app. */\n embedAppId: string | null;\n enabled: boolean;\n /**\n * Monthly AI cap in credits: `null` = no cap (also what an older CRM that does not report it\n * returns), `0` = AI off, N = N credits per UTC calendar month.\n */\n aiMonthlyCapCredits: number | null;\n /** Whether the partner message channel is on for this workspace (false from a CRM that does not report it). */\n partnerChannelEnabled: boolean;\n /** The workspace's own webhook URL; `null` = deliveries go to the URL set with `setWebhook`. */\n webhookUrl: string | null;\n}\n\n/** Body of {@link CrmPartnerClient.upsertWorkspace}. */\nexport type PartnerWorkspaceUpsertBody = Omit<WirePartnerWorkspaceUpsertBody, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {\n /** Turns the partner message channel on or off. Omit to leave it unchanged (off on create). */\n partnerChannelEnabled?: boolean;\n /** Webhook URL for this workspace, used instead of the partner's. `null` clears it; omit to leave it unchanged. */\n webhookUrl?: string | null;\n /**\n * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).\n * Omit on create for the default of 5000; omit on a later call to leave it unchanged.\n */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */\nexport type PartnerWorkspacePatchBody = Omit<WirePartnerWorkspacePatchBody, 'ai_monthly_cap_credits' | 'partner_channel_enabled' | 'webhook_url'> & {\n /** Turns the partner message channel on or off. */\n partnerChannelEnabled?: boolean;\n /** Webhook URL for this workspace, used instead of the partner's. `null` clears it. */\n webhookUrl?: string | null;\n /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */\n aiMonthlyCapCredits?: number | null;\n};\n\n/** Query of {@link CrmPartnerClient.getWorkspaceUsage}: UTC calendar dates, `to` inclusive. */\nexport interface PartnerUsageRange {\n /** `YYYY-MM-DD` (UTC), or a `Date` whose UTC date is used. */\n from: string | Date;\n /** `YYYY-MM-DD` (UTC) or a `Date`; the whole day is included. At most 12 months after `from`. */\n to: string | Date;\n}\n\n/**\n * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)\n * is the one call that carries `embedAppSecret`, shown once: store it. A repeat\n * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`\n * if it was lost.\n */\nexport type PartnerWorkspaceUpsertResult =\n | (PartnerWorkspace & { created: true; embedAppSecret: string })\n | (PartnerWorkspace & { created: false; embedAppSecret?: undefined });\n\n/** Result of {@link CrmPartnerClient.getWorkspace}. */\nexport interface PartnerWorkspaceDetail extends PartnerWorkspace {\n /** Provisioning progress; `active` once the workspace is ready for sessions. */\n state: WirePartnerWorkspaceDetail['state'];\n /**\n * AI credits used in the current UTC month (`period` is `YYYY-MM`); null until the workspace\n * exists, or when talking to a CRM that does not report it.\n */\n ai: { period: string; usedCredits: number } | null;\n}\n\n/** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */\nexport interface PartnerRotatedSecret {\n embedAppId: string;\n embedAppSecret: string;\n}\n\n/** A customer message to hand to the CRM with {@link CrmPartnerClient.sendPartnerMessage}. */\nexport interface PartnerMessageInput {\n /** Your key for the person, as used by contact sync. */\n contactRef: string;\n /** Your id for the conversation. One thread belongs to one contact. */\n threadRef: string;\n /** Your id for the message. Repeating it stores nothing new. */\n messageRef: string;\n /** Plain text, 1 to 10,000 characters, not whitespace only. */\n body: string;\n /** When it was sent: a `Date`, or ISO 8601 with an offset. */\n sentAt: string | Date;\n /** Thread title (1 to 200 characters); set on create, updated when it changes. */\n title?: string;\n /** Your team key; the team is created if new. */\n teamRef?: string;\n}\n\n/** Result of {@link CrmPartnerClient.sendPartnerMessage}. `created` is false for a repeat of a stored `messageRef`. */\nexport interface PartnerMessageResult {\n conversationId: string;\n messageId: string;\n created: boolean;\n}\n\n/** One staff reply owed to you, from {@link CrmPartnerClient.listPartnerMessageChanges}. */\nexport interface PartnerMessageChange {\n deliveryId: string;\n externalRef: string;\n threadRef: string;\n conversationId: string;\n /** Unique per reply: deduplicate on it. */\n messageId: string;\n body: string;\n /** ISO 8601 UTC. */\n sentAt: string;\n sender: {\n /** Your own id for the staff member, or `null` when they have none. */\n userRef: string | null;\n name: string;\n };\n deliveryStatus: 'pending' | 'delivered' | 'failed';\n}\n\n/** One page of {@link CrmPartnerClient.listPartnerMessageChanges}. */\nexport interface PartnerMessageChangesPage {\n items: PartnerMessageChange[];\n nextCursor: string | null;\n}\n\nexport interface CrmPartnerClient {\n /**\n * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional\n * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that\n * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.\n * `aiMonthlyCapCredits` sets the monthly AI cap (see {@link PartnerWorkspaceUpsertBody}).\n */\n upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;\n /** Provisioning status, or `null` when the CRM does not know this ref (404). */\n getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;\n /** Enable/disable the embed app, rename the workspace or set its monthly AI cap. At least one field is required. */\n updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;\n /**\n * AI usage of the workspace from `from` to `to` (UTC dates, `to` inclusive, at most 12 months):\n * totals, then the same figures by operation, model and day, plus the current month's cap and\n * the embedded assistant's tokens (which are recorded but not capped). Returned as the CRM\n * sends it (snake_case). `cost_usd` is the provider cost; credits are what the cap counts.\n * Resolves `null` for a ref the CRM does not know or that has no workspace yet (404).\n */\n getWorkspaceUsage(externalRef: string, range: PartnerUsageRange): Promise<PartnerWorkspaceUsage | null>;\n /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */\n rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;\n /**\n * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the\n * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`\n * only applies when its `recorded_at` is newer than the stored one and the parent has\n * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file\n * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the\n * workspace is disabled and 404 for an unknown workspace.\n */\n upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;\n /**\n * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.\n * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already\n * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it\n * also resolves `null`; use `getWorkspace` to tell them apart.\n */\n eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;\n /**\n * PDPA erasure of the contacts that match a person's phone (E.164) or email (case-insensitive)\n * and that your product never linked by ref, such as a parent who wrote first on WhatsApp.\n * Send `ref` (the erased person's own `contactRef`) so a contact linked only to that ref is\n * erased too. A matched contact with any other ref (another person of yours, or another\n * product) is left alone and counted in `skipped_linked_elsewhere`, so a shared family number\n * survives. At least one of `phone` or `email` is required (a client-side 400\n * `invalid_identity` otherwise). Works while the workspace is disabled. No match resolves\n * `erased: 0`. Resolves `null` for an unknown workspace (404).\n */\n eraseContactsByIdentity(externalRef: string, identity: PartnerContactEraseByIdentityBody): Promise<PartnerContactEraseByIdentityResult | null>;\n /**\n * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`\n * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1\n * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.\n */\n listContactChanges(externalRef: string, query?: { since?: string; cursor?: string; limit?: number }): Promise<ContactChanges>;\n /**\n * Hand a customer message to the CRM. Idempotent on `messageRef`: 201 resolves `created: true`,\n * a repeat (200) resolves `created: false` with the same ids. One `threadRef` belongs to one\n * contact. Rejections surface as {@link CrmPartnerError} with the CRM's code, for example\n * `PARTNER_CHANNEL_DISABLED`, `CONTACT_NOT_FOUND`, `MESSAGE_REF_CONFLICT` (the `messageRef` is already used on\n * another thread; not retryable), `THREAD_CONTACT_MISMATCH`, `WORKSPACE_DISABLED`,\n * `RATE_LIMITED` and `SERVICE_BUSY`.\n */\n sendPartnerMessage(externalRef: string, message: PartnerMessageInput): Promise<PartnerMessageResult>;\n /** Delete the conversation for `threadRef`. `deleted: false` when there is none (already deleted, or never sent). */\n deletePartnerConversation(externalRef: string, threadRef: string): Promise<{ deleted: boolean }>;\n /**\n * One page of staff replies owed to you, oldest first. `limit` is 1 to 500 (default 100).\n *\n * Presenting a `cursor` acknowledges every row before it, so persist a page before calling\n * again with its `nextCursor`. Keep calling until `items` is empty and store the cursor that\n * call returns for the next poll. `nextCursor` is null only when no cursor was sent and there\n * are no rows. Never construct a cursor, and never reuse one across workspaces. A 400\n * `VALIDATION_ERROR` on a stored cursor means drop it and restart with none. Rows are kept 30\n * days. A reply appears a few seconds after it is sent. Delivered rows are included\n * (`deliveryStatus`); deduplicate on `messageId`.\n */\n listPartnerMessageChanges(externalRef: string, query?: { cursor?: string; limit?: number }): Promise<PartnerMessageChangesPage>;\n /**\n * Register (or change) the URL that receives staff replies. The first registration returns the\n * signing `secret`, shown once: store it. Changing the URL returns no secret. The URL must be\n * HTTPS (400 `VALIDATION_ERROR` otherwise).\n */\n setWebhook(input: { url: string }): Promise<{ url: string; secret?: string }>;\n /** The registered webhook, or `null` when none is registered (404). The secret is never returned. */\n getWebhook(): Promise<{ url: string; hasSecret: true } | null>;\n /** Replace the signing secret; the old one stops working at once. Throws a 404 error when no webhook is registered. */\n rotateWebhookSecret(): Promise<{ secret: string }>;\n /** Remove the webhook. Resolves also when none was registered. */\n deleteWebhook(): Promise<void>;\n}\n\n// ─── Implementation ──────────────────────────────────────────────────────────\n\nconst fromStatus = (w: PartnerWorkspaceStatus): PartnerWorkspace => ({\n externalRef: w.external_ref,\n workspaceId: w.workspace_id,\n embedAppId: w.embed_app_id,\n enabled: w.enabled,\n // Absent on a CRM from before the AI cap: reported as no cap.\n aiMonthlyCapCredits: typeof w.ai_monthly_cap_credits === 'number' ? w.ai_monthly_cap_credits : null,\n // Absent on a CRM from before the message channel: reported as off, no URL.\n partnerChannelEnabled: w.partner_channel_enabled === true,\n webhookUrl: typeof w.webhook_url === 'string' ? w.webhook_url : null,\n});\n\n/** Throws a 400 `invalid_date` unless `value` is a valid `Date` or a string; returns the wire string. */\nfunction sentAtWire(value: string | Date): string {\n if (value instanceof Date) {\n if (Number.isNaN(value.getTime())) throw new CrmPartnerError(400, 'invalid_date');\n return value.toISOString();\n }\n if (typeof value !== 'string') throw new CrmPartnerError(400, 'invalid_date');\n return value;\n}\n\nfunction isChange(v: unknown): v is WirePartnerMessageChange {\n return isRecord(v)\n && typeof v.delivery_id === 'string'\n && typeof v.external_ref === 'string'\n && typeof v.thread_ref === 'string'\n && typeof v.conversation_id === 'string'\n && typeof v.message_id === 'string'\n && typeof v.body === 'string'\n && typeof v.sent_at === 'string'\n && isRecord(v.sender)\n && isNullableString(v.sender.user_ref)\n && typeof v.sender.name === 'string'\n && (v.delivery_status === 'pending' || v.delivery_status === 'delivered' || v.delivery_status === 'failed');\n}\n\nconst USAGE_DATE = /^\\d{4}-\\d{2}-\\d{2}$/;\n\n/** `YYYY-MM-DD` as given, or the UTC date of a `Date`; anything else is a 400 `invalid_date`. */\nfunction usageDate(value: string | Date): string {\n const text = value instanceof Date && !Number.isNaN(value.getTime()) ? value.toISOString().slice(0, 10) : value;\n if (typeof text !== 'string' || !USAGE_DATE.test(text)\n || Number.isNaN(Date.parse(`${text}T00:00:00Z`))\n || new Date(`${text}T00:00:00Z`).toISOString().slice(0, 10) !== text) {\n throw new CrmPartnerError(400, 'invalid_date');\n }\n return text;\n}\n\n/** Throws a 400 `invalid_cap` for anything the CRM would refuse, so a typo never leaves the process. */\nfunction checkCap(cap: number | null | undefined): number | null | undefined {\n if (cap === undefined || cap === null) return cap;\n if (typeof cap !== 'number' || !Number.isInteger(cap) || cap < 0 || cap > AI_MONTHLY_CAP_MAX_CREDITS) {\n throw new CrmPartnerError(400, 'invalid_cap');\n }\n return cap;\n}\n\nconst isNullableString = (v: unknown): v is string | null => v === null || typeof v === 'string';\n\nfunction isStatus(v: unknown): v is PartnerWorkspaceStatus {\n return isRecord(v)\n && typeof v.external_ref === 'string'\n && isNullableString(v.workspace_id)\n && isNullableString(v.embed_app_id)\n && typeof v.enabled === 'boolean';\n}\n\nexport function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient {\n if (!opts.crmBaseUrl) throw new Error('createCrmPartnerClient: `crmBaseUrl` is required.');\n if (!opts.partnerKey) throw new Error('createCrmPartnerClient: `partnerKey` is required.');\n const fetchImpl = resolveFetch(opts.fetch, 'createCrmPartnerClient');\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS;\n const root = `${normalizeBase(opts.crmBaseUrl)}/api/partner/v1`;\n const base = `${root}/workspaces`;\n const redact = [opts.partnerKey];\n\n function checkRef(externalRef: string): string {\n if (typeof externalRef !== 'string' || !EXTERNAL_REF_PATTERN.test(externalRef)) {\n throw new CrmPartnerError(400, 'invalid_external_ref');\n }\n return externalRef;\n }\n\n async function call(method: string, path: string, body?: unknown, prefix: string = base): Promise<{ status: number; json: unknown }> {\n const res = await sendJson(fetchImpl, timeoutMs, `${prefix}/${path}`, {\n method,\n headers: { Authorization: `Bearer ${opts.partnerKey}` },\n body,\n });\n if (!res.ok) throw new CrmPartnerError(0, res.kind);\n if (res.status < 200 || res.status >= 300) {\n throw new CrmPartnerError(res.status, errorCodeFrom(res.json, res.status, redact));\n }\n return { status: res.status, json: res.json };\n }\n\n const bad = (status: number) => new CrmPartnerError(status, 'bad_response');\n\n function checkContactRef(contactRef: string): string {\n if (typeof contactRef !== 'string' || !CONTACT_REF_PATTERN.test(contactRef)) {\n throw new CrmPartnerError(400, 'invalid_contact_ref');\n }\n return contactRef;\n }\n\n return {\n async upsertWorkspace(externalRef, body) {\n const ref = checkRef(externalRef);\n const { aiMonthlyCapCredits, partnerChannelEnabled, webhookUrl, ...rest } = body;\n const cap = checkCap(aiMonthlyCapCredits);\n const wireBody: WirePartnerWorkspaceUpsertBody = { ...rest };\n if (cap !== undefined) wireBody.ai_monthly_cap_credits = cap;\n if (partnerChannelEnabled !== undefined) wireBody.partner_channel_enabled = partnerChannelEnabled;\n if (webhookUrl !== undefined) wireBody.webhook_url = webhookUrl;\n const { status, json } = await call('PUT', ref, wireBody);\n if (!isStatus(json)) throw bad(status);\n const wire = json as PartnerWorkspaceCreated | PartnerWorkspaceExisting;\n if (wire.created === true) {\n const secret = (wire as PartnerWorkspaceCreated).embed_app_secret;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { ...fromStatus(wire), created: true, embedAppSecret: secret };\n }\n if (wire.created === false) return { ...fromStatus(wire), created: false };\n throw bad(status);\n },\n\n async getWorkspace(externalRef) {\n const ref = checkRef(externalRef);\n try {\n const { status, json } = await call('GET', ref);\n if (!isStatus(json) || typeof (json as Record<string, unknown>).state !== 'string') throw bad(status);\n const ai = (json as unknown as WirePartnerWorkspaceDetail).ai;\n return {\n ...fromStatus(json),\n state: (json as unknown as WirePartnerWorkspaceDetail).state,\n ai: isRecord(ai) && typeof ai.period === 'string' && typeof ai.used_credits === 'number'\n ? { period: ai.period, usedCredits: ai.used_credits }\n : null,\n };\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async updateWorkspace(externalRef, patch) {\n const ref = checkRef(externalRef);\n const body: WirePartnerWorkspacePatchBody = {};\n if (patch.enabled !== undefined) body.enabled = patch.enabled;\n if (patch.name !== undefined) body.name = patch.name;\n const cap = checkCap(patch.aiMonthlyCapCredits);\n if (cap !== undefined) body.ai_monthly_cap_credits = cap;\n if (patch.partnerChannelEnabled !== undefined) body.partner_channel_enabled = patch.partnerChannelEnabled;\n if (patch.webhookUrl !== undefined) body.webhook_url = patch.webhookUrl;\n const { status, json } = await call('PATCH', ref, body);\n if (!isStatus(json)) throw bad(status);\n return fromStatus(json);\n },\n\n async getWorkspaceUsage(externalRef, range) {\n const ref = checkRef(externalRef);\n const qs = new URLSearchParams({ from: usageDate(range.from), to: usageDate(range.to) });\n try {\n const { status, json } = await call('GET', `${ref}/usage?${qs.toString()}`);\n if (!isRecord(json) || !isRecord(json.totals) || !isRecord(json.cap) || !Array.isArray(json.by_operation)) throw bad(status);\n return json as unknown as PartnerWorkspaceUsage;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async rotateWorkspaceSecret(externalRef) {\n const ref = checkRef(externalRef);\n const { status, json } = await call('POST', `${ref}/rotate-secret`);\n const w = json as Partial<PartnerWorkspaceSecret> | null;\n if (!isRecord(json) || typeof w?.embed_app_id !== 'string' || typeof w.embed_app_secret !== 'string' || !w.embed_app_secret) {\n throw bad(status);\n }\n return { embedAppId: w.embed_app_id, embedAppSecret: w.embed_app_secret };\n },\n\n async upsertContact(externalRef, contactRef, body) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n const { status, json } = await call('PUT', `${ref}/contacts/${encodeURIComponent(cref)}`, body);\n if (!isRecord(json) || !isRecord(json.contact) || typeof json.created !== 'boolean' || typeof json.consent_applied !== 'boolean') {\n throw bad(status);\n }\n return json as unknown as ContactRefUpsertResult;\n },\n\n async eraseContact(externalRef, contactRef) {\n const ref = checkRef(externalRef);\n const cref = checkContactRef(contactRef);\n try {\n const { status, json } = await call('DELETE', `${ref}/contacts/${encodeURIComponent(cref)}`);\n if (!isRecord(json) || json.erased !== true || typeof json.contact_id !== 'string') throw bad(status);\n return json as unknown as PartnerContactEraseResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async eraseContactsByIdentity(externalRef, identity) {\n const ref = checkRef(externalRef);\n const phone = typeof identity?.phone === 'string' ? identity.phone.trim() : undefined;\n const email = typeof identity?.email === 'string' ? identity.email.trim() : undefined;\n const hasPhone = phone !== undefined && /\\d/.test(phone);\n const hasEmail = email !== undefined && email.includes('@');\n if ((identity?.phone !== undefined && !hasPhone) || (identity?.email !== undefined && !hasEmail) || (!hasPhone && !hasEmail)) {\n throw new CrmPartnerError(400, 'invalid_identity');\n }\n if (identity.ref !== undefined) checkContactRef(identity.ref);\n const body: PartnerContactEraseByIdentityBody = {};\n if (hasPhone) body.phone = phone;\n if (hasEmail) body.email = email;\n if (identity.ref !== undefined) body.ref = identity.ref;\n try {\n const { status, json } = await call('POST', `${ref}/contacts/erase-by-identity`, body);\n if (\n !isRecord(json)\n || typeof json.erased !== 'number'\n || !Array.isArray(json.contact_ids)\n || typeof json.skipped_linked_elsewhere !== 'number'\n ) {\n throw bad(status);\n }\n return json as unknown as PartnerContactEraseByIdentityResult;\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async listContactChanges(externalRef, query = {}) {\n const ref = checkRef(externalRef);\n const { since, cursor, limit } = query;\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > CONTACT_CHANGES_MAX_LIMIT)) {\n throw new CrmPartnerError(400, 'invalid_limit');\n }\n const qs = new URLSearchParams();\n if (since !== undefined) qs.set('since', since);\n if (cursor !== undefined) qs.set('cursor', cursor);\n if (limit !== undefined) qs.set('limit', String(limit));\n const q = qs.toString();\n const { status, json } = await call('GET', `${ref}/contacts/changes${q ? `?${q}` : ''}`);\n if (!isRecord(json) || !Array.isArray(json.items) || !(json.next_cursor === null || typeof json.next_cursor === 'string')) {\n throw bad(status);\n }\n return json as unknown as ContactChanges;\n },\n\n async sendPartnerMessage(externalRef, message) {\n const ref = checkRef(externalRef);\n const wireBody: PartnerInboundMessageBody = {\n contact_ref: checkContactRef(message.contactRef),\n thread_ref: message.threadRef,\n message_ref: message.messageRef,\n body: message.body,\n sent_at: sentAtWire(message.sentAt),\n };\n if (message.title !== undefined) wireBody.title = message.title;\n if (message.teamRef !== undefined) wireBody.team_ref = message.teamRef;\n const { status, json } = await call('POST', `${ref}/messages`, wireBody);\n if (!isRecord(json) || typeof json.conversation_id !== 'string' || typeof json.message_id !== 'string' || typeof json.created !== 'boolean') {\n throw bad(status);\n }\n const wire = json as unknown as PartnerInboundMessageResult;\n return { conversationId: wire.conversation_id, messageId: wire.message_id, created: wire.created };\n },\n\n async deletePartnerConversation(externalRef, threadRef) {\n const ref = checkRef(externalRef);\n if (typeof threadRef !== 'string' || !CONTACT_REF_PATTERN.test(threadRef) || threadRef === '.' || threadRef === '..') {\n throw new CrmPartnerError(400, 'invalid_thread_ref');\n }\n const { status, json } = await call('DELETE', `${ref}/conversations/${encodeURIComponent(threadRef)}`);\n if (!isRecord(json) || typeof json.deleted !== 'boolean') throw bad(status);\n return { deleted: (json as unknown as PartnerThreadDeleteResult).deleted };\n },\n\n async listPartnerMessageChanges(externalRef, query = {}) {\n const ref = checkRef(externalRef);\n const { cursor, limit } = query;\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1 || limit > PARTNER_MESSAGE_CHANGES_MAX_LIMIT)) {\n throw new CrmPartnerError(400, 'invalid_limit');\n }\n const qs = new URLSearchParams();\n if (cursor !== undefined) qs.set('cursor', cursor);\n if (limit !== undefined) qs.set('limit', String(limit));\n const q = qs.toString();\n const { status, json } = await call('GET', `${ref}/messages/changes${q ? `?${q}` : ''}`);\n if (!isRecord(json) || !Array.isArray(json.items) || !(json.next_cursor === null || typeof json.next_cursor === 'string')) {\n throw bad(status);\n }\n const page = json as unknown as WirePartnerMessageChanges;\n const items: PartnerMessageChange[] = page.items.map((item: unknown) => {\n if (!isChange(item)) throw bad(status);\n return {\n deliveryId: item.delivery_id,\n externalRef: item.external_ref,\n threadRef: item.thread_ref,\n conversationId: item.conversation_id,\n messageId: item.message_id,\n body: item.body,\n sentAt: item.sent_at,\n sender: { userRef: item.sender.user_ref, name: item.sender.name },\n deliveryStatus: item.delivery_status,\n };\n });\n return { items, nextCursor: page.next_cursor };\n },\n\n async setWebhook(input) {\n const wireBody: PartnerWebhookPutBody = { url: input.url };\n const { status, json } = await call('PUT', 'webhook', wireBody, root);\n if (!isRecord(json) || typeof json.url !== 'string') throw bad(status);\n if (status === 201) {\n const secret = (json as unknown as PartnerWebhookCreated).secret;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { url: json.url, secret };\n }\n return { url: (json as unknown as PartnerWebhookUpdated).url };\n },\n\n async getWebhook() {\n try {\n const { status, json } = await call('GET', 'webhook', undefined, root);\n if (!isRecord(json) || typeof json.url !== 'string' || json.has_secret !== true) throw bad(status);\n return { url: (json as unknown as PartnerWebhookGet).url, hasSecret: true as const };\n } catch (err) {\n if (err instanceof CrmPartnerError && err.status === 404) return null;\n throw err;\n }\n },\n\n async rotateWebhookSecret() {\n const { status, json } = await call('POST', 'webhook/rotate-secret', undefined, root);\n const secret = isRecord(json) ? (json as unknown as Partial<PartnerWebhookRotate>).secret : undefined;\n if (typeof secret !== 'string' || !secret) throw bad(status);\n return { secret };\n },\n\n async deleteWebhook() {\n await call('DELETE', 'webhook', undefined, root);\n },\n };\n}\n\n// Re-exported so partner code can type its inputs without importing the contracts module.\nexport type {\n ContactChanges,\n ContactChangesQuery,\n ContactRefUpsertBody,\n ContactRefUpsertResult,\n PartnerContactEraseByIdentityBody,\n PartnerContactEraseByIdentityResult,\n PartnerContactEraseResult,\n PartnerWorkspaceUsage,\n};\n","/**\n * Internal HTTP helper for the server-side `partner` entry point. Not part of the\n * public API (no package export points here).\n *\n * It never puts a request header, a request body or a response body into an\n * error: callers get the HTTP status, a short sanitized error code, or a\n * transport failure kind, and nothing else.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\nexport type Transport =\n | { ok: true; status: number; json: unknown }\n | { ok: false; kind: 'timeout' | 'network' };\n\n/** Strip trailing slashes and a trailing `/api`, so callers can pass either form. */\nexport function normalizeBase(crmBaseUrl: string): string {\n return crmBaseUrl.replace(/\\/+$/, '').replace(/\\/api$/, '');\n}\n\nexport function resolveFetch(fetchImpl: FetchLike | undefined, who: string): FetchLike {\n const f = fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error(`${who}: no fetch implementation available. Pass \\`fetch\\` explicitly.`);\n }\n return f;\n}\n\n/**\n * One request with a hard timeout covering headers AND body. Returns the parsed\n * JSON (null when the body is empty or not JSON) or a transport failure kind.\n */\nexport async function sendJson(\n fetchImpl: FetchLike,\n timeoutMs: number,\n url: string,\n init: { method: string; headers: Record<string, string>; body?: unknown },\n): Promise<Transport> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: 'application/json', ...init.headers };\n const hasBody = init.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n const res = await fetchImpl(url, {\n method: init.method,\n headers,\n body: hasBody ? JSON.stringify(init.body) : undefined,\n signal: controller.signal,\n });\n const json: unknown = await res.json().catch(() => null);\n if (timedOut) return { ok: false, kind: 'timeout' };\n return { ok: true, status: res.status, json };\n } catch {\n return { ok: false, kind: timedOut ? 'timeout' : 'network' };\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst SAFE_CODE = /^[A-Za-z0-9_.:-]{1,60}$/;\n\n/**\n * A short machine code from an error body, or `HTTP_<status>`. Accepts\n * `{ error: { code } }`, `{ error: \"code\" }` and `{ code }`. A value that is not\n * a short identifier (a sentence, a long string) or that contains one of the\n * `redact` strings (credentials) is dropped, so a code is always safe to log.\n */\nexport function errorCodeFrom(json: unknown, status: number, redact: readonly string[]): string {\n const fallback = `HTTP_${status}`;\n const pick = (v: unknown): string | null => {\n if (typeof v !== 'string' || !SAFE_CODE.test(v)) return null;\n return redact.some((r) => r && v.includes(r)) ? null : v;\n };\n if (json && typeof json === 'object') {\n const o = json as Record<string, unknown>;\n const err = o.error;\n return (\n pick(o.code)\n ?? pick(err)\n ?? (err && typeof err === 'object' ? pick((err as Record<string, unknown>).code) : null)\n ?? fallback\n );\n }\n return fallback;\n}\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n","/**\n * Verifier for the signed webhook the CRM sends for each staff reply on the partner message\n * channel (server side ONLY: it uses `node:crypto`).\n *\n * The CRM sends `POST <url>` with `x-crm-timestamp` (unix seconds) and `x-crm-signature`, the\n * hex HMAC-SHA256 of `<timestamp>.<raw body>` keyed with the secret text from `setWebhook` or\n * `rotateWebhookSecret`. Pass the body exactly as received: a body parsed and serialised again\n * no longer matches the signature.\n */\n\nimport { createHmac, timingSafeEqual } from 'node:crypto';\n\n/** A staff reply, as delivered by the webhook. */\nexport interface PartnerMessageSentEvent {\n event: 'partner_message.sent';\n /** Identifies this delivery. */\n deliveryId: string;\n externalRef: string;\n threadRef: string;\n conversationId: string;\n /** Unique per reply: deduplicate on it. */\n messageId: string;\n body: string;\n /** ISO 8601 UTC. */\n sentAt: string;\n sender: {\n /** Your own id for the staff member, or `null` when they have none. */\n userRef: string | null;\n name: string;\n };\n}\n\nexport type PartnerWebhookVerificationReason = 'missing_headers' | 'stale_timestamp' | 'bad_signature' | 'bad_payload';\n\n/** A delivery that failed verification. The message names the reason and nothing from the request. */\nexport class PartnerWebhookVerificationError extends Error {\n readonly reason: PartnerWebhookVerificationReason;\n\n constructor(reason: PartnerWebhookVerificationReason) {\n super(`Partner webhook verification failed (${reason})`);\n this.name = 'PartnerWebhookVerificationError';\n this.reason = reason;\n Object.setPrototypeOf(this, PartnerWebhookVerificationError.prototype);\n }\n}\n\nexport interface VerifyPartnerWebhookInput {\n /** The request body exactly as received, before any JSON parsing. */\n rawBody: string;\n headers: Headers | Record<string, string | string[] | undefined>;\n /** The signing secret as returned by `setWebhook` / `rotateWebhookSecret`. */\n secret: string;\n /** How far the timestamp may be from now, in either direction. Default 300. */\n toleranceSeconds?: number;\n /** Clock in milliseconds; for tests. Default `Date.now`. */\n now?: () => number;\n}\n\nconst DEFAULT_TOLERANCE_SECONDS = 300;\nconst SIGNATURE_HEX = /^[0-9a-fA-F]{64}$/;\nconst PLAIN_INTEGER = /^[0-9]{1,15}$/;\n\nfunction headerValue(headers: VerifyPartnerWebhookInput['headers'], name: string): string | undefined {\n if (typeof (headers as Headers).get === 'function') return (headers as Headers).get(name) || undefined;\n const record = headers as Record<string, string | string[] | undefined>;\n for (const key of Object.keys(record)) {\n if (key.toLowerCase() !== name) continue;\n const value = record[key];\n const first = Array.isArray(value) ? value[0] : value;\n if (typeof first === 'string' && first !== '') return first;\n }\n return undefined;\n}\n\nconst isString = (value: unknown): value is string => typeof value === 'string';\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value);\n\nfunction parseEvent(rawBody: string): PartnerMessageSentEvent {\n let data: unknown;\n try {\n data = JSON.parse(rawBody);\n } catch {\n throw new PartnerWebhookVerificationError('bad_payload');\n }\n if (!isRecord(data) || data.event !== 'partner_message.sent') throw new PartnerWebhookVerificationError('bad_payload');\n const { sender } = data;\n if (\n !isString(data.delivery_id) || !isString(data.external_ref) || !isString(data.thread_ref)\n || !isString(data.conversation_id) || !isString(data.message_id) || !isString(data.body) || !isString(data.sent_at)\n || !isRecord(sender) || !isString(sender.name) || !(sender.user_ref === null || isString(sender.user_ref))\n ) {\n throw new PartnerWebhookVerificationError('bad_payload');\n }\n return {\n event: 'partner_message.sent',\n deliveryId: data.delivery_id,\n externalRef: data.external_ref,\n threadRef: data.thread_ref,\n conversationId: data.conversation_id,\n messageId: data.message_id,\n body: data.body,\n sentAt: data.sent_at,\n sender: { userRef: sender.user_ref, name: sender.name },\n };\n}\n\n/**\n * Verify a delivery and return the event. Throws {@link PartnerWebhookVerificationError}\n * (answer 401); a present but malformed timestamp counts as `stale_timestamp`, a missing one as `missing_headers`. An empty or\n * non-string `secret`, a non-string `rawBody` or a non-finite or negative `toleranceSeconds`\n * is a caller bug and throws a plain `TypeError`. The body is parsed only after the signature has been verified.\n */\nexport function verifyPartnerWebhook(input: VerifyPartnerWebhookInput): PartnerMessageSentEvent {\n // Caller bugs, not verification failures: never fail open on a bad configuration.\n if (typeof input.secret !== 'string' || input.secret === '') throw new TypeError('verifyPartnerWebhook: secret must be a non-empty string');\n if (typeof input.rawBody !== 'string') throw new TypeError('verifyPartnerWebhook: rawBody must be a string (the body exactly as received)');\n if (input.toleranceSeconds !== undefined && !(Number.isFinite(input.toleranceSeconds) && input.toleranceSeconds >= 0)) {\n throw new TypeError('verifyPartnerWebhook: toleranceSeconds must be a finite number of at least 0');\n }\n\n const timestamp = headerValue(input.headers, 'x-crm-timestamp');\n const signature = headerValue(input.headers, 'x-crm-signature');\n if (timestamp === undefined || signature === undefined) throw new PartnerWebhookVerificationError('missing_headers');\n\n const tolerance = input.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;\n const nowSeconds = (input.now ?? Date.now)() / 1000;\n if (!PLAIN_INTEGER.test(timestamp) || !Number.isFinite(nowSeconds) || Math.abs(nowSeconds - Number(timestamp)) > tolerance) {\n throw new PartnerWebhookVerificationError('stale_timestamp');\n }\n\n if (!SIGNATURE_HEX.test(signature)) throw new PartnerWebhookVerificationError('bad_signature');\n const expected = createHmac('sha256', input.secret).update(`${timestamp}.${input.rawBody}`).digest();\n if (!timingSafeEqual(expected, Buffer.from(signature, 'hex'))) throw new PartnerWebhookVerificationError('bad_signature');\n\n return parseEvent(input.rawBody);\n}\n"],"mappings":"yaAAA,IAAAA,GAAA,GAAAC,EAAAD,GAAA,gCAAAE,EAAA,8BAAAC,EAAA,wBAAAC,EAAA,oBAAAC,EAAA,yBAAAC,EAAA,sCAAAC,EAAA,oCAAAC,EAAA,2BAAAC,GAAA,yBAAAC,IAAA,eAAAC,EAAAX,ICkBO,SAASY,EAAcC,EAA4B,CACxD,OAAOA,EAAW,QAAQ,OAAQ,EAAE,EAAE,QAAQ,SAAU,EAAE,CAC5D,CAEO,SAASC,EAAaC,EAAkCC,EAAwB,CACrF,IAAMC,EAAIF,GAAa,WAAW,MAClC,GAAI,OAAOE,GAAM,WACf,MAAM,IAAI,MAAM,GAAGD,CAAG,iEAAiE,EAEzF,OAAOC,CACT,CAMA,eAAsBC,EACpBH,EACAI,EACAC,EACAC,EACoB,CACpB,IAAMC,EAAa,IAAI,gBACnBC,EAAW,GACTC,EAAQ,WAAW,IAAM,CAC7BD,EAAW,GACXD,EAAW,MAAM,CACnB,EAAGH,CAAS,EACZ,GAAI,CACF,IAAMM,EAAkC,CA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T_CHANGES_MAX_LIMIT","CONTACT_REF_PATTERN","CrmPartnerError","EXTERNAL_REF_PATTERN","PARTNER_MESSAGE_CHANGES_MAX_LIMIT","PartnerWebhookVerificationError","createCrmPartnerClient","verifyPartnerWebhook","__toCommonJS","normalizeBase","crmBaseUrl","resolveFetch","fetchImpl","who","f","sendJson","timeoutMs","url","init","controller","timedOut","timer","headers","hasBody","res","json","SAFE_CODE","errorCodeFrom","status","redact","fallback","pick","v","r","o","err","isRecord","import_node_crypto","PartnerWebhookVerificationError","_PartnerWebhookVerificationError","reason","DEFAULT_TOLERANCE_SECONDS","SIGNATURE_HEX","PLAIN_INTEGER","headerValue","headers","name","record","key","value","first","isString","isRecord","parseEvent","rawBody","data","sender","verifyPartnerWebhook","input","timestamp","signature","tolerance","nowSeconds","expected","CrmPartnerError","_CrmPartnerError","status","code","EXTERNAL_REF_PATTERN","CONTACT_REF_PATTERN","CONTACT_CHANGES_MAX_LIMIT","PARTNER_MESSAGE_CHANGES_MAX_LIMIT","AI_MONTHLY_CAP_MAX_CREDITS","fromStatus","w","sentAtWire","value","isChange","v","isRecord","isNullableString","USAGE_DATE","usageDate","text","checkCap","cap","isStatus","createCrmPartnerClient","opts","fetchImpl","resolveFetch","timeoutMs","root","normalizeBase","base","redact","checkRef","externalRef","call","method","path","body","prefix","res","sendJson","errorCodeFrom","bad","checkContactRef","contactRef","ref","aiMonthlyCapCredits","partnerChannelEnabled","webhookUrl","rest","wireBody","json","wire","secret","ai","err","patch","range","qs","cref","identity","phone","email","hasPhone","hasEmail","query","since","cursor","limit","q","message","threadRef","page","item","input"]}
|