@first-to-fly/crm-sdk 1.6.0 → 1.10.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.
@@ -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 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 { crmSession, type CrmSessionResult, type CrmHostTheme };\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 /** 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 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 });\n hostContextRef.current = { theme, locale };\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 useEffect(() => {\n hostRef.current?.setContext({ theme, locale });\n }, [theme, locale]);\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? } 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=` and `?locale=`), 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 * 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\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\n/**\n * Keeps only values the CRM understands: a known theme and a well-formed language tag.\n * Anything else is dropped, so a bad value can never reach the iframe URL or the message.\n */\nexport function normalizeHostContext(ctx: CrmHostContext | undefined): CrmHostContext {\n const out: CrmHostContext = {};\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` and `locale` as URL query pairs (e.g. `[\"theme=dark\", \"locale=zh-CN\"]`). */\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 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(): void {\n if (!port || (context.theme === undefined && context.locale === 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 context = { ...context, ...normalizeHostContext(ctx) };\n sendContext();\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,QCsBP,IAAMC,EAAiC,CAAC,QAAS,OAAQ,QAAQ,EAC3DC,GAAa,4CAMZ,SAASC,EAAqBC,EAAiD,CACpF,IAAMC,EAAsB,CAAC,EAC7B,OAAID,GAAK,OAASH,EAAY,SAASG,EAAI,KAAK,IAAGC,EAAI,MAAQD,EAAI,OAC/D,OAAOA,GAAK,QAAW,UAAYF,GAAW,KAAKE,EAAI,OAAO,KAAK,CAAC,IAAGC,EAAI,OAASD,EAAI,OAAO,KAAK,GACjGC,CACT,CAGO,SAASC,EAAiBF,EAA2C,CAC1E,IAAMG,EAAQJ,EAAqBC,CAAG,EAChCI,EAAkB,CAAC,EACzB,OAAID,EAAM,OAAOC,EAAM,KAAK,SAAS,mBAAmBD,EAAM,KAAK,CAAC,EAAE,EAClEA,EAAM,QAAQC,EAAM,KAAK,UAAU,mBAAmBD,EAAM,MAAM,CAAC,EAAE,EAClEC,CACT,CAwDA,SAASC,GAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAy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jE,CACF,EAEO6D,GAAQvD","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","HOST_THEMES","BCP47_LIKE","normalizeHostContext","ctx","out","hostContextQuery","clean","pairs","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","context","sendContext","msg","deliverBearer","bearer","err","onPortMessage","e","ok","startHandshake","channel","onWindowMessage","event","path","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","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","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,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,GAAK,IAAM,GACnF,OAAOA,CACT,CAMO,SAASE,EAAmBC,EAAkE,CACnG,GAAI,CAACA,GAAS,OAAOA,GAAU,UAAY,MAAM,QAAQA,CAAK,EAAG,OACjE,IAAMC,EAAoB,CAAC,EAC3B,QAAWC,KAAOR,GAAkB,CAClC,IAAMS,EAAMH,EAAME,CAAG,EACrB,GAAI,OAAOC,GAAQ,UAAYC,GAAU,KAAKD,EAAI,KAAK,CAAC,EAAG,CACzD,IAAIE,EAAMF,EAAI,KAAK,EAAE,YAAY,EAC7BE,EAAI,SAAW,IAAG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ACZ,IAAM6D,EAAI9D,EAAQC,CAAG,EACrBoC,EAASyB,CAAC,EACVhB,EAAW,UAAUgB,CAAC,EACtB,MACF,CAEA,OAAArB,EAAQ,QAAUuB,EAGlBnB,EAAW,UAAU,CAAE,YAAAV,CAAY,CAAC,EAE7B,IAAM,CACX6B,GAAM,QAAQ,EACdvB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACT,EAAUG,EAAatB,CAAc,CAAC,EAI1C,IAAMuD,GAAW,KAAK,UAAU5C,GAAS,IAAI,EACvC6C,GAAkB,KAAK,UAAU5C,GAAgB,IAAI,EACrD6C,EAAcvC,EAAO,EAAK,EAWhC,OAVAkB,EAAU,IAAM,CAEd,IAAMsB,EAAc/C,EAAQ,CAAE,MAAAA,CAAM,EAAK8C,EAAY,QAAU,CAAE,MAAO,IAAK,EAAI,CAAC,EAClFA,EAAY,QAAU,CAAC,CAAC9C,EACxBiB,EAAQ,SAAS,WAAW,CAC1B,MAAAnB,EAAO,OAAAC,EAAQ,aAAAE,EAAc,SAAAC,EAAU,GAAG6C,CAC5C,CAAC,CAEH,EAAG,CAACjD,EAAOC,EAAQ6C,GAAUC,GAAiB3C,CAAQ,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 C=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var j=Object.getOwnPropertyNames;var B=Object.prototype.hasOwnProperty;var I=(e,s)=>{for(var p in s)C(e,p,{get:s[p],enumerable:!0})},F=(e,s,p,f)=>{if(s&&typeof s=="object"||typeof s=="function")for(let l of j(s))!B.call(e,l)&&l!==p&&C(e,l,{get:()=>s[l],enumerable:!(f=$(s,l))||f.enumerable});return e};var L=e=>F(C({},"__esModule",{value:!0}),e);var N={};I(N,{CONTACT_CHANGES_MAX_LIMIT:()=>S,CONTACT_REF_PATTERN:()=>E,CrmPartnerError:()=>k,EXTERNAL_REF_PATTERN:()=>T,createCrmPartnerClient:()=>D});module.exports=L(N);function R(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function _(e,s){let p=e??globalThis.fetch;if(typeof p!="function")throw new Error(`${s}: no fetch implementation available. Pass \`fetch\` explicitly.`);return p}async function W(e,s,p,f){let l=new AbortController,c=!1,u=setTimeout(()=>{c=!0,l.abort()},s);try{let m={Accept:"application/json",...f.headers},y=f.body!==void 0;y&&(m["Content-Type"]="application/json");let r=await e(p,{method:f.method,headers:m,body:y?JSON.stringify(f.body):void 0,signal:l.signal}),o=await r.json().catch(()=>null);return c?{ok:!1,kind:"timeout"}:{ok:!0,status:r.status,json:o}}catch{return{ok:!1,kind:c?"timeout":"network"}}finally{clearTimeout(u)}}var O=/^[A-Za-z0-9_.:-]{1,60}$/;function x(e,s,p){let f=`HTTP_${s}`,l=c=>typeof c!="string"||!O.test(c)||p.some(u=>u&&c.includes(u))?null:c;if(e&&typeof e=="object"){let c=e,u=c.error;return l(c.code)??l(u)??(u&&typeof u=="object"?l(u.code):null)??f}return f}var g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var k=class e extends Error{constructor(s,p){super(s===0?`CRM partner API unreachable (${p})`:`CRM partner API ${s} ${p}`),this.name="CrmPartnerError",this.status=s,this.code=p,Object.setPrototypeOf(this,e.prototype)}},T=/^[A-Za-z0-9_-]{1,64}$/,E=/^[A-Za-z0-9._:-]{1,200}$/,S=200,h=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled}),A=e=>e===null||typeof e=="string";function w(e){return g(e)&&typeof e.external_ref=="string"&&A(e.workspace_id)&&A(e.embed_app_id)&&typeof e.enabled=="boolean"}function D(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let s=_(e.fetch,"createCrmPartnerClient"),p=e.timeoutMs??15e3,f=`${R(e.crmBaseUrl)}/api/partner/v1/workspaces`,l=[e.partnerKey];function c(r){if(typeof r!="string"||!T.test(r))throw new k(400,"invalid_external_ref");return r}async function u(r,o,i){let t=await W(s,p,`${f}/${o}`,{method:r,headers:{Authorization:`Bearer ${e.partnerKey}`},body:i});if(!t.ok)throw new k(0,t.kind);if(t.status<200||t.status>=300)throw new k(t.status,x(t.json,t.status,l));return{status:t.status,json:t.json}}let m=r=>new k(r,"bad_response");function y(r){if(typeof r!="string"||!E.test(r))throw new k(400,"invalid_contact_ref");return r}return{async upsertWorkspace(r,o){let i=c(r),{status:t,json:a}=await u("PUT",i,o);if(!w(a))throw m(t);let n=a;if(n.created===!0){let d=n.embed_app_secret;if(typeof d!="string"||!d)throw m(t);return{...h(n),created:!0,embedAppSecret:d}}if(n.created===!1)return{...h(n),created:!1};throw m(t)},async getWorkspace(r){let o=c(r);try{let{status:i,json:t}=await u("GET",o);if(!w(t)||typeof t.state!="string")throw m(i);return{...h(t),state:t.state}}catch(i){if(i instanceof k&&i.status===404)return null;throw i}},async updateWorkspace(r,o){let i=c(r),t={};o.enabled!==void 0&&(t.enabled=o.enabled),o.name!==void 0&&(t.name=o.name);let{status:a,json:n}=await u("PATCH",i,t);if(!w(n))throw m(a);return h(n)},async rotateWorkspaceSecret(r){let o=c(r),{status:i,json:t}=await u("POST",`${o}/rotate-secret`),a=t;if(!g(t)||typeof a?.embed_app_id!="string"||typeof a.embed_app_secret!="string"||!a.embed_app_secret)throw m(i);return{embedAppId:a.embed_app_id,embedAppSecret:a.embed_app_secret}},async upsertContact(r,o,i){let t=c(r),a=y(o),{status:n,json:d}=await u("PUT",`${t}/contacts/${encodeURIComponent(a)}`,i);if(!g(d)||!g(d.contact)||typeof d.created!="boolean"||typeof d.consent_applied!="boolean")throw m(n);return d},async eraseContact(r,o){let i=c(r),t=y(o);try{let{status:a,json:n}=await u("DELETE",`${i}/contacts/${encodeURIComponent(t)}`);if(!g(n)||n.erased!==!0||typeof n.contact_id!="string")throw m(a);return n}catch(a){if(a instanceof k&&a.status===404)return null;throw a}},async listContactChanges(r,o={}){let i=c(r),{since:t,cursor:a,limit:n}=o;if(n!==void 0&&(!Number.isInteger(n)||n<1||n>S))throw new k(400,"invalid_limit");let d=new URLSearchParams;t!==void 0&&d.set("since",t),a!==void 0&&d.set("cursor",a),n!==void 0&&d.set("limit",String(n));let b=d.toString(),{status:U,json:P}=await u("GET",`${i}/contacts/changes${b?`?${b}`:""}`);if(!g(P)||!Array.isArray(P.items)||!(P.next_cursor===null||typeof P.next_cursor=="string"))throw m(U);return P}}}0&&(module.exports={CONTACT_CHANGES_MAX_LIMIT,CONTACT_REF_PATTERN,CrmPartnerError,EXTERNAL_REF_PATTERN,createCrmPartnerClient});
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});
2
2
  //# sourceMappingURL=partner.cjs.map
@@ -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` / `HTTP_<status>`).\n * The message never contains the key, a secret or a response body.\n *\n * Contact sync (`upsertContact`, `eraseContact`, `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 * 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 PartnerContactEraseResult,\n PartnerWorkspaceCreated,\n PartnerWorkspaceDetail as WirePartnerWorkspaceDetail,\n PartnerWorkspaceExisting,\n PartnerWorkspacePatchBody,\n PartnerWorkspaceSecret,\n PartnerWorkspaceStatus,\n PartnerWorkspaceUpsertBody,\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` / `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/** 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\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\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 */\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 or rename the workspace. At least one field is required. */\n updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;\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 * 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});\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 { status, json } = await call('PUT', ref, body);\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 return { ...fromStatus(json), state: (json as unknown as WirePartnerWorkspaceDetail).state };\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: PartnerWorkspacePatchBody = {};\n if (patch.enabled !== undefined) body.enabled = patch.enabled;\n if (patch.name !== undefined) body.name = patch.name;\n const { status, json } = await call('PATCH', ref, body);\n if (!isStatus(json)) throw bad(status);\n return fromStatus(json);\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 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 PartnerContactEraseResult,\n PartnerWorkspaceUpsertBody,\n PartnerWorkspacePatchBody,\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,+BAAAE,EAAA,wBAAAC,EAAA,oBAAAC,EAAA,yBAAAC,EAAA,2BAAAC,IAAA,eAAAC,EAAAP,GCkBO,SAASQ,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,GA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AG,oBAAoBY,EAAI,IAAIA,CAAC,GAAK,EAAE,EAAE,EACvF,GAAI,CAACjC,EAASsB,CAAI,GAAK,CAAC,MAAM,QAAQA,EAAK,KAAK,GAAK,EAAEA,EAAK,cAAgB,MAAQ,OAAOA,EAAK,aAAgB,UAC9G,MAAMJ,EAAI5B,CAAM,EAElB,OAAOgC,CACT,CACF,CACF","names":["partner_exports","__export","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","fromStatus","w","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","json","wire","secret","err","patch","cref","query","since","cursor","limit","qs","q"]}
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,OA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EAASyB,CAAI,GAAK,CAAC,MAAM,QAAQA,EAAK,KAAK,GAAK,EAAEA,EAAK,cAAgB,MAAQ,OAAOA,EAAK,aAAgB,UAC9G,MAAMP,EAAInC,CAAM,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,5 +1,5 @@
1
- import { O as PartnerWorkspaceUpsertBody, H as PartnerWorkspaceDetail$1, J as PartnerWorkspacePatchBody, z as ContactRefUpsertBody, A as ContactRefUpsertResult, F as PartnerContactEraseResult, x as ContactChanges } from './crm-contracts-iWWbB6Ga.cjs';
2
- export { y as ContactChangesQuery } from './crm-contracts-iWWbB6Ga.cjs';
1
+ import { R as PartnerWorkspaceUpsertBody$1, J as PartnerWorkspaceDetail$1, N as PartnerWorkspacePatchBody$1, S as PartnerWorkspaceUsage, z as ContactRefUpsertBody, A as ContactRefUpsertResult, H as PartnerContactEraseResult, F as PartnerContactEraseByIdentityBody, G as PartnerContactEraseByIdentityResult, x as ContactChanges } from './crm-contracts-BiR0JbKC.cjs';
2
+ export { y as ContactChangesQuery } from './crm-contracts-BiR0JbKC.cjs';
3
3
 
4
4
  /**
5
5
  * Internal HTTP helper for the server-side `partner` entry point. Not part of the
@@ -37,14 +37,19 @@ type FetchLike = typeof fetch;
37
37
  * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
38
38
  * network failure or timeout), `code` is the CRM's short error code (or
39
39
  * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
40
- * `invalid_limit` / `HTTP_<status>`).
40
+ * `invalid_limit` / `invalid_cap` / `invalid_date` / `invalid_identity` / `HTTP_<status>`).
41
41
  * The message never contains the key, a secret or a response body.
42
42
  *
43
- * Contact sync (`upsertContact`, `eraseContact`, `listContactChanges`) acts in a
43
+ * Contact sync (`upsertContact`, `eraseContact`, `eraseContactsByIdentity`, `listContactChanges`) acts in a
44
44
  * provisioned workspace as your product, with the same partner key. A disabled
45
45
  * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still
46
46
  * erases and lists.
47
47
  *
48
+ * AI for the workspace is metered in credits (1 credit = US$0.001). `aiMonthlyCapCredits` is
49
+ * the monthly cap you set per workspace: `null` = no cap, `0` = AI off, N = N credits per UTC
50
+ * calendar month. A workspace created without one gets 5000. `getWorkspaceUsage` reports use
51
+ * over a date range.
52
+ *
48
53
  * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
49
54
  * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
50
55
  * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
@@ -57,7 +62,7 @@ type FetchLike = typeof fetch;
57
62
  declare class CrmPartnerError extends Error {
58
63
  /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
59
64
  readonly status: number;
60
- /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `HTTP_<status>`. */
65
+ /** 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>`. */
61
66
  readonly code: string;
62
67
  constructor(status: number, code: string);
63
68
  }
@@ -76,6 +81,8 @@ interface CrmPartnerClientOptions {
76
81
  /** Per-request timeout in ms. Default 15000. */
77
82
  timeoutMs?: number;
78
83
  }
84
+ /** Upper bound the CRM accepts for `aiMonthlyCapCredits` (100 million credits). */
85
+ declare const AI_MONTHLY_CAP_MAX_CREDITS = 100000000;
79
86
  /** Fields every workspace response carries. */
80
87
  interface PartnerWorkspace {
81
88
  externalRef: string;
@@ -84,6 +91,31 @@ interface PartnerWorkspace {
84
91
  /** Null until provisioning has created the embed app. */
85
92
  embedAppId: string | null;
86
93
  enabled: boolean;
94
+ /**
95
+ * Monthly AI cap in credits: `null` = no cap (also what an older CRM that does not report it
96
+ * returns), `0` = AI off, N = N credits per UTC calendar month.
97
+ */
98
+ aiMonthlyCapCredits: number | null;
99
+ }
100
+ /** Body of {@link CrmPartnerClient.upsertWorkspace}. */
101
+ type PartnerWorkspaceUpsertBody = Omit<PartnerWorkspaceUpsertBody$1, 'ai_monthly_cap_credits'> & {
102
+ /**
103
+ * Monthly AI cap in credits (integer, 0 to {@link AI_MONTHLY_CAP_MAX_CREDITS}, or `null` for none).
104
+ * Omit on create for the default of 5000; omit on a later call to leave it unchanged.
105
+ */
106
+ aiMonthlyCapCredits?: number | null;
107
+ };
108
+ /** Body of {@link CrmPartnerClient.updateWorkspace}. At least one field is required. */
109
+ type PartnerWorkspacePatchBody = Omit<PartnerWorkspacePatchBody$1, 'ai_monthly_cap_credits'> & {
110
+ /** Monthly AI cap in credits; `null` removes the cap, `0` switches AI off. */
111
+ aiMonthlyCapCredits?: number | null;
112
+ };
113
+ /** Query of {@link CrmPartnerClient.getWorkspaceUsage}: UTC calendar dates, `to` inclusive. */
114
+ interface PartnerUsageRange {
115
+ /** `YYYY-MM-DD` (UTC), or a `Date` whose UTC date is used. */
116
+ from: string | Date;
117
+ /** `YYYY-MM-DD` (UTC) or a `Date`; the whole day is included. At most 12 months after `from`. */
118
+ to: string | Date;
87
119
  }
88
120
  /**
89
121
  * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)
@@ -102,6 +134,14 @@ type PartnerWorkspaceUpsertResult = (PartnerWorkspace & {
102
134
  interface PartnerWorkspaceDetail extends PartnerWorkspace {
103
135
  /** Provisioning progress; `active` once the workspace is ready for sessions. */
104
136
  state: PartnerWorkspaceDetail$1['state'];
137
+ /**
138
+ * AI credits used in the current UTC month (`period` is `YYYY-MM`); null until the workspace
139
+ * exists, or when talking to a CRM that does not report it.
140
+ */
141
+ ai: {
142
+ period: string;
143
+ usedCredits: number;
144
+ } | null;
105
145
  }
106
146
  /** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */
107
147
  interface PartnerRotatedSecret {
@@ -113,12 +153,21 @@ interface CrmPartnerClient {
113
153
  * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
114
154
  * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that
115
155
  * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.
156
+ * `aiMonthlyCapCredits` sets the monthly AI cap (see {@link PartnerWorkspaceUpsertBody}).
116
157
  */
117
158
  upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
118
159
  /** Provisioning status, or `null` when the CRM does not know this ref (404). */
119
160
  getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
120
- /** Enable/disable the embed app or rename the workspace. At least one field is required. */
161
+ /** Enable/disable the embed app, rename the workspace or set its monthly AI cap. At least one field is required. */
121
162
  updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
163
+ /**
164
+ * AI usage of the workspace from `from` to `to` (UTC dates, `to` inclusive, at most 12 months):
165
+ * totals, then the same figures by operation, model and day, plus the current month's cap and
166
+ * the embedded assistant's tokens (which are recorded but not capped). Returned as the CRM
167
+ * sends it (snake_case). `cost_usd` is the provider cost; credits are what the cap counts.
168
+ * Resolves `null` for a ref the CRM does not know or that has no workspace yet (404).
169
+ */
170
+ getWorkspaceUsage(externalRef: string, range: PartnerUsageRange): Promise<PartnerWorkspaceUsage | null>;
122
171
  /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
123
172
  rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
124
173
  /**
@@ -137,6 +186,17 @@ interface CrmPartnerClient {
137
186
  * also resolves `null`; use `getWorkspace` to tell them apart.
138
187
  */
139
188
  eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
189
+ /**
190
+ * PDPA erasure of the contacts that match a person's phone (E.164) or email (case-insensitive)
191
+ * and that your product never linked by ref, such as a parent who wrote first on WhatsApp.
192
+ * Send `ref` (the erased person's own `contactRef`) so a contact linked only to that ref is
193
+ * erased too. A matched contact with any other ref (another person of yours, or another
194
+ * product) is left alone and counted in `skipped_linked_elsewhere`, so a shared family number
195
+ * survives. At least one of `phone` or `email` is required (a client-side 400
196
+ * `invalid_identity` otherwise). Works while the workspace is disabled. No match resolves
197
+ * `erased: 0`. Resolves `null` for an unknown workspace (404).
198
+ */
199
+ eraseContactsByIdentity(externalRef: string, identity: PartnerContactEraseByIdentityBody): Promise<PartnerContactEraseByIdentityResult | null>;
140
200
  /**
141
201
  * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
142
202
  * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
@@ -150,4 +210,4 @@ interface CrmPartnerClient {
150
210
  }
151
211
  declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
152
212
 
153
- export { CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerWorkspace, type PartnerWorkspaceDetail, PartnerWorkspacePatchBody, PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, createCrmPartnerClient };
213
+ export { AI_MONTHLY_CAP_MAX_CREDITS, CONTACT_CHANGES_MAX_LIMIT, CONTACT_REF_PATTERN, ContactChanges, ContactRefUpsertBody, ContactRefUpsertResult, type CrmPartnerClient, type CrmPartnerClientOptions, CrmPartnerError, EXTERNAL_REF_PATTERN, PartnerContactEraseByIdentityBody, PartnerContactEraseByIdentityResult, PartnerContactEraseResult, type PartnerRotatedSecret, type PartnerUsageRange, type PartnerWorkspace, type PartnerWorkspaceDetail, type PartnerWorkspacePatchBody, type PartnerWorkspaceUpsertBody, type PartnerWorkspaceUpsertResult, PartnerWorkspaceUsage, createCrmPartnerClient };