@first-to-fly/crm-sdk 1.4.3 → 1.6.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 type CrmBearer,\n type CrmEmbedHost,\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 };\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 /** 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 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 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 url = base + (initialPathRef.current ?? '') + (hostProvidesNav ? '?hostnav=1' : '');\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 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 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 *\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\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 * 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 /** 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\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 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 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,EAAY,eAAAC,EAAa,aAAAC,EAAW,uBAAAC,EAAqB,UAAAC,EAAQ,YAAAC,MAC5D,QC6CP,SAASC,EAAQC,EAAwC,CACvD,MAAO,CAAC,CAACA,GAAQ,OAAOA,GAAS,UAC3BA,EAAyB,SAAW,aACpCA,EAAyB,OAAS,OAC1C,CAmBO,SAASC,EACdC,EACAC,EACiC,CACjC,MAAO,UAAuC,CAC5C,IAAMC,EAAM,MAAM,MAAMF,EAAK,CAAE,OAAQ,OAAQ,GAAGC,CAAK,CAAC,EAClDE,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAME,EAAQD,GAA6B,MAC3C,MAAM,IAAI,MACRC,EAAO,uBAAuBA,CAAI,GAAK,4BAA4BF,EAAI,MAAM,GAC/E,CACF,CACA,IAAMG,E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,EAAc,EAAIpB,EAAe,EAAE,CAYjE,CACF,EAEOsD,GAAQhD","names":["forwardRef","useCallback","useEffect","useImperativeHandle","useRef","useState","isReady","data","crmSession","url","init","res","body","code","result","buildCrmEmbedUrl","crmOrigin","workspaceId","createCrmEmbedHost","opts","target","makeChannel","targetOrigin","port","nonce","disposed","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","renderLoading","renderError","iframeRef","useRef","embedUrl","setEmbedUrl","useState","workspaceId","setWorkspaceId","setError","attempt","setAttempt","primedBearerRef","hostRef","useImperativeHandle","path","getSessionRef","onReadyRef","onErrorRef","onRouteChangeRef","useEffect","initialPathRef","useCallback","n","cancelled","session","url","buildCrmEmbedUrl","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 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,O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,IAAM,CACX4B,GAAM,QAAQ,EACdtB,EAAQ,QAAU,IACpB,CACF,EAAG,CAACT,EAAUG,EAAalB,CAAc,CAAC,EAG1C+B,EAAU,IAAM,CACdP,EAAQ,SAAS,WAAW,CAAE,MAAAf,EAAO,OAAAC,CAAO,CAAC,CAC/C,EAAG,CAACD,EAAOC,CAAM,CAAC,EAEdlB,EACKF,EAAA2D,EAAA,CAAG,SAAArC,EAAcA,EAAYpB,EAAOC,CAAK,EAAIF,GAAaC,EAAOC,CAAK,EAAE,EAG5EsB,EAKHzB,EAAC,UACC,IAAKuB,EACL,IAAKE,EACL,MAAOZ,EACP,UAAWF,EACX,MAAO,CAAE,GAAGf,GAAsB,GAAGgB,CAAM,EAC7C,EAVOZ,EAAA2D,EAAA,CAAG,SAAAtC,EAAgBA,EAAc,EAAItB,GAAe,EAAE,CAYjE,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"]}
@@ -0,0 +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});
2
+ //# sourceMappingURL=partner.cjs.map
@@ -0,0 +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,GAAGD,CAAG,iEAAiE,EAEzF,OAAOC,CACT,CAMA,eAAsBC,EACpBH,EACAI,EACAC,EACAC,EACoB,CACpB,IAAMC,EAAa,IAAI,gBACnBC,EAAW,GACTC,EAAQ,WAAW,IAAM,CAC7BD,EAAW,GACXD,EAAW,MAAM,CACnB,EAAGH,CAAS,EACZ,GAAI,CACF,IAAMM,EAAkC,CAAE,OAAQ,mBAAoB,GAAGJ,EAAK,OAAQ,EAChFK,EAAUL,EAAK,OAAS,OAC1BK,IAASD,EAAQ,cAAc,EAAI,oBACvC,IAAME,EAAM,MAAMZ,EAAUK,EAAK,CAC/B,OAAQC,EAAK,OACb,QAAAI,EACA,KAAMC,EAAU,KAAK,UAAUL,EAAK,IAAI,EAAI,OAC5C,OAAQC,EAAW,MACrB,CAAC,EACKM,EAAgB,MAAMD,EAAI,KAAK,EAAE,MAAM,I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K,YAAe,SAAU,MAAMJ,EAAI5B,CAAM,EACpG,OAAOgC,CACT,OAASG,EAAK,CACZ,GAAIA,aAAerC,GAAmBqC,EAAI,SAAW,IAAK,OAAO,KACjE,MAAMA,CACR,CACF,EAEA,MAAM,mBAAmBf,EAAakB,EAAQ,CAAC,EAAG,CAChD,IAAMP,EAAMZ,EAASC,CAAW,EAC1B,CAAE,MAAAmB,EAAO,OAAAC,EAAQ,MAAAC,CAAM,EAAIH,EACjC,GAAIG,IAAU,SAAc,CAAC,OAAO,UAAUA,CAAK,GAAKA,EAAQ,GAAKA,EAAQrC,GAC3E,MAAM,IAAIN,EAAgB,IAAK,eAAe,EAEhD,IAAM4C,EAAK,IAAI,gBACXH,IAAU,QAAWG,EAAG,IAAI,QAASH,CAAK,EAC1CC,IAAW,QAAWE,EAAG,IAAI,SAAUF,CAAM,EAC7CC,IAAU,QAAWC,EAAG,IAAI,QAAS,OAAOD,CAAK,CAAC,EACtD,IAAME,EAAID,EAAG,SAAS,EAChB,CAAE,OAAA1C,EAAQ,KAAAgC,CAAK,EAAI,MAAMX,EAAK,MAAO,GAAGU,CAAG,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"]}
@@ -0,0 +1,153 @@
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';
3
+
4
+ /**
5
+ * Internal HTTP helper for the server-side `partner` entry point. Not part of the
6
+ * public API (no package export points here).
7
+ *
8
+ * It never puts a request header, a request body or a response body into an
9
+ * error: callers get the HTTP status, a short sanitized error code, or a
10
+ * transport failure kind, and nothing else.
11
+ */
12
+ type FetchLike = typeof fetch;
13
+
14
+ /**
15
+ * CRM Partner SDK (server side ONLY).
16
+ *
17
+ * A product that embeds the CRM (a "partner") provisions one CRM workspace per
18
+ * customer of its own, keyed by the customer's id in the product (`externalRef`).
19
+ * The call authenticates with ONE platform key (`ptk_...`) that can create and
20
+ * manage workspaces for every customer of the partner.
21
+ *
22
+ * **Never run this in a browser, a mobile app or any client bundle.** The partner
23
+ * key is a platform-wide secret and the responses carry per-workspace embed
24
+ * secrets. Keep both in server-side configuration and never log them.
25
+ *
26
+ * ```ts
27
+ * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';
28
+ *
29
+ * const partner = createCrmPartnerClient({
30
+ * crmBaseUrl: process.env.CRM_BASE_URL!,
31
+ * partnerKey: process.env.CRM_PARTNER_KEY!,
32
+ * });
33
+ * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });
34
+ * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once
35
+ * ```
36
+ *
37
+ * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
38
+ * network failure or timeout), `code` is the CRM's short error code (or
39
+ * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
40
+ * `invalid_limit` / `HTTP_<status>`).
41
+ * The message never contains the key, a secret or a response body.
42
+ *
43
+ * Contact sync (`upsertContact`, `eraseContact`, `listContactChanges`) acts in a
44
+ * provisioned workspace as your product, with the same partner key. A disabled
45
+ * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still
46
+ * erases and lists.
47
+ *
48
+ * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
49
+ * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
50
+ * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
51
+ * 500 and status 0 are also safe to repeat.
52
+ *
53
+ * @packageDocumentation
54
+ */
55
+
56
+ /** A failed partner API call. The message never includes the key, secrets or response bodies. */
57
+ declare class CrmPartnerError extends Error {
58
+ /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
59
+ readonly status: number;
60
+ /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `HTTP_<status>`. */
61
+ readonly code: string;
62
+ constructor(status: number, code: string);
63
+ }
64
+ /** Same pattern the CRM enforces on `externalRef`. */
65
+ declare const EXTERNAL_REF_PATTERN: RegExp;
66
+ /** Same pattern the CRM enforces on a `contactRef`. */
67
+ declare const CONTACT_REF_PATTERN: RegExp;
68
+ declare const CONTACT_CHANGES_MAX_LIMIT = 200;
69
+ interface CrmPartnerClientOptions {
70
+ /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */
71
+ crmBaseUrl: string;
72
+ /** Partner key (`ptk_...`). Server-side secret. */
73
+ partnerKey: string;
74
+ /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */
75
+ fetch?: FetchLike;
76
+ /** Per-request timeout in ms. Default 15000. */
77
+ timeoutMs?: number;
78
+ }
79
+ /** Fields every workspace response carries. */
80
+ interface PartnerWorkspace {
81
+ externalRef: string;
82
+ /** Null until provisioning has created the workspace. */
83
+ workspaceId: string | null;
84
+ /** Null until provisioning has created the embed app. */
85
+ embedAppId: string | null;
86
+ enabled: boolean;
87
+ }
88
+ /**
89
+ * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)
90
+ * is the one call that carries `embedAppSecret`, shown once: store it. A repeat
91
+ * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`
92
+ * if it was lost.
93
+ */
94
+ type PartnerWorkspaceUpsertResult = (PartnerWorkspace & {
95
+ created: true;
96
+ embedAppSecret: string;
97
+ }) | (PartnerWorkspace & {
98
+ created: false;
99
+ embedAppSecret?: undefined;
100
+ });
101
+ /** Result of {@link CrmPartnerClient.getWorkspace}. */
102
+ interface PartnerWorkspaceDetail extends PartnerWorkspace {
103
+ /** Provisioning progress; `active` once the workspace is ready for sessions. */
104
+ state: PartnerWorkspaceDetail$1['state'];
105
+ }
106
+ /** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */
107
+ interface PartnerRotatedSecret {
108
+ embedAppId: string;
109
+ embedAppSecret: string;
110
+ }
111
+ interface CrmPartnerClient {
112
+ /**
113
+ * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
114
+ * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that
115
+ * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.
116
+ */
117
+ upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
118
+ /** Provisioning status, or `null` when the CRM does not know this ref (404). */
119
+ getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
120
+ /** Enable/disable the embed app or rename the workspace. At least one field is required. */
121
+ updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
122
+ /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
123
+ rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
124
+ /**
125
+ * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the
126
+ * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`
127
+ * only applies when its `recorded_at` is newer than the stored one and the parent has
128
+ * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file
129
+ * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the
130
+ * workspace is disabled and 404 for an unknown workspace.
131
+ */
132
+ upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;
133
+ /**
134
+ * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.
135
+ * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already
136
+ * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it
137
+ * also resolves `null`; use `getWorkspace` to tell them apart.
138
+ */
139
+ eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
140
+ /**
141
+ * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
142
+ * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
143
+ * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.
144
+ */
145
+ listContactChanges(externalRef: string, query?: {
146
+ since?: string;
147
+ cursor?: string;
148
+ limit?: number;
149
+ }): Promise<ContactChanges>;
150
+ }
151
+ declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
152
+
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 };
@@ -0,0 +1,153 @@
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.js';
2
+ export { y as ContactChangesQuery } from './crm-contracts-iWWbB6Ga.js';
3
+
4
+ /**
5
+ * Internal HTTP helper for the server-side `partner` entry point. Not part of the
6
+ * public API (no package export points here).
7
+ *
8
+ * It never puts a request header, a request body or a response body into an
9
+ * error: callers get the HTTP status, a short sanitized error code, or a
10
+ * transport failure kind, and nothing else.
11
+ */
12
+ type FetchLike = typeof fetch;
13
+
14
+ /**
15
+ * CRM Partner SDK (server side ONLY).
16
+ *
17
+ * A product that embeds the CRM (a "partner") provisions one CRM workspace per
18
+ * customer of its own, keyed by the customer's id in the product (`externalRef`).
19
+ * The call authenticates with ONE platform key (`ptk_...`) that can create and
20
+ * manage workspaces for every customer of the partner.
21
+ *
22
+ * **Never run this in a browser, a mobile app or any client bundle.** The partner
23
+ * key is a platform-wide secret and the responses carry per-workspace embed
24
+ * secrets. Keep both in server-side configuration and never log them.
25
+ *
26
+ * ```ts
27
+ * import { createCrmPartnerClient } from '@first-to-fly/crm-sdk/partner';
28
+ *
29
+ * const partner = createCrmPartnerClient({
30
+ * crmBaseUrl: process.env.CRM_BASE_URL!,
31
+ * partnerKey: process.env.CRM_PARTNER_KEY!,
32
+ * });
33
+ * const ws = await partner.upsertWorkspace(tenantId, { name: 'Acme School' });
34
+ * if (ws.created) saveSecret(tenantId, ws.embedAppId, ws.embedAppSecret); // shown once
35
+ * ```
36
+ *
37
+ * Errors are {@link CrmPartnerError}: `status` is the HTTP status (0 for a
38
+ * network failure or timeout), `code` is the CRM's short error code (or
39
+ * `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` /
40
+ * `invalid_limit` / `HTTP_<status>`).
41
+ * The message never contains the key, a secret or a response body.
42
+ *
43
+ * Contact sync (`upsertContact`, `eraseContact`, `listContactChanges`) acts in a
44
+ * provisioned workspace as your product, with the same partner key. A disabled
45
+ * workspace refuses upserts (409 `WORKSPACE_DISABLED`; not retryable) but still
46
+ * erases and lists.
47
+ *
48
+ * Retryable: `status` 409 (`PROVISIONING_IN_PROGRESS`, another call for the ref is
49
+ * running) and 503 (`SERVICE_BUSY`). Wait a few seconds (the CRM sends
50
+ * `Retry-After: 5`) and repeat the same call; provisioning resumes where it stopped.
51
+ * 500 and status 0 are also safe to repeat.
52
+ *
53
+ * @packageDocumentation
54
+ */
55
+
56
+ /** A failed partner API call. The message never includes the key, secrets or response bodies. */
57
+ declare class CrmPartnerError extends Error {
58
+ /** HTTP status; 0 when the CRM could not be reached (network failure or timeout). 409 and 503 mean retry shortly. */
59
+ readonly status: number;
60
+ /** The CRM's error code, or `timeout` / `network` / `bad_response` / `invalid_external_ref` / `invalid_contact_ref` / `invalid_limit` / `HTTP_<status>`. */
61
+ readonly code: string;
62
+ constructor(status: number, code: string);
63
+ }
64
+ /** Same pattern the CRM enforces on `externalRef`. */
65
+ declare const EXTERNAL_REF_PATTERN: RegExp;
66
+ /** Same pattern the CRM enforces on a `contactRef`. */
67
+ declare const CONTACT_REF_PATTERN: RegExp;
68
+ declare const CONTACT_CHANGES_MAX_LIMIT = 200;
69
+ interface CrmPartnerClientOptions {
70
+ /** CRM base URL, e.g. `https://crm.example.com` (a trailing `/api` is tolerated). */
71
+ crmBaseUrl: string;
72
+ /** Partner key (`ptk_...`). Server-side secret. */
73
+ partnerKey: string;
74
+ /** Custom fetch (tests, proxies). Defaults to the global `fetch`. */
75
+ fetch?: FetchLike;
76
+ /** Per-request timeout in ms. Default 15000. */
77
+ timeoutMs?: number;
78
+ }
79
+ /** Fields every workspace response carries. */
80
+ interface PartnerWorkspace {
81
+ externalRef: string;
82
+ /** Null until provisioning has created the workspace. */
83
+ workspaceId: string | null;
84
+ /** Null until provisioning has created the embed app. */
85
+ embedAppId: string | null;
86
+ enabled: boolean;
87
+ }
88
+ /**
89
+ * Result of {@link CrmPartnerClient.upsertWorkspace}. `created: true` (HTTP 201)
90
+ * is the one call that carries `embedAppSecret`, shown once: store it. A repeat
91
+ * call (HTTP 200) has `created: false` and no secret; use `rotateWorkspaceSecret`
92
+ * if it was lost.
93
+ */
94
+ type PartnerWorkspaceUpsertResult = (PartnerWorkspace & {
95
+ created: true;
96
+ embedAppSecret: string;
97
+ }) | (PartnerWorkspace & {
98
+ created: false;
99
+ embedAppSecret?: undefined;
100
+ });
101
+ /** Result of {@link CrmPartnerClient.getWorkspace}. */
102
+ interface PartnerWorkspaceDetail extends PartnerWorkspace {
103
+ /** Provisioning progress; `active` once the workspace is ready for sessions. */
104
+ state: PartnerWorkspaceDetail$1['state'];
105
+ }
106
+ /** Result of {@link CrmPartnerClient.rotateWorkspaceSecret}. The old secret stops working at once. */
107
+ interface PartnerRotatedSecret {
108
+ embedAppId: string;
109
+ embedAppSecret: string;
110
+ }
111
+ interface CrmPartnerClient {
112
+ /**
113
+ * Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. Optional
114
+ * `currency` (ISO 4217) and `timezone` (IANA) are applied on create and on any later call that
115
+ * sends them; an invalid value is a 400 `VALIDATION_ERROR` and nothing is provisioned.
116
+ */
117
+ upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
118
+ /** Provisioning status, or `null` when the CRM does not know this ref (404). */
119
+ getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
120
+ /** Enable/disable the embed app or rename the workspace. At least one field is required. */
121
+ updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
122
+ /** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
123
+ rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
124
+ /**
125
+ * Idempotent upsert of the contact for `contactRef` (your own key for the person) in the
126
+ * workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`
127
+ * only applies when its `recorded_at` is newer than the stored one and the parent has
128
+ * not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file
129
+ * the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the
130
+ * workspace is disabled and 404 for an unknown workspace.
131
+ */
132
+ upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;
133
+ /**
134
+ * PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.
135
+ * Resolves `null` when the CRM has no contact for this ref (404: never synced, or already
136
+ * erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it
137
+ * also resolves `null`; use `getWorkspace` to tell them apart.
138
+ */
139
+ eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
140
+ /**
141
+ * One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
142
+ * for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
143
+ * to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.
144
+ */
145
+ listContactChanges(externalRef: string, query?: {
146
+ since?: string;
147
+ cursor?: string;
148
+ limit?: number;
149
+ }): Promise<ContactChanges>;
150
+ }
151
+ declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
152
+
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 };
@@ -0,0 +1,2 @@
1
+ function b(e){return e.replace(/\/+$/,"").replace(/\/api$/,"")}function R(e,d){let u=e??globalThis.fetch;if(typeof u!="function")throw new Error(`${d}: no fetch implementation available. Pass \`fetch\` explicitly.`);return u}async function _(e,d,u,m){let k=new AbortController,o=!1,i=setTimeout(()=>{o=!0,k.abort()},d);try{let l={Accept:"application/json",...m.headers},y=m.body!==void 0;y&&(l["Content-Type"]="application/json");let r=await e(u,{method:m.method,headers:l,body:y?JSON.stringify(m.body):void 0,signal:k.signal}),a=await r.json().catch(()=>null);return o?{ok:!1,kind:"timeout"}:{ok:!0,status:r.status,json:a}}catch{return{ok:!1,kind:o?"timeout":"network"}}finally{clearTimeout(i)}}var T=/^[A-Za-z0-9_.:-]{1,60}$/;function W(e,d,u){let m=`HTTP_${d}`,k=o=>typeof o!="string"||!T.test(o)||u.some(i=>i&&o.includes(i))?null:o;if(e&&typeof e=="object"){let o=e,i=o.error;return k(o.code)??k(i)??(i&&typeof i=="object"?k(i.code):null)??m}return m}var g=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);var f=class e extends Error{constructor(d,u){super(d===0?`CRM partner API unreachable (${u})`:`CRM partner API ${d} ${u}`),this.name="CrmPartnerError",this.status=d,this.code=u,Object.setPrototypeOf(this,e.prototype)}},S=/^[A-Za-z0-9_-]{1,64}$/,U=/^[A-Za-z0-9._:-]{1,200}$/,$=200,h=e=>({externalRef:e.external_ref,workspaceId:e.workspace_id,embedAppId:e.embed_app_id,enabled:e.enabled}),x=e=>e===null||typeof e=="string";function C(e){return g(e)&&typeof e.external_ref=="string"&&x(e.workspace_id)&&x(e.embed_app_id)&&typeof e.enabled=="boolean"}function I(e){if(!e.crmBaseUrl)throw new Error("createCrmPartnerClient: `crmBaseUrl` is required.");if(!e.partnerKey)throw new Error("createCrmPartnerClient: `partnerKey` is required.");let d=R(e.fetch,"createCrmPartnerClient"),u=e.timeoutMs??15e3,m=`${b(e.crmBaseUrl)}/api/partner/v1/workspaces`,k=[e.partnerKey];function o(r){if(typeof r!="string"||!S.test(r))throw new f(400,"invalid_external_ref");return r}async function i(r,a,c){let t=await _(d,u,`${m}/${a}`,{method:r,headers:{Authorization:`Bearer ${e.partnerKey}`},body:c});if(!t.ok)throw new f(0,t.kind);if(t.status<200||t.status>=300)throw new f(t.status,W(t.json,t.status,k));return{status:t.status,json:t.json}}let l=r=>new f(r,"bad_response");function y(r){if(typeof r!="string"||!U.test(r))throw new f(400,"invalid_contact_ref");return r}return{async upsertWorkspace(r,a){let c=o(r),{status:t,json:s}=await i("PUT",c,a);if(!C(s))throw l(t);let n=s;if(n.created===!0){let p=n.embed_app_secret;if(typeof p!="string"||!p)throw l(t);return{...h(n),created:!0,embedAppSecret:p}}if(n.created===!1)return{...h(n),created:!1};throw l(t)},async getWorkspace(r){let a=o(r);try{let{status:c,json:t}=await i("GET",a);if(!C(t)||typeof t.state!="string")throw l(c);return{...h(t),state:t.state}}catch(c){if(c instanceof f&&c.status===404)return null;throw c}},async updateWorkspace(r,a){let c=o(r),t={};a.enabled!==void 0&&(t.enabled=a.enabled),a.name!==void 0&&(t.name=a.name);let{status:s,json:n}=await i("PATCH",c,t);if(!C(n))throw l(s);return h(n)},async rotateWorkspaceSecret(r){let a=o(r),{status:c,json:t}=await i("POST",`${a}/rotate-secret`),s=t;if(!g(t)||typeof s?.embed_app_id!="string"||typeof s.embed_app_secret!="string"||!s.embed_app_secret)throw l(c);return{embedAppId:s.embed_app_id,embedAppSecret:s.embed_app_secret}},async upsertContact(r,a,c){let t=o(r),s=y(a),{status:n,json:p}=await i("PUT",`${t}/contacts/${encodeURIComponent(s)}`,c);if(!g(p)||!g(p.contact)||typeof p.created!="boolean"||typeof p.consent_applied!="boolean")throw l(n);return p},async eraseContact(r,a){let c=o(r),t=y(a);try{let{status:s,json:n}=await i("DELETE",`${c}/contacts/${encodeURIComponent(t)}`);if(!g(n)||n.erased!==!0||typeof n.contact_id!="string")throw l(s);return n}catch(s){if(s instanceof f&&s.status===404)return null;throw s}},async listContactChanges(r,a={}){let c=o(r),{since:t,cursor:s,limit:n}=a;if(n!==void 0&&(!Number.isInteger(n)||n<1||n>$))throw new f(400,"invalid_limit");let p=new URLSearchParams;t!==void 0&&p.set("since",t),s!==void 0&&p.set("cursor",s),n!==void 0&&p.set("limit",String(n));let w=p.toString(),{status:A,json:P}=await i("GET",`${c}/contacts/changes${w?`?${w}`:""}`);if(!g(P)||!Array.isArray(P.items)||!(P.next_cursor===null||typeof P.next_cursor=="string"))throw l(A);return P}}}export{$ as CONTACT_CHANGES_MAX_LIMIT,U as CONTACT_REF_PATTERN,f as CrmPartnerError,S as EXTERNAL_REF_PATTERN,I as createCrmPartnerClient};
2
+ //# sourceMappingURL=partner.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/server-http.ts","../src/partner.ts"],"sourcesContent":["/**\n * Internal HTTP helper for the server-side `partner` entry point. Not part of the\n * public API (no package export points here).\n *\n * It never puts a request header, a request body or a response body into an\n * error: callers get the HTTP status, a short sanitized error code, or a\n * transport failure kind, and nothing else.\n */\n\nexport type FetchLike = typeof fetch;\n\nexport const DEFAULT_TIMEOUT_MS = 15_000;\n\nexport type Transport =\n | { ok: true; status: number; json: unknown }\n | { ok: false; kind: 'timeout' | 'network' };\n\n/** Strip trailing slashes and a trailing `/api`, so callers can pass either form. */\nexport function normalizeBase(crmBaseUrl: string): string {\n return crmBaseUrl.replace(/\\/+$/, '').replace(/\\/api$/, '');\n}\n\nexport function resolveFetch(fetchImpl: FetchLike | undefined, who: string): FetchLike {\n const f = fetchImpl ?? globalThis.fetch;\n if (typeof f !== 'function') {\n throw new Error(`${who}: no fetch implementation available. Pass \\`fetch\\` explicitly.`);\n }\n return f;\n}\n\n/**\n * One request with a hard timeout covering headers AND body. Returns the parsed\n * JSON (null when the body is empty or not JSON) or a transport failure kind.\n */\nexport async function sendJson(\n fetchImpl: FetchLike,\n timeoutMs: number,\n url: string,\n init: { method: string; headers: Record<string, string>; body?: unknown },\n): Promise<Transport> {\n const controller = new AbortController();\n let timedOut = false;\n const timer = setTimeout(() => {\n timedOut = true;\n controller.abort();\n }, timeoutMs);\n try {\n const headers: Record<string, string> = { Accept: 'application/json', ...init.headers };\n const hasBody = init.body !== undefined;\n if (hasBody) headers['Content-Type'] = 'application/json';\n const res = await fetchImpl(url, {\n method: init.method,\n headers,\n body: hasBody ? JSON.stringify(init.body) : undefined,\n signal: controller.signal,\n });\n const json: unknown = await res.json().catch(() => null);\n if (timedOut) return { ok: false, kind: 'timeout' };\n return { ok: true, status: res.status, json };\n } catch {\n return { ok: false, kind: timedOut ? 'timeout' : 'network' };\n } finally {\n clearTimeout(timer);\n }\n}\n\nconst SAFE_CODE = /^[A-Za-z0-9_.:-]{1,60}$/;\n\n/**\n * A short machine code from an error body, or `HTTP_<status>`. Accepts\n * `{ error: { code } }`, `{ error: \"code\" }` and `{ code }`. A value that is not\n * a short identifier (a sentence, a long string) or that contains one of the\n * `redact` strings (credentials) is dropped, so a code is always safe to log.\n */\nexport function errorCodeFrom(json: unknown, status: number, redact: readonly string[]): string {\n const fallback = `HTTP_${status}`;\n const pick = (v: unknown): string | null => {\n if (typeof v !== 'string' || !SAFE_CODE.test(v)) return null;\n return redact.some((r) => r && v.includes(r)) ? null : v;\n };\n if (json && typeof json === 'object') {\n const o = json as Record<string, unknown>;\n const err = o.error;\n return (\n pick(o.code)\n ?? pick(err)\n ?? (err && typeof err === 'object' ? pick((err as Record<string, unknown>).code) : null)\n ?? fallback\n );\n }\n return fallback;\n}\n\nexport const isRecord = (v: unknown): v is Record<string, unknown> =>\n typeof v === 'object' && v !== null && !Array.isArray(v);\n","/**\n * 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"],"mappings":"AAkBO,SAASA,EAAcC,EAA4B,CACxD,OAAOA,EAAW,QAAQ,OAAQ,EAAE,EAAE,QAAQ,SAAU,EAAE,CAC5D,CAEO,SAASC,EAAaC,EAAkCC,EAAwB,CACrF,IAAMC,EAAIF,GA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AAQ,KAAAgC,CAAK,EAAI,MAAMX,EAAK,MAAO,GAAGU,CAAG,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":["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","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"]}