@first-to-fly/crm-sdk 1.3.0 → 1.4.1
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 +257 -100
- package/dist/embed-host.cjs +1 -1
- package/dist/embed-host.cjs.map +1 -1
- package/dist/embed-host.d.cts +21 -3
- package/dist/embed-host.d.ts +21 -3
- package/dist/embed-host.js +1 -1
- package/dist/embed-host.js.map +1 -1
- package/dist/embed-react.cjs +2 -0
- package/dist/embed-react.cjs.map +1 -0
- package/dist/embed-react.d.cts +94 -0
- package/dist/embed-react.d.ts +94 -0
- package/dist/embed-react.js +2 -0
- package/dist/embed-react.js.map +1 -0
- package/dist/embed-server.cjs +1 -1
- package/dist/embed-server.cjs.map +1 -1
- package/dist/embed-server.d.cts +58 -80
- package/dist/embed-server.d.ts +58 -80
- package/dist/embed-server.js +1 -1
- package/dist/embed-server.js.map +1 -1
- package/package.json +19 -7
package/dist/embed-server.d.cts
CHANGED
|
@@ -1,29 +1,22 @@
|
|
|
1
|
-
import { JWK } from 'jose';
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* CRM Embed Server SDK (server side).
|
|
5
3
|
*
|
|
6
|
-
* Use this in YOUR SaaS backend to authenticate the embedded CRM.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* POST user identity + your registered `app_id`/`app_secret` to the CRM.
|
|
11
|
-
* Use {@link createEmbedSessionWithKey}. No `jose` required.
|
|
12
|
-
*
|
|
13
|
-
* **Option B — Signed-assertion auth (zero shared-secret):**
|
|
14
|
-
* Mint a short-lived asymmetric (RS256/ES256) assertion server-side and
|
|
15
|
-
* exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or
|
|
16
|
-
* {@link mintCrmAssertion} + {@link exchangeAssertion} separately).
|
|
17
|
-
* Requires the `jose` peer dependency.
|
|
4
|
+
* Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server
|
|
5
|
+
* POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`
|
|
6
|
+
* to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM
|
|
7
|
+
* iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).
|
|
18
8
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
9
|
+
* Two ways to use it:
|
|
10
|
+
* - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`
|
|
11
|
+
* endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).
|
|
12
|
+
* - {@link createEmbedSessionWithKey} — the underlying call, if you want to
|
|
13
|
+
* wire the endpoint yourself.
|
|
21
14
|
*
|
|
22
|
-
* Works in Node and Bun (or any environment with a global `fetch`).
|
|
15
|
+
* Works in Node and Bun (or any environment with a global `fetch`). No crypto /
|
|
16
|
+
* keypair / `jose` dependency — auth is a plain credential exchange.
|
|
23
17
|
*
|
|
24
18
|
* @packageDocumentation
|
|
25
19
|
*/
|
|
26
|
-
|
|
27
20
|
/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
|
|
28
21
|
declare class CrmExchangeError extends Error {
|
|
29
22
|
readonly status: number;
|
|
@@ -33,10 +26,15 @@ declare class CrmExchangeError extends Error {
|
|
|
33
26
|
}
|
|
34
27
|
/** The end-user being embedded into the CRM. */
|
|
35
28
|
interface EmbedUser {
|
|
29
|
+
/** Stable id for this user in YOUR system. */
|
|
36
30
|
id: string;
|
|
31
|
+
/** Verified email — the CRM matches/links the user by this. */
|
|
37
32
|
email: string;
|
|
33
|
+
/** Requested role; the CRM caps it to the install's configured max role. */
|
|
38
34
|
role: 'member' | 'admin';
|
|
35
|
+
/** Optional display name for first-time provisioning. */
|
|
39
36
|
name?: string;
|
|
37
|
+
/** Optional avatar URL for first-time provisioning. */
|
|
40
38
|
avatar_url?: string;
|
|
41
39
|
}
|
|
42
40
|
/** Input for {@link createEmbedSessionWithKey}. */
|
|
@@ -45,13 +43,21 @@ interface CreateEmbedSessionWithKeyInput {
|
|
|
45
43
|
appSecret: string;
|
|
46
44
|
user: EmbedUser;
|
|
47
45
|
}
|
|
48
|
-
/** The CRM session returned by
|
|
46
|
+
/** The CRM session returned by the exchange. */
|
|
49
47
|
interface EmbedSession {
|
|
48
|
+
/** Short-lived CRM bearer to hand to the iframe. */
|
|
50
49
|
accessToken: string;
|
|
50
|
+
/** TTL hint in seconds. */
|
|
51
51
|
expiresIn?: number;
|
|
52
52
|
/** The CRM workspace the user was provisioned into. */
|
|
53
53
|
workspaceId?: string;
|
|
54
|
-
user
|
|
54
|
+
/** The provisioned CRM user. */
|
|
55
|
+
user?: {
|
|
56
|
+
id: string;
|
|
57
|
+
email: string;
|
|
58
|
+
full_name?: string;
|
|
59
|
+
};
|
|
60
|
+
/** The effective role the CRM granted (may be capped below the requested one). */
|
|
55
61
|
role?: string;
|
|
56
62
|
}
|
|
57
63
|
/**
|
|
@@ -74,72 +80,44 @@ declare function createEmbedSessionWithKey(input: CreateEmbedSessionWithKeyInput
|
|
|
74
80
|
crmBaseUrl: string;
|
|
75
81
|
fetch?: typeof fetch;
|
|
76
82
|
}): Promise<EmbedSession>;
|
|
77
|
-
|
|
78
|
-
interface
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
/** PKCS8 PEM private key used to sign assertions. */
|
|
82
|
-
privateKeyPem: string;
|
|
83
|
-
/** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
|
|
84
|
-
publicKeyPem: string;
|
|
85
|
-
/** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
|
|
86
|
-
alg?: CrmEmbedAlg;
|
|
87
|
-
}
|
|
88
|
-
interface CrmAssertionInput {
|
|
89
|
-
/** Stable user id in your system (becomes the CRM external_subject). */
|
|
90
|
-
sub: string;
|
|
91
|
-
/** User email. */
|
|
92
|
-
email: string;
|
|
93
|
-
/** Requested role; the CRM clamps it to the install's configured max_role. */
|
|
94
|
-
requestedRole: 'member' | 'admin';
|
|
95
|
-
/** Your organization id; the CRM resolves the workspace from the org binding. */
|
|
96
|
-
orgId: string;
|
|
97
|
-
/** Optional display name for first-time provisioning. */
|
|
98
|
-
fullName?: string;
|
|
99
|
-
/** Optional avatar URL for first-time provisioning. */
|
|
100
|
-
avatarUrl?: string;
|
|
101
|
-
}
|
|
102
|
-
/** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
|
|
103
|
-
interface CrmEmbedSession {
|
|
104
|
-
accessToken: string;
|
|
105
|
-
expiresIn?: number;
|
|
106
|
-
/** The CRM workspace the user was provisioned into (resolved from org_id). */
|
|
107
|
-
workspaceId?: string;
|
|
108
|
-
user?: {
|
|
109
|
-
id: string;
|
|
110
|
-
email: string;
|
|
111
|
-
full_name?: string;
|
|
112
|
-
};
|
|
113
|
-
role?: string;
|
|
114
|
-
}
|
|
115
|
-
interface ExchangeOptions {
|
|
83
|
+
/** Options for {@link createCrmSessionHandler}. */
|
|
84
|
+
interface CrmSessionHandlerOptions {
|
|
85
|
+
appId: string;
|
|
86
|
+
appSecret: string;
|
|
116
87
|
/** CRM exchange base URL, e.g. "https://api.crm.example.com". */
|
|
117
88
|
crmBaseUrl: string;
|
|
89
|
+
/**
|
|
90
|
+
* Resolve the signed-in user for a request. Return an {@link EmbedUser} to
|
|
91
|
+
* proceed, or throw to reject. A thrown error with a numeric `.status` uses
|
|
92
|
+
* that status; anything else becomes `401`.
|
|
93
|
+
*/
|
|
94
|
+
authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;
|
|
118
95
|
/** Override fetch (tests / custom agents). Defaults to global fetch. */
|
|
119
96
|
fetch?: typeof fetch;
|
|
120
97
|
}
|
|
121
|
-
/** Test/dev only: clear the memoized keys. */
|
|
122
|
-
declare function resetCrmEmbedKeys(): void;
|
|
123
98
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
99
|
+
* Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it
|
|
100
|
+
* into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,
|
|
101
|
+
* Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler
|
|
102
|
+
* or call {@link createEmbedSessionWithKey} directly.)
|
|
126
103
|
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
*
|
|
139
|
-
*
|
|
104
|
+
* It authenticates the request via your `authenticate` callback, runs the
|
|
105
|
+
* credential exchange, and returns the {@link EmbedSession} as JSON — exactly the
|
|
106
|
+
* shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:
|
|
107
|
+
* a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a
|
|
108
|
+
* failed `authenticate` returns its `.status` (or `401`).
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* // app/api/crm/session/route.ts (Next.js)
|
|
113
|
+
* export const POST = createCrmSessionHandler({
|
|
114
|
+
* appId: process.env.CRM_APP_ID!,
|
|
115
|
+
* appSecret: process.env.CRM_APP_SECRET!,
|
|
116
|
+
* crmBaseUrl: process.env.CRM_BASE_URL!,
|
|
117
|
+
* authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
140
120
|
*/
|
|
141
|
-
declare function
|
|
142
|
-
/** Mint + exchange in one call — the typical "give me a CRM session" helper. */
|
|
143
|
-
declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
121
|
+
declare function createCrmSessionHandler(opts: CrmSessionHandlerOptions): (req: Request) => Promise<Response>;
|
|
144
122
|
|
|
145
|
-
export { type CreateEmbedSessionWithKeyInput,
|
|
123
|
+
export { type CreateEmbedSessionWithKeyInput, CrmExchangeError, type CrmSessionHandlerOptions, type EmbedSession, type EmbedUser, createCrmSessionHandler, createEmbedSessionWithKey };
|
package/dist/embed-server.d.ts
CHANGED
|
@@ -1,29 +1,22 @@
|
|
|
1
|
-
import { JWK } from 'jose';
|
|
2
|
-
|
|
3
1
|
/**
|
|
4
2
|
* CRM Embed Server SDK (server side).
|
|
5
3
|
*
|
|
6
|
-
* Use this in YOUR SaaS backend to authenticate the embedded CRM.
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* POST user identity + your registered `app_id`/`app_secret` to the CRM.
|
|
11
|
-
* Use {@link createEmbedSessionWithKey}. No `jose` required.
|
|
12
|
-
*
|
|
13
|
-
* **Option B — Signed-assertion auth (zero shared-secret):**
|
|
14
|
-
* Mint a short-lived asymmetric (RS256/ES256) assertion server-side and
|
|
15
|
-
* exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or
|
|
16
|
-
* {@link mintCrmAssertion} + {@link exchangeAssertion} separately).
|
|
17
|
-
* Requires the `jose` peer dependency.
|
|
4
|
+
* Use this in YOUR SaaS backend to authenticate the embedded CRM. Your server
|
|
5
|
+
* POSTs the signed-in user's identity plus your registered `app_id`/`app_secret`
|
|
6
|
+
* to the CRM and gets back a short-lived CRM bearer. Hand that bearer to the CRM
|
|
7
|
+
* iframe via `embed-host` / `embed-react` (see ./embed-host, ./embed-react).
|
|
18
8
|
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
9
|
+
* Two ways to use it:
|
|
10
|
+
* - {@link createCrmSessionHandler} — a ready-made Web `(Request) => Response`
|
|
11
|
+
* endpoint (Next route handlers, Hono, Bun.serve, Deno, Cloudflare Workers).
|
|
12
|
+
* - {@link createEmbedSessionWithKey} — the underlying call, if you want to
|
|
13
|
+
* wire the endpoint yourself.
|
|
21
14
|
*
|
|
22
|
-
* Works in Node and Bun (or any environment with a global `fetch`).
|
|
15
|
+
* Works in Node and Bun (or any environment with a global `fetch`). No crypto /
|
|
16
|
+
* keypair / `jose` dependency — auth is a plain credential exchange.
|
|
23
17
|
*
|
|
24
18
|
* @packageDocumentation
|
|
25
19
|
*/
|
|
26
|
-
|
|
27
20
|
/** Thrown when the CRM rejects the exchange. `code` is the CRM's error code. */
|
|
28
21
|
declare class CrmExchangeError extends Error {
|
|
29
22
|
readonly status: number;
|
|
@@ -33,10 +26,15 @@ declare class CrmExchangeError extends Error {
|
|
|
33
26
|
}
|
|
34
27
|
/** The end-user being embedded into the CRM. */
|
|
35
28
|
interface EmbedUser {
|
|
29
|
+
/** Stable id for this user in YOUR system. */
|
|
36
30
|
id: string;
|
|
31
|
+
/** Verified email — the CRM matches/links the user by this. */
|
|
37
32
|
email: string;
|
|
33
|
+
/** Requested role; the CRM caps it to the install's configured max role. */
|
|
38
34
|
role: 'member' | 'admin';
|
|
35
|
+
/** Optional display name for first-time provisioning. */
|
|
39
36
|
name?: string;
|
|
37
|
+
/** Optional avatar URL for first-time provisioning. */
|
|
40
38
|
avatar_url?: string;
|
|
41
39
|
}
|
|
42
40
|
/** Input for {@link createEmbedSessionWithKey}. */
|
|
@@ -45,13 +43,21 @@ interface CreateEmbedSessionWithKeyInput {
|
|
|
45
43
|
appSecret: string;
|
|
46
44
|
user: EmbedUser;
|
|
47
45
|
}
|
|
48
|
-
/** The CRM session returned by
|
|
46
|
+
/** The CRM session returned by the exchange. */
|
|
49
47
|
interface EmbedSession {
|
|
48
|
+
/** Short-lived CRM bearer to hand to the iframe. */
|
|
50
49
|
accessToken: string;
|
|
50
|
+
/** TTL hint in seconds. */
|
|
51
51
|
expiresIn?: number;
|
|
52
52
|
/** The CRM workspace the user was provisioned into. */
|
|
53
53
|
workspaceId?: string;
|
|
54
|
-
user
|
|
54
|
+
/** The provisioned CRM user. */
|
|
55
|
+
user?: {
|
|
56
|
+
id: string;
|
|
57
|
+
email: string;
|
|
58
|
+
full_name?: string;
|
|
59
|
+
};
|
|
60
|
+
/** The effective role the CRM granted (may be capped below the requested one). */
|
|
55
61
|
role?: string;
|
|
56
62
|
}
|
|
57
63
|
/**
|
|
@@ -74,72 +80,44 @@ declare function createEmbedSessionWithKey(input: CreateEmbedSessionWithKeyInput
|
|
|
74
80
|
crmBaseUrl: string;
|
|
75
81
|
fetch?: typeof fetch;
|
|
76
82
|
}): Promise<EmbedSession>;
|
|
77
|
-
|
|
78
|
-
interface
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
/** PKCS8 PEM private key used to sign assertions. */
|
|
82
|
-
privateKeyPem: string;
|
|
83
|
-
/** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */
|
|
84
|
-
publicKeyPem: string;
|
|
85
|
-
/** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */
|
|
86
|
-
alg?: CrmEmbedAlg;
|
|
87
|
-
}
|
|
88
|
-
interface CrmAssertionInput {
|
|
89
|
-
/** Stable user id in your system (becomes the CRM external_subject). */
|
|
90
|
-
sub: string;
|
|
91
|
-
/** User email. */
|
|
92
|
-
email: string;
|
|
93
|
-
/** Requested role; the CRM clamps it to the install's configured max_role. */
|
|
94
|
-
requestedRole: 'member' | 'admin';
|
|
95
|
-
/** Your organization id; the CRM resolves the workspace from the org binding. */
|
|
96
|
-
orgId: string;
|
|
97
|
-
/** Optional display name for first-time provisioning. */
|
|
98
|
-
fullName?: string;
|
|
99
|
-
/** Optional avatar URL for first-time provisioning. */
|
|
100
|
-
avatarUrl?: string;
|
|
101
|
-
}
|
|
102
|
-
/** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */
|
|
103
|
-
interface CrmEmbedSession {
|
|
104
|
-
accessToken: string;
|
|
105
|
-
expiresIn?: number;
|
|
106
|
-
/** The CRM workspace the user was provisioned into (resolved from org_id). */
|
|
107
|
-
workspaceId?: string;
|
|
108
|
-
user?: {
|
|
109
|
-
id: string;
|
|
110
|
-
email: string;
|
|
111
|
-
full_name?: string;
|
|
112
|
-
};
|
|
113
|
-
role?: string;
|
|
114
|
-
}
|
|
115
|
-
interface ExchangeOptions {
|
|
83
|
+
/** Options for {@link createCrmSessionHandler}. */
|
|
84
|
+
interface CrmSessionHandlerOptions {
|
|
85
|
+
appId: string;
|
|
86
|
+
appSecret: string;
|
|
116
87
|
/** CRM exchange base URL, e.g. "https://api.crm.example.com". */
|
|
117
88
|
crmBaseUrl: string;
|
|
89
|
+
/**
|
|
90
|
+
* Resolve the signed-in user for a request. Return an {@link EmbedUser} to
|
|
91
|
+
* proceed, or throw to reject. A thrown error with a numeric `.status` uses
|
|
92
|
+
* that status; anything else becomes `401`.
|
|
93
|
+
*/
|
|
94
|
+
authenticate: (req: Request) => EmbedUser | Promise<EmbedUser>;
|
|
118
95
|
/** Override fetch (tests / custom agents). Defaults to global fetch. */
|
|
119
96
|
fetch?: typeof fetch;
|
|
120
97
|
}
|
|
121
|
-
/** Test/dev only: clear the memoized keys. */
|
|
122
|
-
declare function resetCrmEmbedKeys(): void;
|
|
123
98
|
/**
|
|
124
|
-
*
|
|
125
|
-
*
|
|
99
|
+
* Build a Web-standard `(Request) => Promise<Response>` session endpoint. Drop it
|
|
100
|
+
* into any runtime that speaks Web `Request`/`Response` — Next.js route handlers,
|
|
101
|
+
* Hono, Bun.serve, Deno, Cloudflare Workers. (For Express/Koa, adapt the handler
|
|
102
|
+
* or call {@link createEmbedSessionWithKey} directly.)
|
|
126
103
|
*
|
|
127
|
-
*
|
|
128
|
-
*
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
*
|
|
139
|
-
*
|
|
104
|
+
* It authenticates the request via your `authenticate` callback, runs the
|
|
105
|
+
* credential exchange, and returns the {@link EmbedSession} as JSON — exactly the
|
|
106
|
+
* shape `<CrmEmbed getSession>` / `crmSession()` expect. Errors map uniformly:
|
|
107
|
+
* a rejected exchange returns `CrmExchangeError.status` + `{ error: code }`; a
|
|
108
|
+
* failed `authenticate` returns its `.status` (or `401`).
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```typescript
|
|
112
|
+
* // app/api/crm/session/route.ts (Next.js)
|
|
113
|
+
* export const POST = createCrmSessionHandler({
|
|
114
|
+
* appId: process.env.CRM_APP_ID!,
|
|
115
|
+
* appSecret: process.env.CRM_APP_SECRET!,
|
|
116
|
+
* crmBaseUrl: process.env.CRM_BASE_URL!,
|
|
117
|
+
* authenticate: (req) => getMyUser(req), // return EmbedUser, or throw to 401
|
|
118
|
+
* });
|
|
119
|
+
* ```
|
|
140
120
|
*/
|
|
141
|
-
declare function
|
|
142
|
-
/** Mint + exchange in one call — the typical "give me a CRM session" helper. */
|
|
143
|
-
declare function createEmbedSession(input: CrmAssertionInput, config: CrmEmbedSigningConfig, options: ExchangeOptions): Promise<CrmEmbedSession>;
|
|
121
|
+
declare function createCrmSessionHandler(opts: CrmSessionHandlerOptions): (req: Request) => Promise<Response>;
|
|
144
122
|
|
|
145
|
-
export { type CreateEmbedSessionWithKeyInput,
|
|
123
|
+
export { type CreateEmbedSessionWithKeyInput, CrmExchangeError, type CrmSessionHandlerOptions, type EmbedSession, type EmbedUser, createCrmSessionHandler, createEmbedSessionWithKey };
|
package/dist/embed-server.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
|
|
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){return{accessToken:e.access_token,expiresIn:e.expires_in,workspaceId:e.workspace?.id,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 c=o?.error?.code??`HTTP_${n.status}`,p=o?.error?.message??"CRM exchange failed";throw new i(p,n.status,c,o)}return d(o?.data??{})}var a=(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=typeof r?.status=="number"?r.status:401,o=r?.code??"UNAUTHORIZED";return a({error:o},n)}if(!t)return a({error:"UNAUTHORIZED"},401);try{let r=await m({appId:e.appId,appSecret:e.appSecret,user:t},{crmBaseUrl:e.crmBaseUrl,fetch:e.fetch});return a(r,200)}catch(r){return r instanceof i?a({error:r.code},r.status):a({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. Two auth\n * approaches are supported:\n *\n * **Option A — API-key auth (simpler, no keypair):**\n * POST user identity + your registered `app_id`/`app_secret` to the CRM.\n * Use {@link createEmbedSessionWithKey}. No `jose` required.\n *\n * **Option B — Signed-assertion auth (zero shared-secret):**\n * Mint a short-lived asymmetric (RS256/ES256) assertion server-side and\n * exchange it at the CRM for a CRM bearer. Use {@link createEmbedSession} (or\n * {@link mintCrmAssertion} + {@link exchangeAssertion} separately).\n * Requires the `jose` peer dependency.\n *\n * Both paths return a short-lived CRM bearer; hand that bearer to the CRM\n * iframe via `embed-host` (see ./embed-host).\n *\n * Works in Node and Bun (or any environment with a global `fetch`).\n *\n * @packageDocumentation\n */\nimport {\n SignJWT,\n exportJWK,\n importPKCS8,\n importSPKI,\n calculateJwkThumbprint,\n type JWK,\n type KeyLike,\n} from 'jose';\n\n// ─── Shared 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// ─── Option A: API-key auth ──────────────────────────────────────────────────\n\n/** The end-user being embedded into the CRM. */\nexport interface EmbedUser {\n id: string;\n email: string;\n role: 'member' | 'admin';\n name?: string;\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 {@link createEmbedSessionWithKey}. */\nexport interface EmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into. */\n workspaceId?: string;\n user?: unknown;\n role?: string;\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 = `${opts.crmBaseUrl.replace(/\\/$/, '')}/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 const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n// ─── Option B: Signed-assertion auth ────────────────────────────────────────\n\nexport type CrmEmbedAlg = 'RS256' | 'ES256';\n\nconst AUDIENCE = 'crm';\nconst DEFAULT_TTL_SECONDS = 120;\n\nexport interface CrmEmbedSigningConfig {\n /** Issuer — MUST equal the client_id the CRM registered for your app. */\n iss: string;\n /** PKCS8 PEM private key used to sign assertions. */\n privateKeyPem: string;\n /** SPKI PEM public key — required so getCrmEmbedJwks() can publish it. */\n publicKeyPem: string;\n /** Signature algorithm. Default 'RS256'. The CRM accepts RS256 or ES256. */\n alg?: CrmEmbedAlg;\n}\n\nexport interface CrmAssertionInput {\n /** Stable user id in your system (becomes the CRM external_subject). */\n sub: string;\n /** User email. */\n email: string;\n /** Requested role; the CRM clamps it to the install's configured max_role. */\n requestedRole: 'member' | 'admin';\n /** Your organization id; the CRM resolves the workspace from the org binding. */\n orgId: string;\n /** Optional display name for first-time provisioning. */\n fullName?: string;\n /** Optional avatar URL for first-time provisioning. */\n avatarUrl?: string;\n}\n\n/** The CRM session returned by {@link createEmbedSession} / {@link exchangeAssertion}. */\nexport interface CrmEmbedSession {\n accessToken: string;\n expiresIn?: number;\n /** The CRM workspace the user was provisioned into (resolved from org_id). */\n workspaceId?: string;\n user?: { id: string; email: string; full_name?: string };\n role?: string;\n}\n\nexport interface ExchangeOptions {\n /** CRM exchange base URL, e.g. \"https://api.crm.example.com\". */\n crmBaseUrl: string;\n /** Override fetch (tests / custom agents). Defaults to global fetch. */\n fetch?: typeof fetch;\n}\n\ninterface LoadedKeys { privateKey: KeyLike; publicJwk: JWK; kid: string }\n\n// Memoize per config.iss so repeated calls don't re-import keys.\nconst keyCache = new Map<string, Promise<LoadedKeys>>();\n\nfunction randomUUID(): string {\n const c = (globalThis as { crypto?: Crypto }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n // Fallback (should not happen on Node 16+/Bun): RFC4122-ish from getRandomValues.\n const b = new Uint8Array(16);\n c?.getRandomValues?.(b);\n b[6] = (b[6] & 0x0f) | 0x40;\n b[8] = (b[8] & 0x3f) | 0x80;\n const h = Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');\n return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}`;\n}\n\nasync function loadKeys(config: CrmEmbedSigningConfig): Promise<LoadedKeys> {\n const alg = config.alg ?? 'RS256';\n const cacheKey = `${config.iss}:${alg}`;\n const existing = keyCache.get(cacheKey);\n if (existing) return existing;\n\n const created = (async (): Promise<LoadedKeys> => {\n const privateKey = await importPKCS8(config.privateKeyPem, alg);\n const publicKey = await importSPKI(config.publicKeyPem, alg);\n const publicJwk = await exportJWK(publicKey);\n // Stable kid = RFC 7638 thumbprint so the signed header kid matches JWKS.\n const kid = await calculateJwkThumbprint(publicJwk);\n return { privateKey, publicJwk: { ...publicJwk, kid, alg, use: 'sig' }, kid };\n })();\n keyCache.set(cacheKey, created);\n return created;\n}\n\n/** Test/dev only: clear the memoized keys. */\nexport function resetCrmEmbedKeys(): void {\n keyCache.clear();\n}\n\n/**\n * The public JWKS document to serve at a public https URL. Give that URL to the\n * CRM team so they can verify your assertions. Example (Express):\n *\n * app.get('/crm-embed/jwks', async (_req, res) =>\n * res.json(await getCrmEmbedJwks(config)));\n */\nexport async function getCrmEmbedJwks(\n config: CrmEmbedSigningConfig,\n): Promise<{ keys: JWK[] }> {\n const { publicJwk } = await loadKeys(config);\n return { keys: [publicJwk] };\n}\n\n/** Mint a short-lived signed assertion the CRM will exchange for a bearer. */\nexport async function mintCrmAssertion(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options?: { ttlSeconds?: number },\n): Promise<string> {\n const alg = config.alg ?? 'RS256';\n const { privateKey, kid } = await loadKeys(config);\n const ttl = Math.min(options?.ttlSeconds ?? DEFAULT_TTL_SECONDS, DEFAULT_TTL_SECONDS);\n\n return new SignJWT({\n email: input.email,\n requested_role: input.requestedRole,\n org_id: input.orgId,\n ...(input.fullName ? { full_name: input.fullName } : {}),\n ...(input.avatarUrl ? { avatar_url: input.avatarUrl } : {}),\n })\n .setProtectedHeader({ alg, kid })\n .setSubject(input.sub)\n .setIssuer(config.iss)\n .setAudience(AUDIENCE)\n .setIssuedAt()\n .setExpirationTime(`${ttl}s`)\n .setJti(randomUUID())\n .sign(privateKey);\n}\n\n/**\n * Exchange a minted assertion at the CRM for a CRM bearer. Do this server-side\n * so the browser never calls the CRM's exchange endpoint cross-origin.\n */\nexport async function exchangeAssertion(\n assertion: string,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const doFetch = options.fetch ?? fetch;\n const url = `${options.crmBaseUrl.replace(/\\/$/, '')}/api/auth/exchange`;\n const res = await doFetch(url, {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ assertion }),\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 const data = body?.data ?? {};\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\n user: data.user,\n role: data.role,\n };\n}\n\n/** Mint + exchange in one call — the typical \"give me a CRM session\" helper. */\nexport async function createEmbedSession(\n input: CrmAssertionInput,\n config: CrmEmbedSigningConfig,\n options: ExchangeOptions,\n): Promise<CrmEmbedSession> {\n const assertion = await mintCrmAssertion(input, config);\n return exchangeAssertion(assertion, options);\n}\n"],"mappings":"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","names":["SignJWT","exportJWK","importPKCS8","importSPKI","calculateJwkThumbprint","CrmExchangeError","message","status","code","detail","createEmbedSessionWithKey","input","opts","doFetch","url","res","body","msg","data","AUDIENCE","DEFAULT_TTL_SECONDS","keyCache","randomUUID","c","b","h","x","loadKeys","config","alg","cacheKey","existing","created","privateKey","publicKey","publicJwk","kid","resetCrmEmbedKeys","getCrmEmbedJwks","mintCrmAssertion","options","ttl","exchangeAssertion","assertion","createEmbedSession"]}
|
|
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 /** The CRM workspace the user was provisioned into. */\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/** Map the CRM's `{ data: { access_token, ... } }` envelope to an EmbedSession. */\nfunction toEmbedSession(data: Record<string, any>): EmbedSession {\n return {\n accessToken: data.access_token,\n expiresIn: data.expires_in,\n workspaceId: data.workspace?.id,\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 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,EAyCMC,EAAqBC,GAAwBA,EAAI,QAAQ,MAAO,EAAE,EAGxE,SAASC,EAAeC,EAAyC,CAC/D,MAAO,CACL,YAAaA,EAAK,aAClB,UAAWA,EAAK,WAChB,YAAaA,EAAK,WAAW,GAC7B,KAAMA,EAAK,KACX,KAAMA,EAAK,IACb,CACF,CAkBA,eAAsBC,EACpBC,EACAC,EACuB,CACvB,IAAMC,EAAUD,EAAK,OAAS,MACxBL,EAAM,GAAGD,EAAkBM,EAAK,UAAU,CAAC,qBAC3CE,EAAM,MAAMD,EAAQN,EAAK,CAC7B,OAAQ,OACR,QAAS,CAAE,eAAgB,kBAAmB,EAC9C,KAAM,KAAK,UAAU,CACnB,OAAQI,EAAM,MACd,WAAYA,EAAM,UAClB,KAAMA,EAAM,IACd,CAAC,CACH,CAAC,EACKI,EAAO,MAAMD,EAAI,KAAK,EAAE,MAAM,KAAO,CAAC,EAAE,EAC9C,GAAI,CAACA,EAAI,GAAI,CACX,IAAMV,EAAOW,GAAM,OAAO,MAAQ,QAAQD,EAAI,MAAM,GAC9CE,EAAMD,GAAM,OAAO,SAAW,sBACpC,MAAM,IAAId,EAAiBe,EAAKF,EAAI,OAAQV,EAAMW,CAAI,CACxD,CACA,OAAOP,EAAeO,GAAM,MAAQ,CAAC,CAAC,CACxC,CAoBA,IAAME,EAAe,CAACF,EAAeZ,IACnC,IAAI,SAAS,KAAK,UAAUY,CAAI,EAAG,CACjC,OAAAZ,EACA,QAAS,CAAE,eAAgB,kBAAmB,CAChD,CAAC,EAyBI,SAASe,EACdN,EACqC,CACrC,MAAO,OAAOO,GAAoC,CAChD,IAAIC,EACJ,GAAI,CACFA,EAAO,MAAMR,EAAK,aAAaO,CAAG,CACpC,OAASE,EAAK,CACZ,IAAMlB,EAAS,OAAQkB,GAA8B,QAAW,SAC3DA,EAA2B,OAC5B,IACEjB,EAAQiB,GAA2B,MAAQ,eACjD,OAAOJ,EAAa,CAAE,MAAOb,CAAK,EAAGD,CAAM,CAC7C,CACA,GAAI,CAACiB,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,aAAepB,EACVgB,EAAa,CAAE,MAAOI,EAAI,IAAK,EAAGA,EAAI,MAAM,EAE9CJ,EAAa,CAAE,MAAO,oBAAqB,EAAG,GAAG,CAC1D,CACF,CACF","names":["CrmExchangeError","message","status","code","detail","trimTrailingSlash","url","toEmbedSession","data","createEmbedSessionWithKey","input","opts","doFetch","res","body","msg","jsonResponse","createCrmSessionHandler","req","user","err","session"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@first-to-fly/crm-sdk",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.4.1",
|
|
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",
|
|
@@ -29,6 +29,16 @@
|
|
|
29
29
|
"default": "./dist/embed-host.cjs"
|
|
30
30
|
}
|
|
31
31
|
},
|
|
32
|
+
"./embed-react": {
|
|
33
|
+
"import": {
|
|
34
|
+
"types": "./dist/embed-react.d.ts",
|
|
35
|
+
"default": "./dist/embed-react.js"
|
|
36
|
+
},
|
|
37
|
+
"require": {
|
|
38
|
+
"types": "./dist/embed-react.d.cts",
|
|
39
|
+
"default": "./dist/embed-react.cjs"
|
|
40
|
+
}
|
|
41
|
+
},
|
|
32
42
|
"./embed-server": {
|
|
33
43
|
"import": {
|
|
34
44
|
"types": "./dist/embed-server.d.ts",
|
|
@@ -68,24 +78,26 @@
|
|
|
68
78
|
"iframe",
|
|
69
79
|
"embeddable",
|
|
70
80
|
"postmessage",
|
|
71
|
-
"embed"
|
|
72
|
-
"jwt",
|
|
73
|
-
"assertion"
|
|
81
|
+
"embed"
|
|
74
82
|
],
|
|
75
83
|
"author": "First to Fly",
|
|
76
84
|
"license": "MIT",
|
|
77
85
|
"peerDependencies": {
|
|
78
|
-
"
|
|
86
|
+
"react": ">=17"
|
|
79
87
|
},
|
|
80
88
|
"peerDependenciesMeta": {
|
|
81
|
-
"
|
|
89
|
+
"react": {
|
|
82
90
|
"optional": true
|
|
83
91
|
}
|
|
84
92
|
},
|
|
85
93
|
"devDependencies": {
|
|
86
|
-
"
|
|
94
|
+
"@testing-library/react": "^16.1.0",
|
|
87
95
|
"@types/jsdom": "^28.0.0",
|
|
96
|
+
"@types/react": "^18.3.12",
|
|
97
|
+
"@types/react-dom": "^18.3.1",
|
|
88
98
|
"jsdom": "^28.1.0",
|
|
99
|
+
"react": "^18.3.1",
|
|
100
|
+
"react-dom": "^18.3.1",
|
|
89
101
|
"tsup": "^8.5.1",
|
|
90
102
|
"typescript": "^5.9.3",
|
|
91
103
|
"vitest": "^4.0.18"
|