@swirepay-developer/sparo-embed-sdk 1.0.5 → 1.0.8

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/CHANGELOG.md CHANGED
@@ -1,5 +1,26 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.0.8
4
+
5
+ - `account` is optional in guest-token responses — SDK no longer requires or derives it from JWT.
6
+ - Iframe URL uses `embed=true` only; `account` query param added only when provided.
7
+ - `postMessage` auth omits `account` when not in token response.
8
+
9
+ ## 1.0.7
10
+
11
+ - `createGuestTokenFetcher` calls gateway Java API `GET /v1/sparo/guest-token` with `Authorization: Bearer <gateway-jwt>`.
12
+ - Supports wrapped responses `{ data: { token, expiresIn, account } }`.
13
+ - `getAuthorization` callback for dynamic Bearer token on each refresh.
14
+ - URLs are **host-configured** (staging vs prod) — not hardcoded in SDK.
15
+
16
+ ## 1.0.6
17
+
18
+ - Add `createGuestTokenFetcher('/sparo/token')` helper for Java/gateway session cookie flow (Superset-style).
19
+ - Preserve `err.code` from BFF (`merchant_not_enabled`, `invalid_token`, etc.) in `onError`.
20
+ - Auto-refresh on iframe `expired_token` postMessage.
21
+ - `iframe_load_failed` on iframe element error.
22
+ - Example: `examples/embed-vanilla.html`.
23
+
3
24
  ## 1.0.5
4
25
 
5
26
  - Fix DevOps publish: rename `eslint.config.js` → `eslint.config.mjs` and `vitest.config.js` → `vitest.config.mjs` (ESM configs without `"type": "module"` on package).
@@ -1,162 +1,296 @@
1
1
  # Gateway Frontend — SPARO SDK Integration Guide (React)
2
2
 
3
- Step-by-step guide for **gateway-frontend** React developers integrating `@swirepay-developer/sparo-embed-sdk` from npm.
3
+ Step-by-step guide for **gateway-frontend** developers integrating `@swirepay-developer/sparo-embed-sdk`.
4
4
 
5
- > **Prerequisite:** DevOps must publish the SDK from Bitbucket first.
5
+ > **Prerequisite:** DevOps publishes the SDK from Bitbucket.
6
6
  > Repo: https://bitbucket.org/zetametrics/sparo-swirepay-frontend.git — runbook: [DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)
7
- >
8
- > ### Wrong package name (most common after publish)
9
- >
10
- > npm package is **`@swirepay-developer/sparo-embed-sdk`** (scope `swirepay-developer`).
11
- > If your code imports **`@swirepay/sparo-embed-sdk`** (no `-developer`), webpack will always show **Module not found** even after `npm install` and cache clear.
12
- >
13
- > **Fix:** change import + `package.json` dependency to `@swirepay-developer/sparo-embed-sdk` (see Step 1).
14
- >
15
- > **`Module not found`** with the correct name usually means not installed — run `npm view @swirepay-developer/sparo-embed-sdk version` (DevOps screenshot should show `1.0.5`).
16
7
 
17
8
  ---
18
9
 
19
- ## What you are building
10
+ ## How to use the SDK (overview)
20
11
 
21
- ```text
22
- User (logged into gateway)
23
- → React page (SparoChat)
24
- → SDK calls YOUR backend: GET /sparo/token
25
- → YOUR backend calls SPARO: POST /api/guest-token (SPARO_ADMIN_KEY)
26
- → SDK receives { token, expiresIn, account }
27
- → SDK loads SPARO iframe + sends JWT via postMessage
28
- → SPARO chat UI renders (no SPARO login screen)
12
+ The SDK exports two functions you need:
13
+
14
+ ```js
15
+ import {
16
+ embed, // mounts SPARO iframe + handles auth/refresh
17
+ createGuestTokenFetcher, // helper that calls Java GET /v1/sparo/guest-token
18
+ } from '@swirepay-developer/sparo-embed-sdk';
29
19
  ```
30
20
 
31
- You do **not** implement iframe auth yourself — the SDK handles iframe creation, `postMessage`, and token refresh.
21
+ | Function | Purpose |
22
+ |----------|---------|
23
+ | `embed({ ... })` | Creates iframe, fetches token, sends auth to SPARO, auto-refreshes |
24
+ | `createGuestTokenFetcher(url, { getAuthorization })` | Returns a `fetchGuestToken` function for `embed()` |
32
25
 
33
- ---
26
+ **Minimum working integration:**
27
+
28
+ ```jsx
29
+ import { useEffect, useRef } from 'react';
30
+ import { embed, createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
34
31
 
35
- ## Prerequisites
32
+ function SparoChat() {
33
+ const mountRef = useRef(null);
36
34
 
37
- Before starting, confirm with your team:
35
+ useEffect(() => {
36
+ const el = mountRef.current;
37
+ if (!el) return undefined;
38
+
39
+ const handle = embed({
40
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
41
+ mountPoint: el,
42
+ fetchGuestToken: createGuestTokenFetcher(
43
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
44
+ { getAuthorization: getGatewayAccessToken },
45
+ ),
46
+ onReady: () => console.log('[SPARO] ready'),
47
+ onError: (err) => console.error('[SPARO]', err.code, err.message),
48
+ });
38
49
 
39
- | Item | Owner | Notes |
40
- |------|--------|-------|
41
- | npm access to `@swirepay-developer/sparo-embed-sdk` | DevOps / npm org | `npm login` if private scope |
42
- | `SPARO_ADMIN_KEY` | Backend | Never in React code or `.env` with `REACT_APP_` |
43
- | Merchant enabled in SPARO | SPARO admin | Deny-by-default allowlist |
44
- | Backend route `/sparo/token` | Backend | Returns guest JWT for logged-in user |
45
- | SPARO environment URL | Config | Staging vs production `sparoDomain` |
50
+ return () => handle.unmount();
51
+ }, []);
52
+
53
+ return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
54
+ }
55
+ ```
56
+
57
+ You must provide:
58
+
59
+ 1. **`sparoDomain`** — SPARO UI URL (iframe loads from here)
60
+ 2. **`mountPoint`** — DOM element to render into
61
+ 3. **`fetchGuestToken`** — async function returning `{ token, expiresIn, account }`
46
62
 
47
63
  ---
48
64
 
49
- ## Step 1 — Install the SDK
65
+ ## Architecture
50
66
 
51
- From the **gateway-frontend** project root:
67
+ Same pattern as **Apache Superset embedded analytics**: React SDK + backend guest-token API + embedded app iframe.
52
68
 
53
- ```bash
54
- npm install @swirepay-developer/sparo-embed-sdk
69
+ ```text
70
+ User (logged into gateway)
71
+ → React SparoChat page
72
+ → SDK calls GET /v1/sparo/guest-token (Authorization: Bearer <gateway JWT>)
73
+ → Java validates user + merchant allowlist
74
+ → Returns { token, expiresIn, account }
75
+ → SDK loads SPARO iframe (sparoDomain) + postMessage auth
76
+ → SPARO chat UI (no SPARO login screen)
77
+ → SDK auto-refreshes token ~30s before expiry
55
78
  ```
56
79
 
57
- Or add to `package.json`:
80
+ You do **not** implement iframe auth, `postMessage`, or token refresh — the SDK handles that.
81
+
82
+ ---
83
+
84
+ ## Step 1 — Install
85
+
86
+ ```bash
87
+ yarn add @swirepay-developer/sparo-embed-sdk
88
+ ```
58
89
 
59
90
  ```json
60
91
  {
61
92
  "dependencies": {
62
- "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
93
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.8"
63
94
  }
64
95
  }
65
96
  ```
66
97
 
67
- Then:
68
-
69
- ```bash
70
- npm install
71
- ```
72
-
73
- ### Verify install
98
+ Verify:
74
99
 
75
100
  ```bash
76
- npm ls @swirepay-developer/sparo-embed-sdk
101
+ yarn why @swirepay-developer/sparo-embed-sdk
77
102
  ```
78
103
 
79
- You should see the package listed. If not:
80
-
81
- - Add `.npmrc` with `@swirepay-developer:registry` (see [.npmrc.example](../.npmrc.example)) and `npm login` if needed
82
- - Remove any old `"file:..."` path dependency for this package
83
- - Delete `node_modules` and `package-lock.json`, then `npm install` again
104
+ **Package name:** `@swirepay-developer/sparo-embed-sdk` (not `@swirepay/sparo-embed-sdk`).
84
105
 
85
106
  ---
86
107
 
87
- ## Step 2 — Environment variables (frontend)
108
+ ## Step 2 — Environment variables
88
109
 
89
- Add **non-secret** config only. Never put `SPARO_ADMIN_KEY` in React env vars.
110
+ | Variable | Staging | Production |
111
+ |----------|---------|------------|
112
+ | `REACT_APP_SPARO_GUEST_TOKEN_URL` | `https://staging-backend.swirepay.com/v1/sparo/guest-token` | `https://backend.swirepay.com/v1/sparo/guest-token` |
113
+ | `REACT_APP_SPARO_DOMAIN` | `https://sparo-stag.swirepay.com` | `https://sparo.swirepay.com` |
90
114
 
91
- ### `.env.development` (local / dev)
115
+ `.env.development`:
92
116
 
93
117
  ```env
94
- REACT_APP_SPARO_DOMAIN=https://sparo-staging.swirepay.com
118
+ REACT_APP_SPARO_GUEST_TOKEN_URL=https://staging-backend.swirepay.com/v1/sparo/guest-token
119
+ REACT_APP_SPARO_DOMAIN=https://sparo-stag.swirepay.com
95
120
  ```
96
121
 
97
- ### `.env.production`
122
+ `.env.production`:
98
123
 
99
124
  ```env
125
+ REACT_APP_SPARO_GUEST_TOKEN_URL=https://backend.swirepay.com/v1/sparo/guest-token
100
126
  REACT_APP_SPARO_DOMAIN=https://sparo.swirepay.com
101
127
  ```
102
128
 
103
- Use the URL your team provides for each environment.
104
- `sparoDomain` must match the environment your **backend** uses when minting tokens.
129
+ Restart the dev server after changing env vars.
105
130
 
106
131
  ---
107
132
 
108
- ## Step 3 — Backend contract (coordinate with backend team)
133
+ ## Step 3 — Recommended file layout
109
134
 
110
- Your React app will call **your** API, not SPARO directly.
135
+ ```text
136
+ src/
137
+ ├── utils/
138
+ │ └── sparoAuth.js # getGatewayAccessToken()
139
+ ├── routes/
140
+ │ └── SparoChat/
141
+ │ └── index.js # embed() + UI
142
+ └── routes.js # register /sparo route
143
+ ```
111
144
 
112
- ### Required endpoint (example)
145
+ ---
113
146
 
114
- `GET /sparo/token` (or `/api/sparo/token` — match your gateway API prefix)
147
+ ## Code samples
115
148
 
116
- **Request**
149
+ ### Sample 1 — `createGuestTokenFetcher` (recommended)
117
150
 
118
- - Authenticated user session (cookie or Bearer — same as rest of gateway)
119
- - `credentials: 'include'` if cookie-based
151
+ Use this when gateway Java exposes `GET /v1/sparo/guest-token`. The SDK calls it on **mount** and on **each auto-refresh**.
120
152
 
121
- **Response `200`**
153
+ ```js
154
+ import { createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
155
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
156
+
157
+ const fetchGuestToken = createGuestTokenFetcher(
158
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
159
+ {
160
+ getAuthorization: getGatewayAccessToken,
161
+ },
162
+ );
163
+
164
+ // Pass to embed:
165
+ embed({ fetchGuestToken, sparoDomain, mountPoint, ... });
166
+ ```
122
167
 
123
- ```json
124
- {
125
- "token": "eyJhbGciOi...",
126
- "expiresIn": 900,
127
- "account": "account-72ec92..."
168
+ **What `getAuthorization` must return:** raw JWT string (`eyJ...`). The SDK adds `Bearer` if missing.
169
+
170
+ **Same-origin proxy** (if gateway BFF proxies the Java API):
171
+
172
+ ```js
173
+ const fetchGuestToken = createGuestTokenFetcher('/v1/sparo/guest-token', {
174
+ getAuthorization: getGatewayAccessToken,
175
+ });
176
+ ```
177
+
178
+ ---
179
+
180
+ ### Sample 2 — Auth helper (`src/utils/sparoAuth.js`)
181
+
182
+ Wire to whatever gateway already uses for API calls.
183
+
184
+ **Option A — existing axios / auth module:**
185
+
186
+ ```js
187
+ import { getAccessToken } from 'api/auth';
188
+
189
+ export async function getGatewayAccessToken() {
190
+ const token = await getAccessToken();
191
+ if (!token) throw new Error('Not authenticated');
192
+ return token;
128
193
  }
129
194
  ```
130
195
 
131
- | Field | Meaning |
132
- |-------|---------|
133
- | `token` | Short-lived guest JWT from SPARO |
134
- | `expiresIn` | Seconds until expiry (e.g. 900 = 15 min) |
135
- | `account` | Merchant account GID for this user |
196
+ **Option B — token from Redux / session store:**
136
197
 
137
- **Important:** `account` must be the merchant the logged-in user belongs to. Backend resolves it from session/DB — frontend must not let users pick arbitrary merchant IDs.
198
+ ```js
199
+ import store from 'store';
138
200
 
139
- ### Error responses to handle in UI
201
+ export function getGatewayAccessToken() {
202
+ const token = store.getState().auth.accessToken;
203
+ if (!token) throw new Error('Not authenticated');
204
+ return token;
205
+ }
206
+ ```
140
207
 
141
- | HTTP | Meaning | Suggested UI |
142
- |------|---------|----------------|
143
- | 401 | User not logged in | Redirect to login |
144
- | 403 | `merchant_not_enabled` | “Contact us” / support message |
145
- | 429 | Rate limited | Retry message |
146
- | 500 | Mint failed | Generic error + support |
208
+ **Option C — AWS Amplify (if gateway uses Cognito directly):**
209
+
210
+ ```js
211
+ import { fetchAuthSession } from 'aws-amplify/auth';
212
+
213
+ export async function getGatewayAccessToken() {
214
+ const session = await fetchAuthSession();
215
+ const token = session.tokens?.accessToken?.toString();
216
+ if (!token) throw new Error('Not authenticated');
217
+ return token;
218
+ }
219
+ ```
147
220
 
148
221
  ---
149
222
 
150
- ## Step 4 — Create the React page component
223
+ ### Sample 3 — Custom `fetchGuestToken` with axios (alternative)
151
224
 
152
- Create a route component, e.g. `src/routes/SparoChat/index.js`:
225
+ Use this if you prefer gateway's existing axios instance instead of `createGuestTokenFetcher`:
226
+
227
+ ```js
228
+ // src/utils/sparoGuestToken.js
229
+ import axios from 'axios';
230
+ import { getGatewayAccessToken } from './sparoAuth';
231
+
232
+ export async function fetchSparoGuestToken() {
233
+ const token = await getGatewayAccessToken();
234
+
235
+ const { data } = await axios.get(
236
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
237
+ {
238
+ headers: {
239
+ Authorization: `Bearer ${token}`,
240
+ Accept: 'application/json',
241
+ },
242
+ },
243
+ );
244
+
245
+ // Java may wrap response: { data: { token, expiresIn, account } }
246
+ const payload = data?.data?.token ? data.data : data;
247
+
248
+ return {
249
+ token: payload.token,
250
+ expiresIn: payload.expiresIn,
251
+ account: payload.account,
252
+ };
253
+ }
254
+ ```
255
+
256
+ ```jsx
257
+ import { embed } from '@swirepay-developer/sparo-embed-sdk';
258
+ import { fetchSparoGuestToken } from 'utils/sparoGuestToken';
259
+
260
+ embed({
261
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
262
+ mountPoint: mountRef.current,
263
+ fetchGuestToken: fetchSparoGuestToken,
264
+ // ...
265
+ });
266
+ ```
267
+
268
+ Or import the SDK normalizer:
269
+
270
+ ```js
271
+ import { normalizeGuestTokenResponse } from '@swirepay-developer/sparo-embed-sdk';
272
+
273
+ const { data } = await axios.get(url, { headers: { Authorization: `Bearer ${token}` } });
274
+ return normalizeGuestTokenResponse(data);
275
+ ```
276
+
277
+ ---
278
+
279
+ ### Sample 4 — Full `SparoChat` component (copy-paste ready)
280
+
281
+ Create `src/routes/SparoChat/index.js`:
153
282
 
154
283
  ```jsx
155
284
  import React, { useEffect, useRef, useState } from 'react';
156
285
  import { Alert, Spin } from 'antd';
157
- import { embed } from '@swirepay-developer/sparo-embed-sdk';
286
+ import {
287
+ embed,
288
+ createGuestTokenFetcher,
289
+ } from '@swirepay-developer/sparo-embed-sdk';
290
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
158
291
 
159
- const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN || 'https://sparo.swirepay.com';
292
+ const SPARO_DOMAIN = process.env.REACT_APP_SPARO_DOMAIN;
293
+ const GUEST_TOKEN_URL = process.env.REACT_APP_SPARO_GUEST_TOKEN_URL;
160
294
 
161
295
  function SparoChat() {
162
296
  const mountRef = useRef(null);
@@ -175,73 +309,60 @@ function SparoChat() {
175
309
  id: 'sparo-chat',
176
310
  sparoDomain: SPARO_DOMAIN,
177
311
  mountPoint: mountElement,
178
- fetchGuestToken: async () => {
179
- const response = await fetch('/sparo/token', {
180
- method: 'GET',
181
- credentials: 'include',
182
- });
183
- if (response.status === 401) {
184
- window.location.href = '/login';
185
- throw new Error('Unauthorized');
186
- }
187
- const payload = await response.json();
188
- if (!response.ok) {
189
- const apiError = new Error(
190
- payload?.message || payload?.error || 'Unable to fetch SPARO token',
191
- );
192
- apiError.code = payload?.code || 'fetch_failed';
193
- throw apiError;
194
- }
195
- return payload; // { token, expiresIn, account }
196
- },
312
+
313
+ // SDK calls Java API with Bearer JWT on mount + each refresh
314
+ fetchGuestToken: createGuestTokenFetcher(GUEST_TOKEN_URL, {
315
+ getAuthorization: getGatewayAccessToken,
316
+ }),
317
+
197
318
  uiConfig: {
198
319
  theme: 'light',
199
320
  showWelcome: true,
200
321
  showSuggestions: true,
201
322
  hideSidebar: false,
202
323
  },
203
- onReady: () => setLoading(false),
324
+
325
+ onReady: () => {
326
+ setLoading(false);
327
+ },
328
+
204
329
  onError: (err) => {
205
- console.error('[SPARO]', err);
330
+ console.error('[SPARO]', err.code, err.message);
206
331
  setLoading(false);
207
- switch (err?.code) {
208
- case 'merchant_not_enabled':
209
- setError('Your merchant account is not enabled for SPARO.');
210
- break;
211
- case 'rate_limited':
212
- setError('Too many requests. Please try again shortly.');
213
- break;
214
- case 'invalid_token':
215
- setError('Invalid authentication token received.');
216
- break;
217
- case 'iframe_load_failed':
218
- setError('Unable to load SPARO assistant.');
219
- break;
220
- default:
221
- setError(err?.message || 'Failed to initialize SPARO.');
332
+
333
+ if (err.code === 'merchant_not_enabled') {
334
+ setError('Your merchant account is not enabled for SPARO.');
335
+ } else if (err.code === 'invalid_token') {
336
+ setError('Session expired. Please sign in again.');
337
+ } else if (err.code === 'rate_limited') {
338
+ setError('Too many requests. Please try again shortly.');
339
+ } else {
340
+ setError(err.message || 'Failed to initialize SPARO.');
222
341
  }
223
342
  },
224
343
  });
225
344
 
345
+ // Required: tear down iframe + timers when user leaves the page
226
346
  return () => {
227
- if (handleRef.current?.unmount) {
228
- handleRef.current.unmount();
229
- handleRef.current = null;
230
- }
347
+ handleRef.current?.unmount();
348
+ handleRef.current = null;
231
349
  };
232
350
  }, []);
233
351
 
234
352
  return (
235
353
  <div style={{ padding: 20 }}>
236
354
  <h2>SPARO Assistant</h2>
355
+
237
356
  {loading && (
238
357
  <div style={{ marginBottom: 16, textAlign: 'center' }}>
239
358
  <Spin size="large" />
240
359
  </div>
241
360
  )}
361
+
242
362
  {error && (
243
363
  <Alert type="error" showIcon message={error} style={{ marginBottom: 16 }} />
244
364
  )}
365
+
245
366
  <div
246
367
  ref={mountRef}
247
368
  style={{
@@ -260,238 +381,284 @@ function SparoChat() {
260
381
  export default SparoChat;
261
382
  ```
262
383
 
263
- ### If your API base URL is not same-origin
384
+ ---
264
385
 
265
- Use your existing axios instance or API helper:
386
+ ### Sample 5 — `embed()` options explained
266
387
 
267
388
  ```js
268
- import { axiosAuthInstance, API_END_POINTS } from 'api';
389
+ const handle = embed({
390
+ // Required
391
+ sparoDomain: 'https://sparo-stag.swirepay.com', // SPARO UI origin
392
+ mountPoint: document.getElementById('sparo'), // DOM node (use ref.current in React)
393
+ fetchGuestToken: createGuestTokenFetcher(url, { getAuthorization }),
394
+
395
+ // Optional
396
+ id: 'sparo-chat', // iframe element id (default: 'sparo-embed')
397
+ uiConfig: {
398
+ theme: 'light', // 'light' | 'dark'
399
+ showWelcome: true,
400
+ showSuggestions: true,
401
+ hideSidebar: false,
402
+ },
403
+ onReady: () => {}, // iframe authenticated and ready
404
+ onError: (err) => {}, // err.code + err.message
405
+ });
406
+
407
+ // handle.refresh() — force token refresh (rarely needed; SDK auto-refreshes)
408
+ // handle.unmount() — remove iframe + clear timers (call on route unmount)
409
+ ```
410
+
411
+ **`fetchGuestToken` return shape** (Java API must return this):
269
412
 
270
- fetchGuestToken: async () => {
271
- const { data } = await axiosAuthInstance.get('/sparo/token');
272
- return data;
273
- },
413
+ ```js
414
+ {
415
+ token: 'eyJhbGciOi...', // SPARO guest JWT
416
+ expiresIn: 900, // seconds until expiry
417
+ account: 'account-72ec92...', // merchant account GID
418
+ }
274
419
  ```
275
420
 
276
421
  ---
277
422
 
278
- ## Step 5 — Register the route
423
+ ### Sample 6 — Register route
279
424
 
280
- Add a protected route in your router config (example for React Router v5):
425
+ React Router v5 (gateway pattern):
281
426
 
282
427
  ```js
283
428
  import SparoChat from 'routes/SparoChat';
284
429
 
285
- // In routes array:
430
+ // In your routes array:
286
431
  {
287
432
  key: 'sparo',
288
433
  path: '/sparo',
289
434
  exact: true,
290
435
  protected: true,
291
436
  component: SparoChat,
292
- allowedRoles: [/* same roles as your team allows */],
437
+ allowedRoles: ['MERCHANT_ADMIN', 'MERCHANT_USER'],
293
438
  }
294
439
  ```
295
440
 
296
- Add a nav link or header icon that navigates to `/sparo`.
441
+ Nav link example:
297
442
 
298
- Restart the dev server after adding the route:
443
+ ```jsx
444
+ import { Link } from 'react-router-dom';
299
445
 
300
- ```bash
301
- npm start
446
+ <Link to="/sparo">SPARO Assistant</Link>
302
447
  ```
303
448
 
304
449
  ---
305
450
 
306
- ## Step 6 — Test locally
451
+ ### Sample 7 — TypeScript (optional)
307
452
 
308
- 1. Log in to gateway as a user tied to an **enabled** merchant.
309
- 2. Open `/sparo`.
310
- 3. Open DevTools → **Network**:
311
- - Confirm `GET /sparo/token` returns `200` with `token`, `expiresIn`, `account`.
312
- 4. Open DevTools → **Console**:
313
- - No `Module not found` for `@swirepay-developer/sparo-embed-sdk`.
314
- 5. Confirm iframe loads (Elements tab → `iframe` under your mount div).
315
- 6. SPARO UI should appear without a SPARO login page.
453
+ ```tsx
454
+ import { useEffect, useRef } from 'react';
455
+ import {
456
+ embed,
457
+ createGuestTokenFetcher,
458
+ type EmbedHandle,
459
+ type SparoEmbedError,
460
+ } from '@swirepay-developer/sparo-embed-sdk';
461
+ import { getGatewayAccessToken } from 'utils/sparoAuth';
316
462
 
317
- ### Staging vs production
463
+ export function SparoChat(): JSX.Element {
464
+ const mountRef = useRef<HTMLDivElement>(null);
465
+ const handleRef = useRef<EmbedHandle | null>(null);
318
466
 
319
- | Environment | `REACT_APP_SPARO_DOMAIN` | Backend mint URL |
320
- |-------------|--------------------------|------------------|
321
- | Staging | Staging SPARO host | Same SPARO env as domain |
322
- | Production | `https://sparo.swirepay.com` (or prod host) | Production SPARO API |
467
+ useEffect(() => {
468
+ const el = mountRef.current;
469
+ if (!el) return undefined;
470
+
471
+ handleRef.current = embed({
472
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN!,
473
+ mountPoint: el,
474
+ fetchGuestToken: createGuestTokenFetcher(
475
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL!,
476
+ { getAuthorization: getGatewayAccessToken },
477
+ ),
478
+ onError: (err: SparoEmbedError) => {
479
+ console.error(err.code, err.message);
480
+ },
481
+ });
323
482
 
324
- Mismatch (staging token + production domain) causes auth failures.
483
+ return () => handleRef.current?.unmount();
484
+ }, []);
485
+
486
+ return <div ref={mountRef} style={{ width: '100%', height: 720 }} />;
487
+ }
488
+ ```
325
489
 
326
490
  ---
327
491
 
328
- ## Step 7 — SDK API reference (what you pass)
492
+ ### Sample 8 — Manual refresh button (optional)
329
493
 
330
- ### `embed(options)`
494
+ The SDK auto-refreshes ~30s before expiry. Use this only if you need a user-triggered refresh:
331
495
 
332
- | Option | Required | Description |
333
- |--------|----------|-------------|
334
- | `sparoDomain` | Yes | SPARO host, e.g. `https://sparo.swirepay.com` |
335
- | `mountPoint` | Yes | DOM element (use `ref.current`) |
336
- | `fetchGuestToken` | Yes | Async function returning `{ token, expiresIn, account }` |
337
- | `id` | No | iframe id (default `sparo-embed`) |
338
- | `uiConfig` | No | Theme and UI flags (see below) |
339
- | `onReady` | No | Called when iframe signals ready |
340
- | `onError` | No | Called on token/iframe errors |
496
+ ```jsx
497
+ const handleRef = useRef(null);
341
498
 
342
- ### `uiConfig` (optional)
499
+ // inside embed setup:
500
+ handleRef.current = embed({ ... });
343
501
 
344
- ```js
345
- {
346
- theme: 'light', // 'light' | 'dark'
347
- showWelcome: true,
348
- showSuggestions: true,
349
- hideSidebar: false,
350
- }
502
+ // in JSX:
503
+ <button
504
+ type="button"
505
+ onClick={() => handleRef.current?.refresh()}
506
+ >
507
+ Refresh SPARO session
508
+ </button>
351
509
  ```
352
510
 
353
- ### Return value
511
+ ---
354
512
 
355
- ```js
356
- const handle = embed({ ... });
513
+ ## Backend API contract
514
+
515
+ Gateway Java validates the logged-in user and returns a short-lived SPARO guest JWT.
357
516
 
358
- handle.refresh(); // manually refresh token (usually not needed)
359
- handle.unmount(); // cleanup — call on route leave (useEffect return)
517
+ ```http
518
+ GET /v1/sparo/guest-token
519
+ Authorization: Bearer <gateway-session-jwt>
520
+ Accept: application/json
360
521
  ```
361
522
 
362
- Token refresh is **automatic** ~30 seconds before expiry.
523
+ **Response `200`:** (either direct payload, or wrapped in `entity`)
363
524
 
364
- ---
525
+ ```json
526
+ {
527
+ "token": "eyJhbGciOi...",
528
+ "expiresIn": 900,
529
+ "account": "account-72ec92..."
530
+ }
531
+ ```
365
532
 
366
- ## Step 8 — Security checklist (frontend)
533
+ Java wrapper example (also supported):
367
534
 
368
- - Do not store `SPARO_ADMIN_KEY` in frontend.
369
- - Do not put guest `token` in URL query params.
370
- - Do not hardcode production tokens in source.
371
- - Always use `credentials: 'include'` if session is cookie-based.
372
- - Always `unmount()` when leaving the page (see `useEffect` cleanup).
373
- - Size the mount container with CSS (`height: 720px` or full viewport).
535
+ ```json
536
+ {
537
+ "message": "OK",
538
+ "entity": {
539
+ "token": "eyJhbGciOi...",
540
+ "expiresIn": 600,
541
+ "account": "account-72ec92..."
542
+ },
543
+ "responseCode": 200,
544
+ "status": "SUCCESS"
545
+ }
546
+ ```
374
547
 
375
- ---
548
+ Wrapped responses (`{ "data": { ... } }` or `{ "entity": { ... } }`) are handled automatically by `createGuestTokenFetcher` / `normalizeGuestTokenResponse`.
376
549
 
377
- ## Troubleshooting
550
+ ### Refresh behavior (no refresh token policy)
378
551
 
379
- ### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
552
+ - The guest JWT is **short-lived** (`expiresIn` seconds).
553
+ - The SDK **automatically re-calls** the same Java API before expiry (approximately `expiresIn - 30s`), and re-authenticates the iframe.
554
+ - Gateway React should **not** build a separate timer if it uses `embed()` — just provide `fetchGuestToken`.
380
555
 
381
- **Wrong package name.** DevOps published `@swirepay-developer/sparo-embed-sdk@1.0.5`, not `@swirepay/sparo-embed-sdk`.
556
+ > Backend best practice: include `account` explicitly in the payload. If omitted, the SDK can infer it from the JWT `account` claim (or the previous token), but explicit is preferred.
382
557
 
383
- Update **both**:
558
+ | HTTP | SDK `err.code` | UI suggestion |
559
+ |------|----------------|---------------|
560
+ | 401 | `invalid_token` | Redirect to login |
561
+ | 403 | `merchant_not_enabled` | Contact support |
562
+ | 429 | `rate_limited` | Retry later |
563
+ | 5xx | `fetch_failed` | Generic error |
384
564
 
385
- ```js
386
- // SparoChat.js — change this line
387
- import { embed } from '@swirepay-developer/sparo-embed-sdk';
388
- ```
565
+ ---
389
566
 
390
- ```json
391
- // package.json
392
- "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
393
- ```
567
+ ## Test locally
394
568
 
395
- Then:
569
+ 1. Log in as a user tied to an **enabled** merchant.
570
+ 2. Open `/sparo`.
571
+ 3. **Network:** `GET .../v1/sparo/guest-token` → `200` JSON with `token`, `expiresIn`, `account`.
572
+ 4. **Console:** no `Module not found` errors.
573
+ 5. **Elements:** `iframe` under mount div; SPARO UI without login screen.
396
574
 
397
575
  ```bash
398
- npm uninstall @swirepay/sparo-embed-sdk
399
- npm install @swirepay-developer/sparo-embed-sdk
400
- npm start
576
+ yarn start
401
577
  ```
402
578
 
403
- Add to gateway `.npmrc` (no token in git — use env in CI):
579
+ ---
580
+
581
+ ## SDK exports reference
404
582
 
405
- ```ini
406
- @swirepay-developer:registry=https://registry.npmjs.org/
583
+ ```js
584
+ import {
585
+ embed, // main entry — mount SPARO iframe
586
+ createGuestTokenFetcher, // build fetchGuestToken for Java API
587
+ normalizeGuestTokenResponse, // unwrap { data: {...} } from Java
588
+ } from '@swirepay-developer/sparo-embed-sdk';
407
589
  ```
408
590
 
409
- ---
591
+ ### Error codes (`onError`)
410
592
 
411
- ### `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
593
+ | Code | Meaning |
594
+ |------|---------|
595
+ | `merchant_not_enabled` | Merchant not on SPARO allowlist (403) |
596
+ | `invalid_token` | 401 or malformed token response |
597
+ | `expired_token` | Token expired before refresh |
598
+ | `fetch_failed` | Network, CORS, or non-JSON error |
599
+ | `iframe_load_failed` | iframe did not load |
600
+ | `rate_limited` | 429 from backend |
412
601
 
413
- Webpack shows this when the package is **not installed** under `node_modules` (install failed or was never run).
602
+ ---
414
603
 
415
- **Step 0 — verify the package exists on your registry**
604
+ ## Security checklist
416
605
 
417
- From `gateway-frontend`:
606
+ - Do not store `SPARO_ADMIN_KEY` in frontend code.
607
+ - Do not put guest `token` in URL query params.
608
+ - Pass JWT via `getAuthorization` at runtime only.
609
+ - Always call `handle.unmount()` in `useEffect` cleanup.
610
+ - Size mount container with CSS (`height: 720px` minimum).
418
611
 
419
- ```bash
420
- npm view @swirepay-developer/sparo-embed-sdk version
421
- ```
612
+ ---
422
613
 
423
- | Result | Meaning |
424
- |--------|---------|
425
- | `1.0.5` (or similar) | Published — go to Step 1 |
426
- | `404 Not Found` | **Not on registry.npmjs.org** (or wrong scope/name). `npm install` will not add the package → this error persists |
614
+ ## Troubleshooting
427
615
 
428
- If you see **404**, DevOps has not published yet (or gateway lacks npm read access to `@swirepay-developer`). Do not merge gateway code that imports the SDK until `npm view` returns a version.
616
+ ### `Module not found: Can't resolve '@swirepay/sparo-embed-sdk'`
429
617
 
430
- **Step 1 — install and confirm**
618
+ Wrong scope. Use `@swirepay-developer/sparo-embed-sdk`:
431
619
 
432
620
  ```bash
433
- cd gateway-frontend
434
- npm install @swirepay-developer/sparo-embed-sdk
435
- dir node_modules\@swirepay-developer\sparo-embed-sdk\dist
621
+ yarn add @swirepay-developer/sparo-embed-sdk
436
622
  ```
437
623
 
438
- You must see `index.js` and `index.mjs` in that folder. If the folder is missing, the install did not succeed.
439
-
440
- **Step 2**
441
-
442
- 1. Restart `npm start` (CRA caches module resolution).
443
- 2. In `package.json`, use a normal semver dependency — not a broken `file:` path to a machine-specific folder unless every dev shares that path.
444
-
445
- ### Blank iframe / “Awaiting auth”
446
-
447
- - Check `/sparo/token` returns valid JSON shape.
448
- - Confirm `account` matches an allowlisted merchant.
449
- - Confirm `sparoDomain` matches token mint environment (HTTPS in prod).
624
+ ### `Module not found: Can't resolve '@swirepay-developer/sparo-embed-sdk'`
450
625
 
451
- ### Mixed content blocked
626
+ ```bash
627
+ npm view @swirepay-developer/sparo-embed-sdk version
628
+ ```
452
629
 
453
- - Page is `https://` but `sparoDomain` is `http://` → use HTTPS SPARO URL.
630
+ If version prints, run `yarn add` and restart dev server. If `404`, SDK not published yet.
454
631
 
455
- ### `merchant_not_enabled` (403)
632
+ ### Guest-token returns HTML / 404
456
633
 
457
- - Merchant not on SPARO allowlist — contact SPARO admin, not a frontend bug.
634
+ Wrong `REACT_APP_SPARO_GUEST_TOKEN_URL` — must be Java API URL, not a React route.
458
635
 
459
- ### `fetch_failed`
636
+ ### Blank iframe
460
637
 
461
- - Backend down, CORS issue, or user session expired.
462
- - Check Network tab on `/sparo/token`.
638
+ - Response missing `token`, `expiresIn`, or `account`.
639
+ - `REACT_APP_SPARO_DOMAIN` mismatched with token environment (staging vs prod).
463
640
 
464
641
  ### Iframe works on refresh but not first load
465
642
 
466
- - Ensure `mountRef.current` exists before calling `embed` (use `useEffect`, not render body).
467
- - Do not call `embed` with `null` mount point.
643
+ Call `embed` inside `useEffect` after `mountRef.current` is set.
468
644
 
469
645
  ---
470
646
 
471
- ## Minimal checklist
647
+ ## Checklist
472
648
 
473
- - [ ] `npm install @swirepay-developer/sparo-embed-sdk`
474
- - [ ] `REACT_APP_SPARO_DOMAIN` set per environment
475
- - [ ] Backend `/sparo/token` implemented and tested
476
- - [ ] `SparoChat` component with `useEffect` + `unmount` cleanup
477
- - [ ] Route registered (e.g. `/sparo`)
478
- - [ ] User has access to enabled merchant
479
- - [ ] Dev server restarted after install
649
+ - [ ] `yarn add @swirepay-developer/sparo-embed-sdk`
650
+ - [ ] Env vars set (`REACT_APP_SPARO_GUEST_TOKEN_URL`, `REACT_APP_SPARO_DOMAIN`)
651
+ - [ ] `getGatewayAccessToken` wired in `src/utils/sparoAuth.js`
652
+ - [ ] `SparoChat` uses `embed` + `createGuestTokenFetcher`
653
+ - [ ] `useEffect` cleanup calls `handle.unmount()`
654
+ - [ ] Route `/sparo` registered
655
+ - [ ] Dev server restarted after install / env changes
480
656
 
481
657
  ---
482
658
 
483
659
  ## Related docs
484
660
 
485
- - [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) — full architecture and backend mint examples
661
+ - [SPARO-EMBEDDING.md](./SPARO-EMBEDDING.md) — architecture and backend contract
662
+ - [examples/embed-vanilla.html](./examples/embed-vanilla.html) — vanilla JS example (no React)
486
663
  - [INSTALL.md](./INSTALL.md) — npm install troubleshooting
487
- - [SECURITY.md](./SECURITY.md) — trust boundaries and secrets
488
-
489
- ---
490
-
491
- ## Support contacts
492
-
493
- | Issue | Contact |
494
- |-------|---------|
495
- | SDK npm / import errors | Frontend platform / SDK maintainers |
496
- | `/sparo/token` / `SPARO_ADMIN_KEY` | Backend team |
497
- | Merchant allowlist | SPARO admin |
664
+ - [SECURITY.md](./SECURITY.md) — trust boundaries
package/README.md CHANGED
@@ -12,7 +12,7 @@
12
12
  |------|--------|
13
13
  | **You (SDK)** | Push this repo to Bitbucket (`sdkmaster` or release branch). Bump version in `package.json` for each release. |
14
14
  | **DevOps** | Clone repo → `npm ci` → `npm publish`. See **[DEVOPS-NPM-PUBLISH.md](./DEVOPS-NPM-PUBLISH.md)**. |
15
- | **Gateway developer** | After publish: `npm install @swirepay-developer/sparo-embed-sdk` and follow **[GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md)**. |
15
+ | **Gateway developer** | SDK: [GATEWAY-REACT-GUIDE.md](./GATEWAY-REACT-GUIDE.md) · Middleware: [../sparo-key-backend](../sparo-key-backend) |
16
16
 
17
17
  Until DevOps publishes, gateway will show:
18
18
 
@@ -31,7 +31,7 @@ npm install @swirepay-developer/sparo-embed-sdk
31
31
  ```json
32
32
  {
33
33
  "dependencies": {
34
- "@swirepay-developer/sparo-embed-sdk": "^1.0.5"
34
+ "@swirepay-developer/sparo-embed-sdk": "^1.0.8"
35
35
  }
36
36
  }
37
37
  ```
@@ -40,23 +40,39 @@ Private package: use [.npmrc.example](./.npmrc.example) with org `NPM_TOKEN` (De
40
40
 
41
41
  ---
42
42
 
43
- ## Quick Start
43
+ ## Quick Start (Java guest-token API)
44
+
45
+ Gateway Java API (URLs from **host env**, not SDK):
46
+
47
+ | Environment | Guest-token URL |
48
+ |-------------|-----------------|
49
+ | Staging | `https://staging-backend.swirepay.com/v1/sparo/guest-token` |
50
+ | Production | `https://backend.swirepay.com/v1/sparo/guest-token` |
44
51
 
45
52
  ```js
46
- import { embed } from '@swirepay-developer/sparo-embed-sdk';
53
+ import {
54
+ embed,
55
+ createGuestTokenFetcher,
56
+ } from '@swirepay-developer/sparo-embed-sdk';
47
57
 
48
58
  const handle = embed({
49
59
  id: 'sparo-chat',
50
- sparoDomain: 'https://sparo.swirepay.com',
60
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
51
61
  mountPoint: document.getElementById('sparo'),
52
- fetchGuestToken: async () => {
53
- const res = await fetch('/sparo/token', { credentials: 'include' });
54
- if (!res.ok) throw new Error('token fetch failed');
55
- return await res.json(); // { token, expiresIn, account }
56
- },
62
+
63
+ fetchGuestToken: createGuestTokenFetcher(
64
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
65
+ { getAuthorization: getGatewayBearerToken },
66
+ ),
67
+
68
+ uiConfig: { theme: 'light' },
69
+ onReady: () => console.log('[Sparo] ready'),
70
+ onError: (err) => console.error('[Sparo]', err.code, err.message),
57
71
  });
58
72
  ```
59
73
 
74
+ `getGatewayBearerToken()` returns the logged-in user's gateway JWT (same as other API calls).
75
+
60
76
  ---
61
77
 
62
78
  ## Docs
@@ -7,12 +7,21 @@ Embed the SPARO assistant into your application with short-lived guest JWTs, no
7
7
 
8
8
  ## Architecture
9
9
 
10
- 1. User opens your page.
11
- 2. SDK calls `fetchGuestToken()` in your app.
12
- 3. Your backend calls SPARO mint endpoint with `SPARO_ADMIN_KEY`.
13
- 4. SPARO returns guest JWT (`token`, `expiresIn`).
14
- 5. SDK creates iframe and posts auth via `postMessage` (never URL token).
15
- 6. SDK refreshes token automatically before expiry.
10
+ Same pattern as **Apache Superset embedded analytics**:
11
+
12
+ | Role | Superset | SPARO |
13
+ |------|----------|-------|
14
+ | React SDK | `@superset-ui/embedded-sdk` | `@swirepay-developer/sparo-embed-sdk` |
15
+ | Guest-token middleware | `supersetmiddleware` | **`sparo-key-backend`** |
16
+ | Guest-token route | `POST /guest-token` | `POST /guest-token` |
17
+ | Embedded app | Superset UI URL | `sparoDomain` (e.g. `https://sparo-stag.swirepay.com`) |
18
+
19
+ 1. User opens your page (gateway, Cognito session).
20
+ 2. SDK calls `fetchGuestToken()` → **sparo-key-backend** `POST /guest-token` (Cognito Bearer).
21
+ 3. Middleware loads `SPARO_ADMIN_KEY` from AWS Secrets Manager (`swirepay-sparoai/dev/backend-env`).
22
+ 4. Middleware calls SPARO `POST /api/guest-token`.
23
+ 5. SDK receives `{ token, expiresIn, account }`, loads iframe, `postMessage` auth.
24
+ 6. SDK auto-refreshes before expiry.
16
25
 
17
26
  ## Prerequisites
18
27
 
@@ -21,34 +30,50 @@ Embed the SPARO assistant into your application with short-lived guest JWTs, no
21
30
  - Merchant allowlisted in SPARO.
22
31
  - Your backend endpoint that authenticates end users and returns guest token.
23
32
 
24
- ## Backend Token Mint Endpoint
33
+ ## Backend — Java guest-token API
25
34
 
26
- `POST https://sparo.swirepay.com/api/guest-token`
35
+ Gateway Java validates the user and mints the SPARO guest JWT.
27
36
 
28
- Headers:
29
- - `Authorization: Bearer <SPARO_ADMIN_KEY>`
30
- - `Content-Type: application/json`
37
+ ```http
38
+ GET https://staging-backend.swirepay.com/v1/sparo/guest-token
39
+ Authorization: Bearer <gateway-session-jwt>
40
+ Accept: application/json
41
+ ```
42
+
43
+ Production: `https://backend.swirepay.com/v1/sparo/guest-token`
31
44
 
32
- Body:
45
+ **Response** (direct or wrapped in `data`):
33
46
 
34
47
  ```json
35
48
  {
36
- "user": "user-abc",
37
- "account": "account-72ec92...",
38
- "scope": ["chat:read", "chat:write"],
39
- "ttl": 900
49
+ "token": "eyJhbGciOi...",
50
+ "expiresIn": 900,
51
+ "account": "account-72ec92..."
40
52
  }
41
53
  ```
42
54
 
43
- Response:
55
+ SDK usage:
44
56
 
45
- ```json
46
- {
47
- "token": "eyJhbGciOi...",
48
- "expiresIn": 900
49
- }
57
+ ```js
58
+ import { embed, createGuestTokenFetcher } from '@swirepay-developer/sparo-embed-sdk';
59
+
60
+ embed({
61
+ sparoDomain: process.env.REACT_APP_SPARO_DOMAIN,
62
+ mountPoint: document.getElementById('sparo'),
63
+ fetchGuestToken: createGuestTokenFetcher(
64
+ process.env.REACT_APP_SPARO_GUEST_TOKEN_URL,
65
+ { getAuthorization: getGatewayBearerToken },
66
+ ),
67
+ });
50
68
  ```
51
69
 
70
+ Two URLs (host config):
71
+
72
+ | Variable | Example |
73
+ |----------|---------|
74
+ | `REACT_APP_SPARO_GUEST_TOKEN_URL` | `https://staging-backend.swirepay.com/v1/sparo/guest-token` |
75
+ | `REACT_APP_SPARO_DOMAIN` | `https://sparo-stag.swirepay.com` |
76
+
52
77
  ## Frontend Integration
53
78
 
54
79
  ```html
@@ -56,20 +81,24 @@ Response:
56
81
  ```
57
82
 
58
83
  ```js
59
- import { embed } from '@swirepay-developer/sparo-embed-sdk';
84
+ import {
85
+ embed,
86
+ createGuestTokenFetcher,
87
+ } from '@swirepay-developer/sparo-embed-sdk';
60
88
 
61
89
  const handle = embed({
62
90
  id: 'sparo-chat',
63
91
  sparoDomain: 'https://sparo.swirepay.com',
64
92
  mountPoint: document.getElementById('sparo'),
65
- fetchGuestToken: async () => {
66
- const res = await fetch('/sparo/token', { credentials: 'include' });
67
- if (!res.ok) throw new Error('token fetch failed');
68
- return await res.json(); // { token, expiresIn, account }
69
- },
93
+
94
+ // Java BFF: GET /sparo/token (credentials: include)
95
+ fetchGuestToken: createGuestTokenFetcher('/sparo/token'),
96
+
70
97
  uiConfig: { theme: 'light' },
71
98
  onReady: () => console.log('[Sparo] ready'),
72
99
  onError: (err) => {
100
+ // err.code: merchant_not_enabled | invalid_token | expired_token |
101
+ // fetch_failed | iframe_load_failed
73
102
  console.error('[Sparo]', err.code, err.message);
74
103
  },
75
104
  });
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});module.exports=G(P);function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let d=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let l=!0,T=!1,m=null,p=null,y=()=>{p&&(window.clearTimeout(p),p=null)},h=n=>{b&&b(n)},S=()=>{if(!l||!T||!m)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:m.token,account:m.account,uiConfig:v},d)},D=n=>{y();let r=Math.max(5,n-30);p=window.setTimeout(()=>{w().catch(()=>{})},r*1e3)},w=async()=>{if(!l)return;let n;try{n=await c()}catch(f){let R=a("fetch_failed",(f==null?void 0:f.message)||"Failed to fetch guest token");throw h(R),R}let r=H(n);m=r,D(r.expiresIn);let u=N(d,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!l||n.origin!==d)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",f=a(u,r.message||u,r.status);h(f)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),w().catch(n=>{h(n)}),{refresh:()=>w(),unmount:()=>{l=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;0&&(module.exports={embed});
1
+ var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var s in t)y(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of M(t))!F.call(e,u)&&u!==s&&y(e,u,{get:()=>t[u],enumerable:!(r=D(t,u))||r.enumerable});return e};var N=e=>z(y({},"__esModule",{value:!0}),e);var U={};I(U,{createGuestTokenFetcher:()=>L,default:()=>G,embed:()=>_,normalizeGuestTokenResponse:()=>E});module.exports=N(U);function O(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function p(e,t,s){let r=new Error(t||e);return r.code=e,typeof s=="number"&&(r.status=s),r}function P(e){if(!e||typeof e!="object")throw p("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw p("invalid_token","Missing token in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw p("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:typeof e.account=="string"?e.account:void 0,expiresIn:t}}function H(e,t){let s=new URLSearchParams({embed:"true"});return typeof t=="string"&&t&&s.set("account",t),`${e}/embed.html?${s.toString()}`}function _(e){let{id:t="sparo-embed",sparoDomain:s,mountPoint:r,fetchGuestToken:u,uiConfig:k={},onReady:g,onError:d}=e||{};if(!r||!(r instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof u!="function")throw new Error("fetchGuestToken must be a function");let a=O(s),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let c=!0,f=!1,l=null,h=null,x=()=>{h&&(window.clearTimeout(h),h=null)},T=n=>{d&&d(b(n))},b=n=>n&&typeof n=="object"&&n.code?n:p("fetch_failed",(n==null?void 0:n.message)||"SPARO embed error"),R=()=>{if(!c||!f||!l)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:l.token,...l.account?{account:l.account}:{},uiConfig:k},a)},v=n=>{x();let i=Math.max(5,n-30);h=window.setTimeout(()=>{w().catch(()=>{})},i*1e3)},w=async()=>{if(!c)return;let n;try{n=await u()}catch(j){let A=b(j);throw T(A),A}let i=P(n);l=i,v(i.expiresIn);let m=H(a,i.account);!o.src||o.src!==m?o.src=m:R()},S=n=>{if(!c||n.origin!==a)return;let i=n.data;if(!(!i||typeof i!="object"||typeof i.type!="string")){if(i.type==="sparo:ready"||i.type==="SPARO_EMBED_READY"){f=!0,R(),g&&g();return}if(i.type==="sparo:error"){let m=i.code||"iframe_error";if(m==="expired_token"){w().catch(()=>{});return}T(p(m,i.message||m,i.status))}}};return o.addEventListener("error",()=>{T(p("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",S),r.innerHTML="",r.appendChild(o),w().catch(()=>{}),{refresh:()=>w(),unmount:()=>{c=!1,x(),window.removeEventListener("message",S),o.parentNode===r&&r.removeChild(o)}}}var G=_;function E(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function L(e,t={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:s,init:r={}}=t,u=r.method||"GET",k=r.credentials??(s?"omit":"include");return async function(){let d=new Headers(r.headers||{});if(s){let f=await s();f&&d.set("Authorization",f.startsWith("Bearer ")?f:`Bearer ${f}`)}d.has("Accept")||d.set("Accept","application/json");let a=await fetch(e,{...r,method:u,credentials:k,headers:d}),o=a.headers.get("content-type")||"",c={};if(o.includes("application/json")?c=await a.json().catch(()=>({})):a.ok||(c={message:(await a.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!a.ok){let f=E(c)||c,l=new Error(f.message||f.error||c.message||c.error||`token fetch failed (${a.status})`);throw l.code=f.code||c.code||(a.status===403?"merchant_not_enabled":a.status===401?"invalid_token":"fetch_failed"),l.status=a.status,l}return E(c)}}0&&(module.exports={createGuestTokenFetcher,embed,normalizeGuestTokenResponse});
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- function v(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function c(e,o,i){let s=new Error(o||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function D(e){if(!e||typeof e!="object")throw c("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw c("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw c("invalid_token","Missing account in fetchGuestToken response");let o=Number(e.expiresIn||900);if(!Number.isFinite(o)||o<=0)throw c("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:o}}function L(e,o){let i=new URLSearchParams({embed:"true",account:o});return`${e}/embed.html?${i.toString()}`}function _(e){let{id:o="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:w,uiConfig:R={},onReady:E,onError:g}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof w!="function")throw new Error("fetchGuestToken must be a function");let p=v(i),r=document.createElement("iframe");r.id=o,r.title="SPARO Assistant",r.style.width="100%",r.style.height="100%",r.style.border="0",r.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),r.setAttribute("referrerpolicy","no-referrer");let f=!0,k=!1,l=null,m=null,b=()=>{m&&(window.clearTimeout(m),m=null)},d=t=>{g&&g(t)},T=()=>{if(!f||!k||!l)return;let t=r.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:R},p)},x=t=>{b();let n=Math.max(5,t-30);m=window.setTimeout(()=>{h().catch(()=>{})},n*1e3)},h=async()=>{if(!f)return;let t;try{t=await w()}catch(u){let S=c("fetch_failed",(u==null?void 0:u.message)||"Failed to fetch guest token");throw d(S),S}let n=D(t);l=n,x(n.expiresIn);let a=L(p,n.account);!r.src||r.src!==a?r.src=a:T()},y=t=>{if(!f||t.origin!==p)return;let n=t.data;if(!(!n||typeof n!="object"||typeof n.type!="string")){if(n.type==="sparo:ready"||n.type==="SPARO_EMBED_READY"){k=!0,T(),E&&E();return}if(n.type==="sparo:error"){let a=n.code||"iframe_error",u=c(a,n.message||a,n.status);d(u)}}};return window.addEventListener("message",y),s.innerHTML="",s.appendChild(r),h().catch(t=>{d(t)}),{refresh:()=>h(),unmount:()=>{f=!1,b(),window.removeEventListener("message",y),r.parentNode===s&&s.removeChild(r)}}}var M=_;export{M as default,_ as embed};
1
+ function L(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function m(e,s,f){let r=new Error(s||e);return r.code=e,typeof f=="number"&&(r.status=f),r}function v(e){if(!e||typeof e!="object")throw m("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw m("invalid_token","Missing token in fetchGuestToken response");let s=Number(e.expiresIn||900);if(!Number.isFinite(s)||s<=0)throw m("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:typeof e.account=="string"?e.account:void 0,expiresIn:s}}function j(e,s){let f=new URLSearchParams({embed:"true"});return typeof s=="string"&&s&&f.set("account",s),`${e}/embed.html?${f.toString()}`}function S(e){let{id:s="sparo-embed",sparoDomain:f,mountPoint:r,fetchGuestToken:p,uiConfig:E={},onReady:k,onError:l}=e||{};if(!r||!(r instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof p!="function")throw new Error("fetchGuestToken must be a function");let i=L(f),n=document.createElement("iframe");n.id=s,n.title="SPARO Assistant",n.style.width="100%",n.style.height="100%",n.style.border="0",n.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),n.setAttribute("referrerpolicy","no-referrer");let a=!0,c=!1,u=null,h=null,y=()=>{h&&(window.clearTimeout(h),h=null)},g=t=>{l&&l(_(t))},_=t=>t&&typeof t=="object"&&t.code?t:m("fetch_failed",(t==null?void 0:t.message)||"SPARO embed error"),x=()=>{if(!a||!c||!u)return;let t=n.contentWindow;!t||typeof t.postMessage!="function"||t.postMessage({type:"sparo:auth",token:u.token,...u.account?{account:u.account}:{},uiConfig:E},i)},A=t=>{y();let o=Math.max(5,t-30);h=window.setTimeout(()=>{w().catch(()=>{})},o*1e3)},w=async()=>{if(!a)return;let t;try{t=await p()}catch(G){let R=_(G);throw g(R),R}let o=v(t);u=o,A(o.expiresIn);let d=j(i,o.account);!n.src||n.src!==d?n.src=d:x()},b=t=>{if(!a||t.origin!==i)return;let o=t.data;if(!(!o||typeof o!="object"||typeof o.type!="string")){if(o.type==="sparo:ready"||o.type==="SPARO_EMBED_READY"){c=!0,x(),k&&k();return}if(o.type==="sparo:error"){let d=o.code||"iframe_error";if(d==="expired_token"){w().catch(()=>{});return}g(m(d,o.message||d,o.status))}}};return n.addEventListener("error",()=>{g(m("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",b),r.innerHTML="",r.appendChild(n),w().catch(()=>{}),{refresh:()=>w(),unmount:()=>{a=!1,y(),window.removeEventListener("message",b),n.parentNode===r&&r.removeChild(n)}}}var D=S;function T(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function M(e,s={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:f,init:r={}}=s,p=r.method||"GET",E=r.credentials??(f?"omit":"include");return async function(){let l=new Headers(r.headers||{});if(f){let c=await f();c&&l.set("Authorization",c.startsWith("Bearer ")?c:`Bearer ${c}`)}l.has("Accept")||l.set("Accept","application/json");let i=await fetch(e,{...r,method:p,credentials:E,headers:l}),n=i.headers.get("content-type")||"",a={};if(n.includes("application/json")?a=await i.json().catch(()=>({})):i.ok||(a={message:(await i.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!i.ok){let c=T(a)||a,u=new Error(c.message||c.error||a.message||a.error||`token fetch failed (${i.status})`);throw u.code=c.code||a.code||(i.status===403?"merchant_not_enabled":i.status===401?"invalid_token":"fetch_failed"),u.status=i.status,u}return T(a)}}export{M as createGuestTokenFetcher,D as default,S as embed,T as normalizeGuestTokenResponse};
@@ -1 +1 @@
1
- var SparoEmbedSDK=(()=>{var E=Object.defineProperty;var L=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var A=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var i in t)E(e,i,{get:t[i],enumerable:!0})},F=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of M(t))!A.call(e,c)&&c!==i&&E(e,c,{get:()=>t[c],enumerable:!(s=L(t,c))||s.enumerable});return e};var G=e=>F(E({},"__esModule",{value:!0}),e);var P={};I(P,{default:()=>x,embed:()=>g});function C(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function a(e,t,i){let s=new Error(t||e);return s.code=e,typeof i=="number"&&(s.status=i),s}function H(e){if(!e||typeof e!="object")throw a("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw a("invalid_token","Missing token in fetchGuestToken response");if(!e.account||typeof e.account!="string")throw a("invalid_token","Missing account in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw a("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:e.account,expiresIn:t}}function N(e,t){let i=new URLSearchParams({embed:"true",account:t});return`${e}/embed.html?${i.toString()}`}function g(e){let{id:t="sparo-embed",sparoDomain:i,mountPoint:s,fetchGuestToken:c,uiConfig:v={},onReady:k,onError:b}=e||{};if(!s||!(s instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof c!="function")throw new Error("fetchGuestToken must be a function");let p=C(i),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let f=!0,T=!1,l=null,m=null,y=()=>{m&&(window.clearTimeout(m),m=null)},d=n=>{b&&b(n)},S=()=>{if(!f||!T||!l)return;let n=o.contentWindow;!n||typeof n.postMessage!="function"||n.postMessage({type:"sparo:auth",token:l.token,account:l.account,uiConfig:v},p)},D=n=>{y();let r=Math.max(5,n-30);m=window.setTimeout(()=>{h().catch(()=>{})},r*1e3)},h=async()=>{if(!f)return;let n;try{n=await c()}catch(w){let R=a("fetch_failed",w?.message||"Failed to fetch guest token");throw d(R),R}let r=H(n);l=r,D(r.expiresIn);let u=N(p,r.account);!o.src||o.src!==u?o.src=u:S()},_=n=>{if(!f||n.origin!==p)return;let r=n.data;if(!(!r||typeof r!="object"||typeof r.type!="string")){if(r.type==="sparo:ready"||r.type==="SPARO_EMBED_READY"){T=!0,S(),k&&k();return}if(r.type==="sparo:error"){let u=r.code||"iframe_error",w=a(u,r.message||u,r.status);d(w)}}};return window.addEventListener("message",_),s.innerHTML="",s.appendChild(o),h().catch(n=>{d(n)}),{refresh:()=>h(),unmount:()=>{f=!1,y(),window.removeEventListener("message",_),o.parentNode===s&&s.removeChild(o)}}}var x=g;return G(P);})();
1
+ var SparoEmbedSDK=(()=>{var y=Object.defineProperty;var D=Object.getOwnPropertyDescriptor;var M=Object.getOwnPropertyNames;var F=Object.prototype.hasOwnProperty;var I=(e,t)=>{for(var s in t)y(e,s,{get:t[s],enumerable:!0})},z=(e,t,s,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let u of M(t))!F.call(e,u)&&u!==s&&y(e,u,{get:()=>t[u],enumerable:!(n=D(t,u))||n.enumerable});return e};var N=e=>z(y({},"__esModule",{value:!0}),e);var U={};I(U,{createGuestTokenFetcher:()=>L,default:()=>G,embed:()=>_,normalizeGuestTokenResponse:()=>E});function O(e){try{return new URL(e).origin}catch{throw new Error("Invalid sparoDomain. Expected absolute URL, e.g. https://sparo.swirepay.com")}}function p(e,t,s){let n=new Error(t||e);return n.code=e,typeof s=="number"&&(n.status=s),n}function P(e){if(!e||typeof e!="object")throw p("fetch_failed","fetchGuestToken must return an object");if(!e.token||typeof e.token!="string")throw p("invalid_token","Missing token in fetchGuestToken response");let t=Number(e.expiresIn||900);if(!Number.isFinite(t)||t<=0)throw p("invalid_token","Invalid expiresIn in fetchGuestToken response");return{token:e.token,account:typeof e.account=="string"?e.account:void 0,expiresIn:t}}function H(e,t){let s=new URLSearchParams({embed:"true"});return typeof t=="string"&&t&&s.set("account",t),`${e}/embed.html?${s.toString()}`}function _(e){let{id:t="sparo-embed",sparoDomain:s,mountPoint:n,fetchGuestToken:u,uiConfig:k={},onReady:g,onError:d}=e||{};if(!n||!(n instanceof HTMLElement))throw new Error("mountPoint must be a valid HTMLElement");if(typeof u!="function")throw new Error("fetchGuestToken must be a function");let a=O(s),o=document.createElement("iframe");o.id=t,o.title="SPARO Assistant",o.style.width="100%",o.style.height="100%",o.style.border="0",o.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms allow-popups allow-modals"),o.setAttribute("referrerpolicy","no-referrer");let c=!0,f=!1,l=null,h=null,x=()=>{h&&(window.clearTimeout(h),h=null)},T=r=>{d&&d(b(r))},b=r=>r&&typeof r=="object"&&r.code?r:p("fetch_failed",r?.message||"SPARO embed error"),R=()=>{if(!c||!f||!l)return;let r=o.contentWindow;!r||typeof r.postMessage!="function"||r.postMessage({type:"sparo:auth",token:l.token,...l.account?{account:l.account}:{},uiConfig:k},a)},v=r=>{x();let i=Math.max(5,r-30);h=window.setTimeout(()=>{w().catch(()=>{})},i*1e3)},w=async()=>{if(!c)return;let r;try{r=await u()}catch(j){let A=b(j);throw T(A),A}let i=P(r);l=i,v(i.expiresIn);let m=H(a,i.account);!o.src||o.src!==m?o.src=m:R()},S=r=>{if(!c||r.origin!==a)return;let i=r.data;if(!(!i||typeof i!="object"||typeof i.type!="string")){if(i.type==="sparo:ready"||i.type==="SPARO_EMBED_READY"){f=!0,R(),g&&g();return}if(i.type==="sparo:error"){let m=i.code||"iframe_error";if(m==="expired_token"){w().catch(()=>{});return}T(p(m,i.message||m,i.status))}}};return o.addEventListener("error",()=>{T(p("iframe_load_failed","Unable to load SPARO embed iframe"))}),window.addEventListener("message",S),n.innerHTML="",n.appendChild(o),w().catch(()=>{}),{refresh:()=>w(),unmount:()=>{c=!1,x(),window.removeEventListener("message",S),o.parentNode===n&&n.removeChild(o)}}}var G=_;function E(e){return!e||typeof e!="object"?e:e.data&&typeof e.data=="object"&&e.data.token?e.data:e.entity&&typeof e.entity=="object"&&e.entity.token?e.entity:e}function L(e,t={}){if(!e||typeof e!="string")throw new Error("createGuestTokenFetcher(tokenUrl) requires a URL string");let{getAuthorization:s,init:n={}}=t,u=n.method||"GET",k=n.credentials??(s?"omit":"include");return async function(){let d=new Headers(n.headers||{});if(s){let f=await s();f&&d.set("Authorization",f.startsWith("Bearer ")?f:`Bearer ${f}`)}d.has("Accept")||d.set("Accept","application/json");let a=await fetch(e,{...n,method:u,credentials:k,headers:d}),o=a.headers.get("content-type")||"",c={};if(o.includes("application/json")?c=await a.json().catch(()=>({})):a.ok||(c={message:(await a.text().catch(()=>"")).slice(0,200)||"Non-JSON error response"}),!a.ok){let f=E(c)||c,l=new Error(f.message||f.error||c.message||c.error||`token fetch failed (${a.status})`);throw l.code=f.code||c.code||(a.status===403?"merchant_not_enabled":a.status===401?"invalid_token":"fetch_failed"),l.status=a.status,l}return E(c)}}return N(U);})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirepay-developer/sparo-embed-sdk",
3
- "version": "1.0.5",
3
+ "version": "1.0.8",
4
4
  "description": "SPARO embedding SDK for guest-token based iframe integration",
5
5
  "private": false,
6
6
  "license": "UNLICENSED",
package/types/index.d.ts CHANGED
@@ -9,7 +9,7 @@ export type UiConfig = {
9
9
  export type GuestTokenResponse = {
10
10
  token: string;
11
11
  expiresIn: number;
12
- account: string;
12
+ account?: string;
13
13
  };
14
14
 
15
15
  export type SparoEmbedErrorCode =
@@ -44,5 +44,21 @@ export type EmbedHandle = {
44
44
  };
45
45
 
46
46
  export declare function embed(options: EmbedOptions): EmbedHandle;
47
+
48
+ export type CreateGuestTokenFetcherOptions = {
49
+ /** Returns gateway session JWT (called on mount and each SDK refresh). */
50
+ getAuthorization?: () => string | Promise<string>;
51
+ init?: RequestInit;
52
+ };
53
+
54
+ export declare function normalizeGuestTokenResponse(
55
+ body: unknown,
56
+ ): GuestTokenResponse;
57
+
58
+ export declare function createGuestTokenFetcher(
59
+ tokenUrl: string,
60
+ options?: CreateGuestTokenFetcherOptions,
61
+ ): () => Promise<GuestTokenResponse>;
62
+
47
63
  export default embed;
48
64