@first-to-fly/crm-sdk 1.4.2 → 1.4.3
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/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,eAAA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AAe,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,IAAMlB,EAAS,OAAQkB,GAA8B,QAAW,SAC3DA,EAA2B,OAC5B,IACEjB,EAAQiB,GAA2B,MAAQ,eACjD,OAAOH,EAAa,CAAE,MAAOd,CAAK,EAAGD,CAAM,CAC7C,CACA,GAAI,CAACiB,EAAM,OAAOF,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMI,EAAU,MAAMtB,EACpB,CAAE,MAAOa,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAO,CAAK,EACrD,CAAE,WAAYP,EAAK,WAAY,MAAOA,EAAK,KAAM,CACnD,EACA,OAAOK,EAAaI,EAAS,GAAG,CAClC,OAASD,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","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,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,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AAM,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,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,E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ACA,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]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AAMa,CAAI,CACxD,CACA,OAAOT,EAAeS,GAAM,MAAQ,CAAC,CAAC,CACxC,CAoBA,IAAME,EAAe,CAACF,EAAed,IACnC,IAAI,SAAS,KAAK,UAAUc,CAAI,EAAG,CACjC,OAAAd,EACA,QAAS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,EAyBI,SAASiB,EACdN,EACqC,CACrC,MAAO,OAAOO,GAAoC,CAChD,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMR,EAAK,aAAaO,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMC,EAAaD,GAA8B,OAC3CpB,EAAS,OAAOqB,GAAc,SAAWA,EAAY,IACrDpB,EAAQmB,GAA2B,MAAQ,eAIjD,OAAI,OAAOC,GAAc,UACvB,QAAQ,MAAM,uEAAwED,CAAG,EAEpFJ,EAAa,CAAE,MAAOf,CAAK,EAAGD,CAAM,CAC7C,CAGA,GAAI,CAACmB,EAAM,OAAOH,EAAa,CAAE,MAAO,cAAe,EAAG,GAAG,EAE7D,GAAI,CACF,IAAMM,EAAU,MAAMb,EACpB,CAAE,MAAOE,EAAK,MAAO,UAAWA,EAAK,UAAW,KAAAQ,CAAK,EACrD,CAAE,WAAYR,EAAK,WAAY,MAAOA,EAAK,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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-to-fly/crm-sdk",
|
|
3
|
-
"version": "1.4.
|
|
3
|
+
"version": "1.4.3",
|
|
4
4
|
"description": "CRM SDK — embed third-party apps inside the CRM, or embed the CRM inside your own SaaS (proxy-free, signed-assertion or API-key auth)",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.cjs",
|