@first-to-fly/crm-sdk 1.4.2 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +84 -1
- package/dist/api.cjs +1 -1
- package/dist/api.cjs.map +1 -1
- package/dist/api.d.cts +5 -711
- package/dist/api.d.ts +5 -711
- package/dist/api.js +1 -1
- package/dist/api.js.map +1 -1
- package/dist/crm-contracts-DLY_TSwy.d.cts +1012 -0
- package/dist/crm-contracts-DLY_TSwy.d.ts +1012 -0
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/dist/partner.cjs +2 -0
- package/dist/partner.cjs.map +1 -0
- package/dist/partner.d.cts +149 -0
- package/dist/partner.d.ts +149 -0
- package/dist/partner.js +2 -0
- package/dist/partner.js.map +1 -0
- package/package.json +11 -1
package/dist/embed-server.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var
|
|
1
|
+
"use strict";var p=Object.defineProperty;var m=Object.getOwnPropertyDescriptor;var l=Object.getOwnPropertyNames;var g=Object.prototype.hasOwnProperty;var f=(e,r)=>{for(var s in r)p(e,s,{get:r[s],enumerable:!0})},h=(e,r,s,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let n of l(r))!g.call(e,n)&&n!==s&&p(e,n,{get:()=>r[n],enumerable:!(t=m(r,n))||t.enumerable});return e};var S=e=>h(p({},"__esModule",{value:!0}),e);var w={};f(w,{CrmExchangeError:()=>i,createCrmSessionHandler:()=>E,createEmbedSessionWithKey:()=>u});module.exports=S(w);var i=class extends Error{constructor(s,t,n,o){super(s);this.status=t;this.code=n;this.detail=o;this.name="CrmExchangeError"}},y=e=>e.replace(/\/$/,"");function b(e){let r=e.access_token,s=e.workspace?.id;if(typeof r!="string"||r.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof s!="string"||s.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:r,expiresIn:e.expires_in,workspaceId:s,user:e.user,role:e.role}}async function u(e,r){let s=r.fetch??fetch,t=`${y(r.crmBaseUrl)}/api/auth/exchange`,n=await s(t,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let a=o?.error?.code??`HTTP_${n.status}`,d=o?.error?.message??"CRM exchange failed";throw new i(d,n.status,a,o)}return b(o?.data??{})}var c=(e,r)=>new Response(JSON.stringify(e),{status:r,headers:{"content-type":"application/json"}});function E(e){return async r=>{let s;try{s=await e.authenticate(r)}catch(t){let n=t?.status,o=typeof n=="number"?n:401,a=t?.code??"UNAUTHORIZED";return typeof n!="number"&&console.error("[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly",t),c({error:a},o)}if(!s)return c({error:"UNAUTHORIZED"},401);try{let t=await u({appId:e.appId,appSecret:e.appSecret,user:s},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return c(t,200)}catch(t){return t instanceof i?c({error:t.code},t.status):(console.error("[crm-sdk] createCrmSessionHandler: session exchange failed",t),c({error:"CRM_SESSION_FAILED"},502))}}}0&&(module.exports={CrmExchangeError,createCrmSessionHandler,createEmbedSessionWithKey});
|
|
2
2
|
//# sourceMappingURL=embed-server.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const status = typeof (err as { status?: unknown })?.status === 'number'\n ? (err as { status: number }).status\n : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n return jsonResponse({ error: code }, status);\n }\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAAAC,EAAAD,EAAA,sBAAAE,EAAA,4BAAAC,EAAA,8BAAAC,IAAA,eAAAC,EAAAL,GAuBO,IAAME,EAAN,cAA+B,KAAM,CAC1C,YACEI,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA6CMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAQxE,SAASC,EAAeC,EAAyC,CAC/D,IAAMC,EAAcD,EAAK,aACnBE,EAAcF,EAAK,WAAW,GACpC,GAAI,OAAOC,GAAgB,UAAYA,EAAY,SAAW,EAC5D,MAAM,IAAIZ,EAAiB,oCAAqC,IAAK,qBAAsBW,CAAI,EAEjG,GAAI,OAAOE,GAAgB,UAAYA,EAAY,SAAW,EAC5D,MAAM,IAAIb,EAAiB,oCAAqC,IAAK,qBAAsBW,CAAI,EAEjG,MAAO,CACL,YAAAC,EACA,UAAWD,EAAK,WAChB,YAAAE,EACA,KAAMF,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAkBA,eAAsBT,EACpBY,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBN,EAAM,GAAGD,EAAkBO,EAAK,UAAU,CAAC,qBAC3CE,EAAM,MAAMD,EAAQP,EAAK,CAC7B,OA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QAAQ,MAAM,6DAA8DA,CAAG,EACxEH,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["embed_server_exports","__export","CrmExchangeError","createCrmSessionHandler","createEmbedSessionWithKey","__toCommonJS","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","input","opts","doFetch","res","body","msg","jsonResponse","req","user","err","session"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const rawStatus = (err as { status?: unknown })?.status;\n const status = typeof rawStatus === 'number' ? rawStatus : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n // A throw with no explicit numeric status is more likely a real fault (DB\n // timeout, bug in the callback) than an auth rejection — log it so it isn't\n // hidden behind a misleading 401, mirroring the exchange handler below.\n if (typeof rawStatus !== 'number') {\n console.error('[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly', err);\n }\n return jsonResponse({ error: code }, status);\n }\n // A falsy return is also treated as unauthenticated (defensive: a partner whose\n // lookup returns null/undefined yields a clean 401, not a downstream 502).\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"yaAAA,IAAAA,EAAA,GAA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ACA,OAAOR,EAAeQ,GAAM,MAAQ,CAAC,CAAC,CACxC,CAoBA,IAAME,EAAe,CAACF,EAAeb,IACnC,IAAI,SAAS,KAAK,UAAUa,CAAI,EAAG,CACjC,OAAAb,EACA,QAAS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,EAyBI,SAASJ,EACdc,EACqC,CACrC,MAAO,OAAOM,GAAoC,CAChD,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMP,EAAK,aAAaM,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMC,EAAaD,GAA8B,OAC3ClB,EAAS,OAAOmB,GAAc,SAAWA,EAAY,IACrDlB,EAAQiB,GAA2B,MAAQ,eAIjD,OAAI,OAAOC,GAAc,UACvB,QAAQ,MAAM,uEAAwED,CAAG,EAEpFH,EAAa,CAAE,MAAOd,CAAK,EAAGD,CAAM,CAC7C,CAGA,GAAI,CAACiB,EAAM,OAAOF,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMK,EAAU,MAAMvB,EACpB,CAAE,MAAOa,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAO,CAAK,EACrD,CAAE,WAAYP,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaK,EAAS,GAAG,CAClC,OAASF,EAAK,CACZ,OAAIA,aAAevB,EACVoB,EAAa,CAAE,MAAOG,EAAI,IAAK,EAAGA,EAAI,MAAM,GAIrD,QAAQ,MAAM,6DAA8DA,CAAG,EACxEH,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["embed_server_exports","__export","CrmExchangeError","createCrmSessionHandler","createEmbedSessionWithKey","__toCommonJS","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","input","opts","doFetch","res","body","msg","jsonResponse","req","user","err","rawStatus","session"]}
|
package/dist/embed-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var i=class extends Error{constructor(t,r,n,o){super(t);this.status=r;this.code=n;this.detail=o;this.name="CrmExchangeError"}},u=e=>e.replace(/\/$/,"");function d(e){let s=e.access_token,t=e.workspace?.id;if(typeof s!="string"||s.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof t!="string"||t.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:s,expiresIn:e.expires_in,workspaceId:t,user:e.user,role:e.role}}async function m(e,s){let t=s.fetch??fetch,r=`${u(s.crmBaseUrl)}/api/auth/exchange`,n=await t(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let
|
|
1
|
+
var i=class extends Error{constructor(t,r,n,o){super(t);this.status=r;this.code=n;this.detail=o;this.name="CrmExchangeError"}},u=e=>e.replace(/\/$/,"");function d(e){let s=e.access_token,t=e.workspace?.id;if(typeof s!="string"||s.length===0)throw new i("CRM response missing access_token",502,"MALFORMED_RESPONSE",e);if(typeof t!="string"||t.length===0)throw new i("CRM response missing workspace id",502,"MALFORMED_RESPONSE",e);return{accessToken:s,expiresIn:e.expires_in,workspaceId:t,user:e.user,role:e.role}}async function m(e,s){let t=s.fetch??fetch,r=`${u(s.crmBaseUrl)}/api/auth/exchange`,n=await t(r,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({app_id:e.appId,app_secret:e.appSecret,user:e.user})}),o=await n.json().catch(()=>({}));if(!n.ok){let a=o?.error?.code??`HTTP_${n.status}`,p=o?.error?.message??"CRM exchange failed";throw new i(p,n.status,a,o)}return d(o?.data??{})}var c=(e,s)=>new Response(JSON.stringify(e),{status:s,headers:{"content-type":"application/json"}});function l(e){return async s=>{let t;try{t=await e.authenticate(s)}catch(r){let n=r?.status,o=typeof n=="number"?n:401,a=r?.code??"UNAUTHORIZED";return typeof n!="number"&&console.error("[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly",r),c({error:a},o)}if(!t)return c({error:"UNAUTHORIZED"},401);try{let r=await m({appId:e.appId,appSecret:e.appSecret,user:t},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return c(r,200)}catch(r){return r instanceof i?c({error:r.code},r.status):(console.error("[crm-sdk] createCrmSessionHandler: session exchange failed",r),c({error:"CRM_SESSION_FAILED"},502))}}}export{i as CrmExchangeError,l as createCrmSessionHandler,m as createEmbedSessionWithKey};
|
|
2
2
|
//# sourceMappingURL=embed-server.js.map
|
package/dist/embed-server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const status = typeof (err as { status?: unknown })?.status === 'number'\n ? (err as { status: number }).status\n : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n return jsonResponse({ error: code }, status);\n }\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"AAuBO,IAAMA,EAAN,cAA+B,KAAM,CAC1C,YACEC,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA6CMC,EAAq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,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMR,EAAK,aAAaO,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMpB,EAAS,OAAQoB,GAA8B,QAAW,SAC3DA,EAA2B,OAC5B,IACEnB,EAAQmB,GAA2B,MAAQ,eACjD,OAAOJ,EAAa,CAAE,MAAOf,CAAK,EAAGD,CAAM,CAC7C,CACA,GAAI,CAACmB,EAAM,OAAOH,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMK,EAAU,MAAMZ,EACpB,CAAE,MAAOE,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAQ,CAAK,EACrD,CAAE,WAAYR,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaK,EAAS,GAAG,CAClC,OAASD,EAAK,CACZ,OAAIA,aAAetB,EACVkB,EAAa,CAAE,MAAOI,EAAI,IAAK,EAAGA,EAAI,MAAM,GAIrD,QAAQ,MAAM,6DAA8DA,CAAG,EACxEJ,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["CrmExchangeError","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","createEmbedSessionWithKey","input","opts","doFetch","res","body","msg","jsonResponse","createCrmSessionHandler","req","user","err","session"]}
|
|
1
|
+
{"version":3,"sources":["../src/embed-server.ts"],"sourcesContent":["/**\n * CRM Embed Server SDK (server side).\n *\n * Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server\n * POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`\n * to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM\n * iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).\n *\n * Two ways to use it:\n * - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`\n * endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).\n * - {@link createEmbedSessionWithKey} — the underlying call, if you want to\n * wire the endpoint yourself.\n *\n * Works in Node and Bun (or any environment with a global `fetch`). No crypto /\n * keypair / `jose` dependency — auth is a plain credential exchange.\n *\n * @packageDocumentation\n */\n\n// ─── Error class ─────────────────────────────────────────────────────────────\n\n/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */\nexport class CrmExchangeError extends Error {\n constructor(\n message: string,\n public readonly status: number,\n public readonly code: string,\n public readonly detail?: unknown,\n ) {\n super(message);\n this.name = 'CrmExchangeError';\n }\n}\n\n// ─── Types ───────────────────────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n /** Stable id for this user in YOUR system. */\n id: string;\n /** Verified email — the CRM matches/links the user by this. */\n email: string;\n /** Requested role; the CRM caps it to the install's configured max role. */\n role: 'member' | 'admin';\n /** Optional display name for first-time provisioning. */\n name?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatar_url?: string;\n}\n\n/** Input for {@link createEmbedSessionWithKey}. */\nexport interface CreateEmbedSessionWithKeyInput {\n appId: string;\n appSecret: string;\n user: EmbedUser;\n}\n\n/** The CRM session returned by the exchange. */\nexport interface EmbedSession {\n /** Short-lived CRM bearer to hand to the iframe. */\n accessToken: string;\n /** TTL hint in seconds. */\n expiresIn?: number;\n /**\n * The CRM workspace the user was provisioned into. Always present on a\n * successful exchange (validated in `toEmbedSession`), so the browser can\n * build the embed URL without a further check.\n */\n workspaceId: string;\n /** The provisioned CRM user. */\n user?: { id: string; email: string; full_name?: string };\n /** The effective role the CRM granted (may be capped below the requested one). */\n role?: string;\n}\n\n// ─── Core exchange ───────────────────────────────────────────────────────────\n\nconst trimTrailingSlash = (url: string): string => url.replace(/\\/$/, '');\n\n/**\n * Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession.\n * Validates the two fields the type promises as non-optional so a malformed 2xx\n * fails loudly here (the one construction boundary) instead of surfacing later\n * as an `/embed/undefined` URL or an undefined bearer in the iframe.\n */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n const accessToken = data.access_token;\n const workspaceId = data.workspace?.id;\n if (typeof accessToken !== 'string' || accessToken.length === 0) {\n throw new CrmExchangeError('CRM response missing access_token', 502, 'MALFORMED_RESPONSE', data);\n }\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new CrmExchangeError('CRM response missing workspace id', 502, 'MALFORMED_RESPONSE', data);\n }\n return {\n accessToken,\n expiresIn: data.expires_in,\n workspaceId,\n user: data.user,\n role: data.role,\n };\n}\n\n/**\n * Exchange app credentials + user identity for a short-lived CRM bearer.\n *\n * POSTs `{ app_id, app_secret, user }` to `${crmBaseUrl}/api/auth/exchange`\n * and maps the CRM response to an {@link EmbedSession}. On non-2xx, throws\n * {@link CrmExchangeError} with `.status` and `.code`.\n *\n * @example\n * ```typescript\n * const session = await createEmbedSessionWithKey(\n * { appId: process.env.CRM_APP_ID!, appSecret: process.env.CRM_APP_SECRET!, user },\n * { crmBaseUrl: process.env.CRM_BASE_URL! },\n * );\n * // { accessToken, expiresIn, workspaceId, user, role }\n * ```\n */\nexport async function createEmbedSessionWithKey(\n input: CreateEmbedSessionWithKeyInput,\n opts: { crmBaseUrl: string; fetch?: typeof fetch },\n): Promise<EmbedSession> {\n const doFetch = opts.fetch ?? fetch;\n const url = `${trimTrailingSlash(opts.crmBaseUrl)}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({\n app_id: input.appId,\n app_secret: input.appSecret,\n user: input.user,\n }),\n });\n const body = await res.json().catch(() => ({}));\n if (!res.ok) {\n const code = body?.error?.code ?? `HTTP_${res.status}`;\n const msg = body?.error?.message ?? 'CRM exchange failed';\n throw new CrmExchangeError(msg, res.status, code, body);\n }\n return toEmbedSession(body?.data ?? {});\n}\n\n// ─── Ready-made session endpoint ─────────────────────────────────────────────\n\n/** Options for {@link createCrmSessionHandler}. */\nexport interface CrmSessionHandlerOptions {\n appId: string;\n appSecret: string;\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /**\n * Resolve the signed-in user for a request. Return an {@link EmbedUser} to\n * proceed, or throw to reject. A thrown error with a numeric `.status` uses\n * that status; anything else becomes `401`.\n */\n authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\nconst jsonResponse = (body: unknown, status: number): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { 'content-type': 'application/json' },\n });\n\n/**\n * Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it\n * into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,\n * Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler\n * or call {@link createEmbedSessionWithKey} directly.)\n *\n * It authenticates the request via your `authenticate` callback, runs the\n * credential exchange, and returns the {@link EmbedSession} as JSON — exactly the\n * shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:\n * a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a\n * failed `authenticate` returns its `.status` (or `401`).\n *\n * @example\n * ```typescript\n * // app/api/crm/session/route.ts (Next.js)\n * export const POST = createCrmSessionHandler({\n * appId: process.env.CRM_APP_ID!,\n * appSecret: process.env.CRM_APP_SECRET!,\n * crmBaseUrl: process.env.CRM_BASE_URL!,\n * authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401\n * });\n * ```\n */\nexport function createCrmSessionHandler(\n opts: CrmSessionHandlerOptions,\n): (req: Request) => Promise<Response> {\n return async (req: Request): Promise<Response> => {\n let user: EmbedUser;\n try {\n user = await opts.authenticate(req);\n } catch (err) {\n const rawStatus = (err as { status?: unknown })?.status;\n const status = typeof rawStatus === 'number' ? rawStatus : 401;\n const code = (err as { code?: string })?.code ?? 'UNAUTHORIZED';\n // A throw with no explicit numeric status is more likely a real fault (DB\n // timeout, bug in the callback) than an auth rejection — log it so it isn't\n // hidden behind a misleading 401, mirroring the exchange handler below.\n if (typeof rawStatus !== 'number') {\n console.error('[crm-sdk] createCrmSessionHandler: authenticate() threw unexpectedly', err);\n }\n return jsonResponse({ error: code }, status);\n }\n // A falsy return is also treated as unauthenticated (defensive: a partner whose\n // lookup returns null/undefined yields a clean 401, not a downstream 502).\n if (!user) return jsonResponse({ error: 'UNAUTHORIZED' }, 401);\n\n try {\n const session = await createEmbedSessionWithKey(\n { appId: opts.appId, appSecret: opts.appSecret, user },\n { crmBaseUrl: opts.crmBaseUrl, fetch: opts.fetch },\n );\n return jsonResponse(session, 200);\n } catch (err) {\n if (err instanceof CrmExchangeError) {\n return jsonResponse({ error: err.code }, err.status);\n }\n // Unexpected (network failure, misconfig, bug) — don't discard the stack\n // behind a bare 502; log it server-side so the failure is debuggable.\n console.error('[crm-sdk] createCrmSessionHandler: session exchange failed', err);\n return jsonResponse({ error: 'CRM_SESSION_FAILED' }, 502);\n }\n };\n}\n"],"mappings":"AAuBO,IAAMA,EAAN,cAA+B,KAAM,CAC1C,YACEC,EACgBC,EACAC,EACAC,EAChB,CACA,MAAMH,CAAO,EAJG,YAAAC,EACA,UAAAC,EACA,YAAAC,EAGhB,KAAK,KAAO,kBACd,CACF,EA6CMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAQxE,SAASC,EAAeC,EAAyC,CAC/D,IAAMC,EAAcD,EAAK,aACnBE,EAAcF,EAAK,WAAW,GACpC,GAAI,OAAOC,GAAgB,UAAYA,EAAY,SAAW,EAC5D,MAAM,IAAIT,EAAiB,oCAAqC,IAAK,qBAAsBQ,CAAI,EAEjG,GAAI,OAAOE,GAAgB,UAAYA,EAAY,SAAW,EAC5D,MAAM,IAAIV,EAAiB,oCAAqC,IAAK,qBAAsBQ,CAAI,EAEjG,MAAO,CACL,YAAAC,EACA,UAAWD,EAAK,WAChB,YAAAE,EACA,KAAMF,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAkBA,eAAsBG,EACpBC,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBP,EAAM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KAAM,CACnD,EACA,OAAOK,EAAaM,EAAS,GAAG,CAClC,OAASF,EAAK,CACZ,OAAIA,aAAetB,EACVkB,EAAa,CAAE,MAAOI,EAAI,IAAK,EAAGA,EAAI,MAAM,GAIrD,QAAQ,MAAM,6DAA8DA,CAAG,EACxEJ,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,EAC1D,CACF,CACF","names":["CrmExchangeError","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","accessToken","workspaceId","createEmbedSessionWithKey","input","opts","doFetch","res","body","msg","jsonResponse","createCrmSessionHandler","req","user","err","rawStatus","session"]}
|
package/dist/partner.cjs
ADDED
|
@@ -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 /** Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. */\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,EAA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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,149 @@
|
|
|
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-DLY_TSwy.cjs';
|
|
2
|
+
export { y as ContactChangesQuery } from './crm-contracts-DLY_TSwy.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
|
+
/** Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. */
|
|
113
|
+
upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
|
|
114
|
+
/** Provisioning status, or `null` when the CRM does not know this ref (404). */
|
|
115
|
+
getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
|
|
116
|
+
/** Enable/disable the embed app or rename the workspace. At least one field is required. */
|
|
117
|
+
updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
|
|
118
|
+
/** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
|
|
119
|
+
rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
|
|
120
|
+
/**
|
|
121
|
+
* Idempotent upsert of the contact for `contactRef` (your own key for the person) in the
|
|
122
|
+
* workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`
|
|
123
|
+
* only applies when its `recorded_at` is newer than the stored one and the parent has
|
|
124
|
+
* not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file
|
|
125
|
+
* the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the
|
|
126
|
+
* workspace is disabled and 404 for an unknown workspace.
|
|
127
|
+
*/
|
|
128
|
+
upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;
|
|
129
|
+
/**
|
|
130
|
+
* PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.
|
|
131
|
+
* Resolves `null` when the CRM has no contact for this ref (404: never synced, or already
|
|
132
|
+
* erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it
|
|
133
|
+
* also resolves `null`; use `getWorkspace` to tell them apart.
|
|
134
|
+
*/
|
|
135
|
+
eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
|
|
136
|
+
/**
|
|
137
|
+
* One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
|
|
138
|
+
* for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
|
|
139
|
+
* to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.
|
|
140
|
+
*/
|
|
141
|
+
listContactChanges(externalRef: string, query?: {
|
|
142
|
+
since?: string;
|
|
143
|
+
cursor?: string;
|
|
144
|
+
limit?: number;
|
|
145
|
+
}): Promise<ContactChanges>;
|
|
146
|
+
}
|
|
147
|
+
declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
|
|
148
|
+
|
|
149
|
+
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,149 @@
|
|
|
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-DLY_TSwy.js';
|
|
2
|
+
export { y as ContactChangesQuery } from './crm-contracts-DLY_TSwy.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
|
+
/** Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. */
|
|
113
|
+
upsertWorkspace(externalRef: string, body: PartnerWorkspaceUpsertBody): Promise<PartnerWorkspaceUpsertResult>;
|
|
114
|
+
/** Provisioning status, or `null` when the CRM does not know this ref (404). */
|
|
115
|
+
getWorkspace(externalRef: string): Promise<PartnerWorkspaceDetail | null>;
|
|
116
|
+
/** Enable/disable the embed app or rename the workspace. At least one field is required. */
|
|
117
|
+
updateWorkspace(externalRef: string, patch: PartnerWorkspacePatchBody): Promise<PartnerWorkspace>;
|
|
118
|
+
/** Replace the embed app secret. Throws a 404 error for an unknown or not-yet-active ref. */
|
|
119
|
+
rotateWorkspaceSecret(externalRef: string): Promise<PartnerRotatedSecret>;
|
|
120
|
+
/**
|
|
121
|
+
* Idempotent upsert of the contact for `contactRef` (your own key for the person) in the
|
|
122
|
+
* workspace: finds it by ref (then phone, then email) or creates it. `whatsapp_consent`
|
|
123
|
+
* only applies when its `recorded_at` is newer than the stored one and the parent has
|
|
124
|
+
* not replied STOP (`consent_applied` says whether it did). `team_ref` + `team_name` file
|
|
125
|
+
* the contact under your team, created if new. Fails with 409 `WORKSPACE_DISABLED` while the
|
|
126
|
+
* workspace is disabled and 404 for an unknown workspace.
|
|
127
|
+
*/
|
|
128
|
+
upsertContact(externalRef: string, contactRef: string, body: ContactRefUpsertBody): Promise<ContactRefUpsertResult>;
|
|
129
|
+
/**
|
|
130
|
+
* PDPA erasure: overwrites the contact's personal data, soft-deletes it and removes its refs.
|
|
131
|
+
* Resolves `null` when the CRM has no contact for this ref (404: never synced, or already
|
|
132
|
+
* erased). Works while the workspace is disabled. An unknown workspace is also a 404, so it
|
|
133
|
+
* also resolves `null`; use `getWorkspace` to tell them apart.
|
|
134
|
+
*/
|
|
135
|
+
eraseContact(externalRef: string, contactRef: string): Promise<PartnerContactEraseResult | null>;
|
|
136
|
+
/**
|
|
137
|
+
* One page of the contacts changes feed (oldest first, includes deleted contacts). Pass `since`
|
|
138
|
+
* for the first page and the returned `next_cursor` as `cursor` until it is null. `limit` is 1
|
|
139
|
+
* to 200 (default 100). Works while the workspace is disabled; an unknown workspace throws 404.
|
|
140
|
+
*/
|
|
141
|
+
listContactChanges(externalRef: string, query?: {
|
|
142
|
+
since?: string;
|
|
143
|
+
cursor?: string;
|
|
144
|
+
limit?: number;
|
|
145
|
+
}): Promise<ContactChanges>;
|
|
146
|
+
}
|
|
147
|
+
declare function createCrmPartnerClient(opts: CrmPartnerClientOptions): CrmPartnerClient;
|
|
148
|
+
|
|
149
|
+
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 };
|
package/dist/partner.js
ADDED
|
@@ -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 /** Idempotent: provisions the workspace for `externalRef`, or resumes/returns it. */\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,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,E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ElB,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"]}
|