@integralscope/command-transfer-checkout-js 0.1.4 → 0.1.6

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 CHANGED
@@ -33,7 +33,7 @@ Your site never talks to the pay UI as source code. The SDK only opens Command T
33
33
 
34
34
  ## 1. Create the checkout on your server
35
35
 
36
- When the customer is ready to pay, your backend creates a checkout with your **secret API key**. Return only the public session to the browser:
36
+ When the customer is ready to pay, your backend creates a checkout. This browser SDK never calls that API. Return only the public session to the browser:
37
37
 
38
38
  ```json
39
39
  {
@@ -42,26 +42,54 @@ When the customer is ready to pay, your backend creates a checkout with your **s
42
42
  }
43
43
  ```
44
44
 
45
- Do not put the secret key in frontend env, HTML, or the SDK.
45
+ Do not put the secret key in frontend env, HTML, or this package.
46
+
47
+ Development API (Command Transfer staging):
48
+
49
+ - Base URL: `https://ct-dev-api-482193062708.us-central1.run.app`
50
+ - Spec: [Swagger](https://ct-dev-api-482193062708.us-central1.run.app/swagger/index.html#/)
51
+
52
+ `POST /v1/checkout` requires `Authorization: Bearer sk_…` and `Idempotency-Key`. Amounts are **minor units**.
46
53
 
47
54
  Example merchant endpoint:
48
55
 
49
56
  ```js
50
- // server
57
+ // server only — never ship sk_ to the browser
58
+ const CT_API = process.env.COMMAND_TRANSFER_API_ORIGIN;
59
+ const CT_SECRET = process.env.COMMAND_TRANSFER_SECRET_KEY;
60
+
51
61
  app.post("/api/checkout", async (req, res) => {
52
- const session = await createCommandTransferCheckout({
53
- amount: 450000,
54
- currency: "NGN",
55
- // ...your order fields
62
+ const response = await fetch(`${CT_API}/v1/checkout`, {
63
+ method: "POST",
64
+ headers: {
65
+ Authorization: `Bearer ${CT_SECRET}`,
66
+ "Content-Type": "application/json",
67
+ "Idempotency-Key": crypto.randomUUID(),
68
+ },
69
+ body: JSON.stringify({
70
+ amount: 450000,
71
+ currency: "NGN",
72
+ customer_email: req.body.email,
73
+ reference: req.body.orderId,
74
+ }),
56
75
  });
57
76
 
77
+ if (!response.ok) {
78
+ res.status(502).json({ error: "checkout_create_failed" });
79
+ return;
80
+ }
81
+
82
+ const session = await response.json();
83
+
58
84
  res.json({
59
- intentId: session.id,
85
+ intentId: session.intent.id,
60
86
  clientToken: session.client_token,
61
87
  });
62
88
  });
63
89
  ```
64
90
 
91
+ Store `COMMAND_TRANSFER_SECRET_KEY` only on the server. Do not log `client_token`.
92
+
65
93
  The browser then:
66
94
 
67
95
  ```js
@@ -109,7 +137,7 @@ checkout.on("error", ({ code, message }) => {
109
137
  });
110
138
  ```
111
139
 
112
- The SDK opens Checkout Web from the origin Command Transfer bakes in at build time (`VITE_CHECKOUT_ORIGIN`).
140
+ The SDK opens Checkout Web, where the customer pays by card or bank transfer. Do not collect card details on your site or send them through this SDK.
113
141
 
114
142
  ### Inline
115
143
 
@@ -153,7 +181,7 @@ On completion they land on `returnUrl` with query params:
153
181
 
154
182
  | Param | Meaning |
155
183
  | -------------- | -------------------------------------------- |
156
- | `checkout_id` | The checkout you created |
184
+ | `checkout_id` | The checkout you have created |
157
185
  | `reference` | Present when payment succeeded |
158
186
  | `status` | `success` or an error code |
159
187
 
@@ -196,9 +224,9 @@ If the customer had not finished paying, this emits `cancel`.
196
224
  After `success` or a redirect return:
197
225
 
198
226
  1. Send `intentId` to your backend.
199
- 2. Fetch the checkout from Command Transfer with your secret key.
200
- 3. Fulfill only when status is `SUCCEEDED`.
201
- 4. Ignore a client `success` event that your API does not confirm.
227
+ 2. Your server calls `GET /v1/checkout/{intentID}` with `Authorization: Bearer sk_…`.
228
+ 3. Fulfill only when `intent.status` is `SUCCEEDED`.
229
+ 4. Ignore a browser `success` event that your API does not confirm.
202
230
 
203
231
  ```js
204
232
  checkout.on("success", async ({ intentId }) => {
@@ -214,6 +242,18 @@ checkout.on("success", async ({ intentId }) => {
214
242
  });
215
243
  ```
216
244
 
245
+ Server confirm (same secret, never from this SDK):
246
+
247
+ ```js
248
+ const response = await fetch(`${CT_API}/v1/checkout/${intentId}`, {
249
+ headers: { Authorization: `Bearer ${CT_SECRET}` },
250
+ });
251
+ const checkout = await response.json();
252
+ const paid = checkout.intent?.status === "SUCCEEDED";
253
+ ```
254
+
255
+ Do not call `/v1/checkout/.../client` or card-attempt routes from the merchant page. Those use the payer `ctc_…` token and belong on Command Transfer Checkout Web, not in this SDK.
256
+
217
257
  ## Config
218
258
 
219
259
  | Field | Required | Notes |
@@ -248,7 +288,8 @@ If you set a Content-Security-Policy on your site, allow Command Transfer’s ch
248
288
 
249
289
  ## Rules
250
290
 
251
- - Secret API keys stay on your server.
291
+ - Secret API keys (`sk_…`) stay on your server. This package must not receive them.
252
292
  - `clientToken` is a payer capability for that checkout. Do not log it, put it in query strings, or persist it in `localStorage`.
253
- - `success` in the browser is UX only. Fulfill from server-side confirmation.
293
+ - `success` in the browser is UX only. Fulfill from server-side `GET /v1/checkout/{intentID}` when status is `SUCCEEDED`.
254
294
  - Do not load checkout from your own storefront.
295
+ - Do not call Command Transfer admin, auth, or business APIs from the browser.
@@ -10,11 +10,11 @@ class f {
10
10
  }
11
11
  emit(e, t) {
12
12
  const n = this.listeners.get(e);
13
- n && [...n].forEach((i) => {
13
+ n && [...n].forEach((o) => {
14
14
  try {
15
- i(t);
16
- } catch (o) {
17
- console.error(`Checkout "${String(e)}" handler failed.`, o);
15
+ o(t);
16
+ } catch (i) {
17
+ console.error(`Checkout "${String(e)}" handler failed.`, i);
18
18
  }
19
19
  });
20
20
  }
@@ -28,14 +28,14 @@ function m(r) {
28
28
  }
29
29
  const a = m(
30
30
  "https://ct-dev-checkout.web.app"
31
- ), g = /* @__PURE__ */ new Set([
31
+ ), w = /* @__PURE__ */ new Set([
32
32
  "checkout.ready",
33
33
  "checkout.success",
34
34
  "checkout.cancel",
35
35
  "checkout.error",
36
36
  "checkout.resize"
37
37
  ]);
38
- function w(r) {
38
+ function g(r) {
39
39
  return !!r && typeof r == "object" && !Array.isArray(r);
40
40
  }
41
41
  function c(r, e) {
@@ -44,10 +44,10 @@ function c(r, e) {
44
44
  return !t || t.length > e || /[\u0000-\u001f\u007f]/.test(t) ? null : t;
45
45
  }
46
46
  function k(r, e) {
47
- if (!w(r) || r.source !== s)
47
+ if (!g(r) || r.source !== s)
48
48
  return null;
49
49
  const t = c(r.type, 64);
50
- if (!t || !g.has(t))
50
+ if (!t || !w.has(t))
51
51
  return null;
52
52
  const n = c(r.checkoutId, 128);
53
53
  if (n !== e)
@@ -60,12 +60,12 @@ function k(r, e) {
60
60
  checkoutId: n
61
61
  };
62
62
  case "checkout.success": {
63
- const i = c(r.reference, 128);
64
- return i ? {
63
+ const o = c(r.reference, 128);
64
+ return o ? {
65
65
  source: s,
66
66
  type: t,
67
67
  checkoutId: n,
68
- reference: i
68
+ reference: o
69
69
  } : null;
70
70
  }
71
71
  case "checkout.cancel":
@@ -75,22 +75,22 @@ function k(r, e) {
75
75
  checkoutId: n
76
76
  };
77
77
  case "checkout.error": {
78
- const i = c(r.code, 64), o = c(r.message, 280);
79
- return !i || !o ? null : {
78
+ const o = c(r.code, 64), i = c(r.message, 280);
79
+ return !o || !i ? null : {
80
80
  source: s,
81
81
  type: t,
82
82
  checkoutId: n,
83
- code: i,
84
- message: o
83
+ code: o,
84
+ message: i
85
85
  };
86
86
  }
87
87
  case "checkout.resize": {
88
- const i = typeof r.height == "number" ? r.height : Number(r.height);
89
- return !Number.isFinite(i) || i < 200 || i > 4e3 ? null : {
88
+ const o = typeof r.height == "number" ? r.height : Number(r.height);
89
+ return !Number.isFinite(o) || o < 200 || o > 4e3 ? null : {
90
90
  source: s,
91
91
  type: t,
92
92
  checkoutId: n,
93
- height: Math.round(i)
93
+ height: Math.round(o)
94
94
  };
95
95
  }
96
96
  default:
@@ -148,9 +148,10 @@ class y {
148
148
  "allow-forms",
149
149
  "allow-popups",
150
150
  "allow-popups-to-escape-sandbox",
151
+ "allow-modals",
151
152
  "allow-top-navigation-by-user-activation"
152
153
  ].join(" ")
153
- ), e.style.width = "100%", e.style.height = "640px", e.style.border = "0", e.style.display = "block", e.style.background = "#f3f0ff", e.style.borderRadius = this.presentation === "modal" ? "16px" : "0", e;
154
+ ), e.style.width = "100%", e.style.height = "720px", e.style.border = "0", e.style.display = "block", e.style.background = "#f3f0ff", e.style.borderRadius = this.presentation === "modal" ? "16px" : "0", e;
154
155
  }
155
156
  mountModal(e) {
156
157
  const t = document.createElement("div");
@@ -173,8 +174,8 @@ class y {
173
174
  "border-radius:16px",
174
175
  "box-shadow:0 24px 64px rgba(15,12,41,0.28)"
175
176
  ].join(";");
176
- const i = document.createElement("button");
177
- i.type = "button", i.setAttribute("aria-label", "Close checkout"), i.textContent = "×", i.style.cssText = [
177
+ const o = document.createElement("button");
178
+ o.type = "button", o.setAttribute("aria-label", "Close checkout"), o.textContent = "×", o.style.cssText = [
178
179
  "position:absolute",
179
180
  "top:8px",
180
181
  "right:8px",
@@ -189,11 +190,11 @@ class y {
189
190
  "line-height:1",
190
191
  "cursor:pointer",
191
192
  "box-shadow:0 2px 8px rgba(15,12,41,0.16)"
192
- ].join(";"), i.addEventListener("click", this.onCloseRequest), t.addEventListener("click", (o) => {
193
- o.target === t && this.onCloseRequest();
194
- }), this.escapeListener = (o) => {
195
- o.key === "Escape" && this.onCloseRequest();
196
- }, window.addEventListener("keydown", this.escapeListener), this.previousBodyOverflow = document.body.style.overflow, document.body.style.overflow = "hidden", n.append(i, e), t.appendChild(n), document.body.appendChild(t), this.overlay = t, i.focus();
193
+ ].join(";"), o.addEventListener("click", this.onCloseRequest), t.addEventListener("click", (i) => {
194
+ i.target === t && this.onCloseRequest();
195
+ }), this.escapeListener = (i) => {
196
+ i.key === "Escape" && this.onCloseRequest();
197
+ }, window.addEventListener("keydown", this.escapeListener), this.previousBodyOverflow = document.body.style.overflow, document.body.style.overflow = "hidden", n.append(o, e), t.appendChild(n), document.body.appendChild(t), this.overlay = t, o.focus();
197
198
  }
198
199
  teardownModal() {
199
200
  this.escapeListener && (window.removeEventListener("keydown", this.escapeListener), this.escapeListener = null), this.overlay?.remove(), this.overlay = null, this.previousBodyOverflow !== null && (document.body.style.overflow = this.previousBodyOverflow, this.previousBodyOverflow = null);
@@ -216,11 +217,11 @@ function l(r) {
216
217
  function E(r) {
217
218
  const e = r.split(".");
218
219
  if (e.length !== 4) return !1;
219
- const t = e.map((o) => Number(o));
220
- if (t.some((o) => !Number.isInteger(o) || o < 0 || o > 255))
220
+ const t = e.map((i) => Number(i));
221
+ if (t.some((i) => !Number.isInteger(i) || i < 0 || i > 255))
221
222
  return !1;
222
- const [n, i] = t;
223
- return n === 10 || n === 127 || n === 192 && i === 168 || n === 172 && i >= 16 && i <= 31;
223
+ const [n, o] = t;
224
+ return n === 10 || n === 127 || n === 192 && o === 168 || n === 172 && o >= 16 && o <= 31;
224
225
  }
225
226
  function I(r) {
226
227
  const e = h(r);
@@ -276,16 +277,16 @@ function L(r) {
276
277
  throw new Error("Checkout config is required.");
277
278
  if (!r.intentId?.trim())
278
279
  throw new Error("intentId is required.");
279
- const e = C(r.intentId), t = x(r.clientToken ?? ""), n = M(), i = r.mode ?? "inline";
280
- if (i !== "inline" && i !== "modal" && i !== "redirect")
280
+ const e = C(r.intentId), t = x(r.clientToken ?? ""), n = M(), o = r.mode ?? "inline";
281
+ if (o !== "inline" && o !== "modal" && o !== "redirect")
281
282
  throw new Error('mode must be "inline", "modal", or "redirect".');
282
- const o = r.returnUrl ? O(r.returnUrl, "returnUrl") : void 0;
283
+ const i = r.returnUrl ? O(r.returnUrl, "returnUrl") : void 0;
283
284
  return {
284
285
  intentId: e,
285
286
  clientToken: t,
286
287
  checkoutOrigin: n,
287
- mode: i,
288
- returnUrl: o
288
+ mode: o,
289
+ returnUrl: i
289
290
  };
290
291
  }
291
292
  class T {
@@ -368,10 +369,10 @@ class T {
368
369
  const n = e === "modal" ? document.body : b(t);
369
370
  if (!n)
370
371
  throw new Error("Checkout container was not found.");
371
- const i = this.getCheckoutUrl(e);
372
+ const o = this.getCheckoutUrl(e);
372
373
  this.iframeManager = new y({
373
374
  checkoutId: this.config.intentId,
374
- checkoutUrl: i,
375
+ checkoutUrl: o,
375
376
  checkoutOrigin: this.config.checkoutOrigin,
376
377
  presentation: e,
377
378
  onMessage: this.handleMessage,
@@ -1 +1 @@
1
- (function(s,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(s=typeof globalThis<"u"?globalThis:s||self,u(s.CommandTransferCheckout={}))})(this,(function(s){"use strict";class u{constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{n?.delete(t)}}emit(e,t){const n=this.listeners.get(e);n&&[...n].forEach(o=>{try{o(t)}catch(i){console.error(`Checkout "${String(e)}" handler failed.`,i)}})}removeAllListeners(){this.listeners.clear()}}const c="commandtransfer.checkout",h="ctc_";function g(r){return r?.trim()||""}const l=g("https://ct-dev-checkout.web.app"),w=new Set(["checkout.ready","checkout.success","checkout.cancel","checkout.error","checkout.resize"]);function k(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function a(r,e){if(typeof r!="string")return null;const t=r.trim();return!t||t.length>e||/[\u0000-\u001f\u007f]/.test(t)?null:t}function p(r,e){if(!k(r)||r.source!==c)return null;const t=a(r.type,64);if(!t||!w.has(t))return null;const n=a(r.checkoutId,128);if(n!==e)return null;switch(t){case"checkout.ready":return{source:c,type:t,checkoutId:n};case"checkout.success":{const o=a(r.reference,128);return o?{source:c,type:t,checkoutId:n,reference:o}:null}case"checkout.cancel":return{source:c,type:t,checkoutId:n};case"checkout.error":{const o=a(r.code,64),i=a(r.message,280);return!o||!i?null:{source:c,type:t,checkoutId:n,code:o,message:i}}case"checkout.resize":{const o=typeof r.height=="number"?r.height:Number(r.height);return!Number.isFinite(o)||o<200||o>4e3?null:{source:c,type:t,checkoutId:n,height:Math.round(o)}}default:return null}}class y{constructor(e){this.sourceWindow=null,this.handleMessage=t=>{if(t.origin!==this.checkoutOrigin||!this.sourceWindow||t.source!==this.sourceWindow)return;const n=p(t.data,this.checkoutId);n&&this.onMessage(n)},this.checkoutId=e.checkoutId,this.checkoutOrigin=e.checkoutOrigin,this.onMessage=e.onMessage,window.addEventListener("message",this.handleMessage)}setSourceWindow(e){this.sourceWindow=e}destroy(){window.removeEventListener("message",this.handleMessage),this.sourceWindow=null}}class b{constructor(e){this.iframe=null,this.overlay=null,this.previousBodyOverflow=null,this.escapeListener=null,this.checkoutUrl=e.checkoutUrl,this.presentation=e.presentation,this.onCloseRequest=e.onCloseRequest,this.bridge=new y({checkoutId:e.checkoutId,checkoutOrigin:e.checkoutOrigin,onMessage:e.onMessage})}mount(e){if(this.iframe)throw new Error("Checkout iframe is already mounted.");const t=this.createIframe();this.presentation==="modal"?this.mountModal(t):e.appendChild(t),this.iframe=t,this.bridge.setSourceWindow(t.contentWindow),t.addEventListener("load",()=>{this.bridge.setSourceWindow(t.contentWindow)})}setHeight(e){this.iframe&&(this.iframe.style.height=`${Math.round(e)}px`)}destroy(){this.bridge.destroy(),this.iframe?.remove(),this.iframe=null,this.teardownModal()}createIframe(){const e=document.createElement("iframe");return e.src=this.checkoutUrl,e.title="Command Transfer checkout",e.setAttribute("allow","payment; clipboard-write; publickey-credentials-get"),e.setAttribute("referrerpolicy","no-referrer"),e.setAttribute("sandbox",["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-popups-to-escape-sandbox","allow-top-navigation-by-user-activation"].join(" ")),e.style.width="100%",e.style.height="640px",e.style.border="0",e.style.display="block",e.style.background="#f3f0ff",e.style.borderRadius=this.presentation==="modal"?"16px":"0",e}mountModal(e){const t=document.createElement("div");t.setAttribute("data-ct-checkout","overlay"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Payment checkout"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:24px 16px","background:rgba(15,12,41,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:relative","width:min(420px,100%)","max-height:calc(100vh - 48px)","overflow:auto","border-radius:16px","box-shadow:0 24px 64px rgba(15,12,41,0.28)"].join(";");const o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close checkout"),o.textContent="×",o.style.cssText=["position:absolute","top:8px","right:8px","z-index:1","width:32px","height:32px","border:0","border-radius:999px","background:#ffffff","color:#1e1654","font-size:22px","line-height:1","cursor:pointer","box-shadow:0 2px 8px rgba(15,12,41,0.16)"].join(";"),o.addEventListener("click",this.onCloseRequest),t.addEventListener("click",i=>{i.target===t&&this.onCloseRequest()}),this.escapeListener=i=>{i.key==="Escape"&&this.onCloseRequest()},window.addEventListener("keydown",this.escapeListener),this.previousBodyOverflow=document.body.style.overflow,document.body.style.overflow="hidden",n.append(o,e),t.appendChild(n),document.body.appendChild(t),this.overlay=t,o.focus()}teardownModal(){this.escapeListener&&(window.removeEventListener("keydown",this.escapeListener),this.escapeListener=null),this.overlay?.remove(),this.overlay=null,this.previousBodyOverflow!==null&&(document.body.style.overflow=this.previousBodyOverflow,this.previousBodyOverflow=null)}}function v(r){if(typeof r!="string")return r;const e=r.trim();return e?e.startsWith("#")||e.startsWith(".")||e.startsWith("[")?document.querySelector(e):document.getElementById(e)??document.querySelector(e):null}const C=/^[A-Za-z0-9._:-]{1,128}$/;function d(r){return r.replace(/^\[|\]$/g,"").toLowerCase()}function f(r){const e=d(r);return e==="localhost"||e==="127.0.0.1"||e==="::1"}function E(r){const e=r.split(".");if(e.length!==4)return!1;const t=e.map(i=>Number(i));if(t.some(i=>!Number.isInteger(i)||i<0||i>255))return!1;const[n,o]=t;return n===10||n===127||n===192&&o===168||n===172&&o>=16&&o<=31}function I(r){const e=d(r);return f(e)||E(e)?!0:e.endsWith(".local")||e.endsWith(".test")||e.endsWith(".localhost")}function x(r){const e=r.trim();if(!C.test(e))throw new Error("intentId is invalid.");return e}function M(r){const e=r.trim(),t=e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():e;if(!t.toLowerCase().startsWith(h))throw new Error(`clientToken is invalid. Expected a token starting with ${h}.`);if(t.length>512||/\s/.test(t))throw new Error("clientToken is invalid.");return t}function m(r,e,t){let n;try{n=new URL(r)}catch{throw new Error(`${e} is not a valid URL.`)}if(n.username||n.password)throw new Error(`${e} must not include credentials.`);if(n.protocol==="https:"||n.protocol==="http:"&&t(n.hostname))return n;throw new Error(`${e} must be an https URL.`)}function O(){if(!l)throw new Error("checkout origin is not configured.");return m(l,"checkout origin",f).origin}function U(r,e){return m(r,e,I).toString()}function T(r){const e=encodeURIComponent(r.intentId),t=new URL(`/pay/${e}`,r.checkoutOrigin);return r.mode==="redirect"?r.returnUrl&&t.searchParams.set("return_url",r.returnUrl):(t.searchParams.set("embed","1"),r.parentOrigin&&t.searchParams.set("origin",r.parentOrigin)),t.hash=`token=${encodeURIComponent(r.clientToken)}`,t.toString()}function L(r){if(!r||typeof r!="object")throw new Error("Checkout config is required.");if(!r.intentId?.trim())throw new Error("intentId is required.");const e=x(r.intentId),t=M(r.clientToken??""),n=O(),o=r.mode??"inline";if(o!=="inline"&&o!=="modal"&&o!=="redirect")throw new Error('mode must be "inline", "modal", or "redirect".');const i=r.returnUrl?U(r.returnUrl,"returnUrl"):void 0;return{intentId:e,clientToken:t,checkoutOrigin:n,mode:o,returnUrl:i}}class S{constructor(e){this.events=new u,this.iframeManager=null,this.mounted=!1,this.settled=!1,this.handleMessage=t=>{switch(t.type){case"checkout.ready":this.events.emit("ready",{intentId:t.checkoutId});break;case"checkout.success":this.settled=!0,this.events.emit("success",{intentId:t.checkoutId,reference:t.reference}),this.teardownFrame();break;case"checkout.cancel":this.settled=!0,this.events.emit("cancel",void 0),this.teardownFrame();break;case"checkout.error":this.settled=!0,this.events.emit("error",{code:t.code,message:t.message}),this.teardownFrame();break;case"checkout.resize":this.iframeManager?.setHeight(t.height);break}},this.config=L(e),this.containerOption=e.container}start(e){if(this.config.mode==="redirect"){this.redirect();return}if(this.config.mode==="modal"){this.open();return}this.mount(e??this.containerOption)}mount(e){this.mountFrame("inline",e??this.containerOption)}open(){this.mountFrame("modal",document.body)}redirect(){window.location.assign(this.getCheckoutUrl("redirect"))}on(e,t){return this.events.on(e,t)}close(){const e=this.mounted;this.teardownFrame(),e&&!this.settled&&(this.settled=!0,this.events.emit("cancel",void 0))}getCheckoutUrl(e){return T({intentId:this.config.intentId,clientToken:this.config.clientToken,checkoutOrigin:this.config.checkoutOrigin,mode:e,returnUrl:this.config.returnUrl,parentOrigin:e==="redirect"?void 0:window.location.origin})}mountFrame(e,t){if(this.mounted)throw new Error("Checkout is already mounted.");if(!t)throw new Error("Checkout container was not found.");const n=e==="modal"?document.body:v(t);if(!n)throw new Error("Checkout container was not found.");const o=this.getCheckoutUrl(e);this.iframeManager=new b({checkoutId:this.config.intentId,checkoutUrl:o,checkoutOrigin:this.config.checkoutOrigin,presentation:e,onMessage:this.handleMessage,onCloseRequest:()=>this.close()}),this.iframeManager.mount(n),this.mounted=!0}teardownFrame(){this.iframeManager?.destroy(),this.iframeManager=null,this.mounted=!1}}s.Checkout=S,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
1
+ (function(s,u){typeof exports=="object"&&typeof module<"u"?u(exports):typeof define=="function"&&define.amd?define(["exports"],u):(s=typeof globalThis<"u"?globalThis:s||self,u(s.CommandTransferCheckout={}))})(this,(function(s){"use strict";class u{constructor(){this.listeners=new Map}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>{n?.delete(t)}}emit(e,t){const n=this.listeners.get(e);n&&[...n].forEach(o=>{try{o(t)}catch(i){console.error(`Checkout "${String(e)}" handler failed.`,i)}})}removeAllListeners(){this.listeners.clear()}}const c="commandtransfer.checkout",h="ctc_";function g(r){return r?.trim()||""}const l=g("https://ct-dev-checkout.web.app"),w=new Set(["checkout.ready","checkout.success","checkout.cancel","checkout.error","checkout.resize"]);function k(r){return!!r&&typeof r=="object"&&!Array.isArray(r)}function a(r,e){if(typeof r!="string")return null;const t=r.trim();return!t||t.length>e||/[\u0000-\u001f\u007f]/.test(t)?null:t}function p(r,e){if(!k(r)||r.source!==c)return null;const t=a(r.type,64);if(!t||!w.has(t))return null;const n=a(r.checkoutId,128);if(n!==e)return null;switch(t){case"checkout.ready":return{source:c,type:t,checkoutId:n};case"checkout.success":{const o=a(r.reference,128);return o?{source:c,type:t,checkoutId:n,reference:o}:null}case"checkout.cancel":return{source:c,type:t,checkoutId:n};case"checkout.error":{const o=a(r.code,64),i=a(r.message,280);return!o||!i?null:{source:c,type:t,checkoutId:n,code:o,message:i}}case"checkout.resize":{const o=typeof r.height=="number"?r.height:Number(r.height);return!Number.isFinite(o)||o<200||o>4e3?null:{source:c,type:t,checkoutId:n,height:Math.round(o)}}default:return null}}class y{constructor(e){this.sourceWindow=null,this.handleMessage=t=>{if(t.origin!==this.checkoutOrigin||!this.sourceWindow||t.source!==this.sourceWindow)return;const n=p(t.data,this.checkoutId);n&&this.onMessage(n)},this.checkoutId=e.checkoutId,this.checkoutOrigin=e.checkoutOrigin,this.onMessage=e.onMessage,window.addEventListener("message",this.handleMessage)}setSourceWindow(e){this.sourceWindow=e}destroy(){window.removeEventListener("message",this.handleMessage),this.sourceWindow=null}}class b{constructor(e){this.iframe=null,this.overlay=null,this.previousBodyOverflow=null,this.escapeListener=null,this.checkoutUrl=e.checkoutUrl,this.presentation=e.presentation,this.onCloseRequest=e.onCloseRequest,this.bridge=new y({checkoutId:e.checkoutId,checkoutOrigin:e.checkoutOrigin,onMessage:e.onMessage})}mount(e){if(this.iframe)throw new Error("Checkout iframe is already mounted.");const t=this.createIframe();this.presentation==="modal"?this.mountModal(t):e.appendChild(t),this.iframe=t,this.bridge.setSourceWindow(t.contentWindow),t.addEventListener("load",()=>{this.bridge.setSourceWindow(t.contentWindow)})}setHeight(e){this.iframe&&(this.iframe.style.height=`${Math.round(e)}px`)}destroy(){this.bridge.destroy(),this.iframe?.remove(),this.iframe=null,this.teardownModal()}createIframe(){const e=document.createElement("iframe");return e.src=this.checkoutUrl,e.title="Command Transfer checkout",e.setAttribute("allow","payment; clipboard-write; publickey-credentials-get"),e.setAttribute("referrerpolicy","no-referrer"),e.setAttribute("sandbox",["allow-scripts","allow-same-origin","allow-forms","allow-popups","allow-popups-to-escape-sandbox","allow-modals","allow-top-navigation-by-user-activation"].join(" ")),e.style.width="100%",e.style.height="720px",e.style.border="0",e.style.display="block",e.style.background="#f3f0ff",e.style.borderRadius=this.presentation==="modal"?"16px":"0",e}mountModal(e){const t=document.createElement("div");t.setAttribute("data-ct-checkout","overlay"),t.setAttribute("role","dialog"),t.setAttribute("aria-modal","true"),t.setAttribute("aria-label","Payment checkout"),t.style.cssText=["position:fixed","inset:0","z-index:2147483647","display:flex","align-items:center","justify-content:center","padding:24px 16px","background:rgba(15,12,41,0.55)"].join(";");const n=document.createElement("div");n.style.cssText=["position:relative","width:min(420px,100%)","max-height:calc(100vh - 48px)","overflow:auto","border-radius:16px","box-shadow:0 24px 64px rgba(15,12,41,0.28)"].join(";");const o=document.createElement("button");o.type="button",o.setAttribute("aria-label","Close checkout"),o.textContent="×",o.style.cssText=["position:absolute","top:8px","right:8px","z-index:1","width:32px","height:32px","border:0","border-radius:999px","background:#ffffff","color:#1e1654","font-size:22px","line-height:1","cursor:pointer","box-shadow:0 2px 8px rgba(15,12,41,0.16)"].join(";"),o.addEventListener("click",this.onCloseRequest),t.addEventListener("click",i=>{i.target===t&&this.onCloseRequest()}),this.escapeListener=i=>{i.key==="Escape"&&this.onCloseRequest()},window.addEventListener("keydown",this.escapeListener),this.previousBodyOverflow=document.body.style.overflow,document.body.style.overflow="hidden",n.append(o,e),t.appendChild(n),document.body.appendChild(t),this.overlay=t,o.focus()}teardownModal(){this.escapeListener&&(window.removeEventListener("keydown",this.escapeListener),this.escapeListener=null),this.overlay?.remove(),this.overlay=null,this.previousBodyOverflow!==null&&(document.body.style.overflow=this.previousBodyOverflow,this.previousBodyOverflow=null)}}function v(r){if(typeof r!="string")return r;const e=r.trim();return e?e.startsWith("#")||e.startsWith(".")||e.startsWith("[")?document.querySelector(e):document.getElementById(e)??document.querySelector(e):null}const C=/^[A-Za-z0-9._:-]{1,128}$/;function d(r){return r.replace(/^\[|\]$/g,"").toLowerCase()}function f(r){const e=d(r);return e==="localhost"||e==="127.0.0.1"||e==="::1"}function E(r){const e=r.split(".");if(e.length!==4)return!1;const t=e.map(i=>Number(i));if(t.some(i=>!Number.isInteger(i)||i<0||i>255))return!1;const[n,o]=t;return n===10||n===127||n===192&&o===168||n===172&&o>=16&&o<=31}function I(r){const e=d(r);return f(e)||E(e)?!0:e.endsWith(".local")||e.endsWith(".test")||e.endsWith(".localhost")}function x(r){const e=r.trim();if(!C.test(e))throw new Error("intentId is invalid.");return e}function M(r){const e=r.trim(),t=e.toLowerCase().startsWith("bearer ")?e.slice(7).trim():e;if(!t.toLowerCase().startsWith(h))throw new Error(`clientToken is invalid. Expected a token starting with ${h}.`);if(t.length>512||/\s/.test(t))throw new Error("clientToken is invalid.");return t}function m(r,e,t){let n;try{n=new URL(r)}catch{throw new Error(`${e} is not a valid URL.`)}if(n.username||n.password)throw new Error(`${e} must not include credentials.`);if(n.protocol==="https:"||n.protocol==="http:"&&t(n.hostname))return n;throw new Error(`${e} must be an https URL.`)}function O(){if(!l)throw new Error("checkout origin is not configured.");return m(l,"checkout origin",f).origin}function U(r,e){return m(r,e,I).toString()}function T(r){const e=encodeURIComponent(r.intentId),t=new URL(`/pay/${e}`,r.checkoutOrigin);return r.mode==="redirect"?r.returnUrl&&t.searchParams.set("return_url",r.returnUrl):(t.searchParams.set("embed","1"),r.parentOrigin&&t.searchParams.set("origin",r.parentOrigin)),t.hash=`token=${encodeURIComponent(r.clientToken)}`,t.toString()}function L(r){if(!r||typeof r!="object")throw new Error("Checkout config is required.");if(!r.intentId?.trim())throw new Error("intentId is required.");const e=x(r.intentId),t=M(r.clientToken??""),n=O(),o=r.mode??"inline";if(o!=="inline"&&o!=="modal"&&o!=="redirect")throw new Error('mode must be "inline", "modal", or "redirect".');const i=r.returnUrl?U(r.returnUrl,"returnUrl"):void 0;return{intentId:e,clientToken:t,checkoutOrigin:n,mode:o,returnUrl:i}}class S{constructor(e){this.events=new u,this.iframeManager=null,this.mounted=!1,this.settled=!1,this.handleMessage=t=>{switch(t.type){case"checkout.ready":this.events.emit("ready",{intentId:t.checkoutId});break;case"checkout.success":this.settled=!0,this.events.emit("success",{intentId:t.checkoutId,reference:t.reference}),this.teardownFrame();break;case"checkout.cancel":this.settled=!0,this.events.emit("cancel",void 0),this.teardownFrame();break;case"checkout.error":this.settled=!0,this.events.emit("error",{code:t.code,message:t.message}),this.teardownFrame();break;case"checkout.resize":this.iframeManager?.setHeight(t.height);break}},this.config=L(e),this.containerOption=e.container}start(e){if(this.config.mode==="redirect"){this.redirect();return}if(this.config.mode==="modal"){this.open();return}this.mount(e??this.containerOption)}mount(e){this.mountFrame("inline",e??this.containerOption)}open(){this.mountFrame("modal",document.body)}redirect(){window.location.assign(this.getCheckoutUrl("redirect"))}on(e,t){return this.events.on(e,t)}close(){const e=this.mounted;this.teardownFrame(),e&&!this.settled&&(this.settled=!0,this.events.emit("cancel",void 0))}getCheckoutUrl(e){return T({intentId:this.config.intentId,clientToken:this.config.clientToken,checkoutOrigin:this.config.checkoutOrigin,mode:e,returnUrl:this.config.returnUrl,parentOrigin:e==="redirect"?void 0:window.location.origin})}mountFrame(e,t){if(this.mounted)throw new Error("Checkout is already mounted.");if(!t)throw new Error("Checkout container was not found.");const n=e==="modal"?document.body:v(t);if(!n)throw new Error("Checkout container was not found.");const o=this.getCheckoutUrl(e);this.iframeManager=new b({checkoutId:this.config.intentId,checkoutUrl:o,checkoutOrigin:this.config.checkoutOrigin,presentation:e,onMessage:this.handleMessage,onCloseRequest:()=>this.close()}),this.iframeManager.mount(n),this.mounted=!0}teardownFrame(){this.iframeManager?.destroy(),this.iframeManager=null,this.mounted=!1}}s.Checkout=S,Object.defineProperty(s,Symbol.toStringTag,{value:"Module"})}));
@@ -1 +1 @@
1
- {"version":3,"file":"IframeManager.d.ts","sourceRoot":"","sources":["../../src/iframe/IframeManager.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,UAAU,oBAAoB;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,QAAQ,GAAG,OAAO,CAAC;IACjC,SAAS,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;IAC9C,cAAc,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAkC;IAChD,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,oBAAoB,CAAuB;IACnD,OAAO,CAAC,cAAc,CAAiD;IACvE,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAqB;IAClD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAa;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgB;gBAE3B,OAAO,EAAE,oBAAoB;IAYzC,KAAK,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAoBnC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAQ/B,OAAO,IAAI,IAAI;IAOf,OAAO,CAAC,YAAY;IA8BpB,OAAO,CAAC,UAAU;IAwElB,OAAO,CAAC,aAAa;CActB"}
1
+ {"version":3,"file":"IframeManager.d.ts","sourceRoot":"","sources":["../../src/iframe/IframeManager.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,UAAU,CAAC;AAEhD,UAAU,oBAAoB;IAC5B,UAAU,EAAE,MAAM,CAAC;IACnB,WAAW,EAAE,MAAM,CAAC;IACpB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,QAAQ,GAAG,OAAO,CAAC;IACjC,SAAS,EAAE,CAAC,OAAO,EAAE,eAAe,KAAK,IAAI,CAAC;IAC9C,cAAc,EAAE,MAAM,IAAI,CAAC;CAC5B;AAED,qBAAa,aAAa;IACxB,OAAO,CAAC,MAAM,CAAkC;IAChD,OAAO,CAAC,OAAO,CAA4B;IAC3C,OAAO,CAAC,oBAAoB,CAAuB;IACnD,OAAO,CAAC,cAAc,CAAiD;IACvE,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAS;IACrC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAqB;IAClD,OAAO,CAAC,QAAQ,CAAC,cAAc,CAAa;IAC5C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAgB;gBAE3B,OAAO,EAAE,oBAAoB;IAYzC,KAAK,CAAC,SAAS,EAAE,WAAW,GAAG,IAAI;IAoBnC,SAAS,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI;IAQ/B,OAAO,IAAI,IAAI;IAOf,OAAO,CAAC,YAAY;IA+BpB,OAAO,CAAC,UAAU;IAwElB,OAAO,CAAC,aAAa;CActB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@integralscope/command-transfer-checkout-js",
3
- "version": "0.1.4",
3
+ "version": "0.1.6",
4
4
  "description": "Command Transfer Checkout Web SDK",
5
5
  "repository": {
6
6
  "type": "git",