munim-billing 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/LICENSE +42 -201
  2. package/README.md +8 -27
  3. package/lib/cjs/index.js +2 -28
  4. package/lib/cjs/react-native.js +2 -118
  5. package/lib/cjs/web.js +2 -157
  6. package/lib/esm/chunks/57OHO4KT.js +2 -0
  7. package/lib/esm/client.d.ts +0 -1
  8. package/lib/esm/errors.d.ts +0 -1
  9. package/lib/esm/index.d.ts +0 -1
  10. package/lib/esm/index.js +2 -6
  11. package/lib/esm/react-native.d.ts +0 -1
  12. package/lib/esm/react-native.js +2 -114
  13. package/lib/esm/types.d.ts +5 -1
  14. package/lib/esm/version.d.ts +1 -2
  15. package/lib/esm/web.d.ts +0 -1
  16. package/lib/esm/web.js +2 -152
  17. package/lib/esm/webhooks.d.ts +0 -1
  18. package/package.json +11 -16
  19. package/lib/cjs/client.js +0 -233
  20. package/lib/cjs/client.js.map +0 -1
  21. package/lib/cjs/errors.js +0 -55
  22. package/lib/cjs/errors.js.map +0 -1
  23. package/lib/cjs/index.js.map +0 -1
  24. package/lib/cjs/react-native.js.map +0 -1
  25. package/lib/cjs/types.js +0 -21
  26. package/lib/cjs/types.js.map +0 -1
  27. package/lib/cjs/version.js +0 -6
  28. package/lib/cjs/version.js.map +0 -1
  29. package/lib/cjs/web.js.map +0 -1
  30. package/lib/cjs/webhooks.js +0 -137
  31. package/lib/cjs/webhooks.js.map +0 -1
  32. package/lib/esm/client.d.ts.map +0 -1
  33. package/lib/esm/client.js +0 -226
  34. package/lib/esm/client.js.map +0 -1
  35. package/lib/esm/errors.d.ts.map +0 -1
  36. package/lib/esm/errors.js +0 -50
  37. package/lib/esm/errors.js.map +0 -1
  38. package/lib/esm/index.d.ts.map +0 -1
  39. package/lib/esm/index.js.map +0 -1
  40. package/lib/esm/react-native.d.ts.map +0 -1
  41. package/lib/esm/react-native.js.map +0 -1
  42. package/lib/esm/types.d.ts.map +0 -1
  43. package/lib/esm/types.js +0 -18
  44. package/lib/esm/types.js.map +0 -1
  45. package/lib/esm/version.d.ts.map +0 -1
  46. package/lib/esm/version.js +0 -3
  47. package/lib/esm/version.js.map +0 -1
  48. package/lib/esm/web.d.ts.map +0 -1
  49. package/lib/esm/web.js.map +0 -1
  50. package/lib/esm/webhooks.d.ts.map +0 -1
  51. package/lib/esm/webhooks.js +0 -129
  52. package/lib/esm/webhooks.js.map +0 -1
  53. package/src/client.ts +0 -314
  54. package/src/errors.ts +0 -74
  55. package/src/index.ts +0 -26
  56. package/src/react-native.ts +0 -154
  57. package/src/types.ts +0 -360
  58. package/src/version.ts +0 -2
  59. package/src/web.ts +0 -182
  60. package/src/webhooks.ts +0 -169
package/lib/cjs/web.js CHANGED
@@ -1,157 +1,2 @@
1
- "use strict";
2
- /**
3
- * munim-billing/web: open a Munim checkout from a web page.
4
- *
5
- * Create the checkout on your server (`munim.checkouts.create`) and pass its
6
- * `url` here. Never put your secret key in browser code.
7
- */
8
- Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.redirectToCheckout = redirectToCheckout;
10
- exports.isCheckoutMessage = isCheckoutMessage;
11
- exports.openCheckout = openCheckout;
12
- /** Sends the whole page to the checkout. */
13
- function redirectToCheckout(url) {
14
- assertCheckoutUrl(url);
15
- window.location.assign(url);
16
- }
17
- function assertCheckoutUrl(url) {
18
- let parsed;
19
- try {
20
- parsed = new URL(url);
21
- }
22
- catch {
23
- throw new Error(`munim-billing: not a checkout URL: ${url}`);
24
- }
25
- if (parsed.protocol !== 'https:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') {
26
- throw new Error('munim-billing: checkout URLs must be https.');
27
- }
28
- return parsed;
29
- }
30
- /** Whether a `postMessage` payload is one of the checkout page's messages. */
31
- function isCheckoutMessage(data) {
32
- if (!data || typeof data !== 'object')
33
- return false;
34
- const message = data;
35
- return (message.source === 'munim-billing' &&
36
- (message.type === 'checkout.completed' || message.type === 'checkout.closed') &&
37
- typeof message.checkout_id === 'string');
38
- }
39
- /**
40
- * Shows the checkout in a full-screen overlay on top of your page.
41
- *
42
- * The checkout page tells the overlay when the customer has paid (or wants
43
- * out) with `postMessage`; only messages from the checkout's own origin
44
- * count. Card wallets that need the top window (some bank redirects) still
45
- * work: the checkout page handles those itself.
46
- */
47
- function openCheckout(url, options = {}) {
48
- const parsed = assertCheckoutUrl(url);
49
- const origin = parsed.origin;
50
- // Tell the page it's embedded, so it posts messages instead of redirecting.
51
- parsed.searchParams.set('embed', '1');
52
- const doc = window.document;
53
- const overlay = doc.createElement('div');
54
- overlay.setAttribute('role', 'dialog');
55
- overlay.setAttribute('aria-modal', 'true');
56
- overlay.setAttribute('aria-label', 'Checkout');
57
- overlay.setAttribute('data-munim-billing-overlay', '');
58
- Object.assign(overlay.style, {
59
- position: 'fixed',
60
- inset: '0',
61
- zIndex: String(options.zIndex ?? 2147483000),
62
- background: 'rgba(15, 15, 20, 0.55)',
63
- display: 'flex',
64
- alignItems: 'center',
65
- justifyContent: 'center',
66
- });
67
- const frame = doc.createElement('iframe');
68
- frame.src = parsed.toString();
69
- frame.title = 'Checkout';
70
- // Payment Request (Apple Pay, Google Pay) needs this inside an iframe.
71
- frame.setAttribute('allow', 'payment *');
72
- Object.assign(frame.style, {
73
- width: '100%',
74
- height: '100%',
75
- maxWidth: '480px',
76
- maxHeight: '760px',
77
- border: '0',
78
- borderRadius: '14px',
79
- background: '#ffffff',
80
- boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
81
- });
82
- if (window.matchMedia?.('(max-width: 520px)').matches) {
83
- frame.style.maxWidth = 'none';
84
- frame.style.maxHeight = 'none';
85
- frame.style.borderRadius = '0';
86
- }
87
- const closeButton = doc.createElement('button');
88
- closeButton.type = 'button';
89
- closeButton.setAttribute('aria-label', 'Close checkout');
90
- closeButton.textContent = '×';
91
- Object.assign(closeButton.style, {
92
- position: 'absolute',
93
- top: '12px',
94
- right: '12px',
95
- width: '36px',
96
- height: '36px',
97
- borderRadius: '18px',
98
- border: '0',
99
- background: 'rgba(255,255,255,0.92)',
100
- color: '#111',
101
- fontSize: '24px',
102
- lineHeight: '36px',
103
- cursor: 'pointer',
104
- boxShadow: '0 2px 8px rgba(0,0,0,0.25)',
105
- });
106
- overlay.appendChild(frame);
107
- overlay.appendChild(closeButton);
108
- const previousOverflow = doc.body.style.overflow;
109
- doc.body.style.overflow = 'hidden';
110
- doc.body.appendChild(overlay);
111
- let done = false;
112
- const teardown = () => {
113
- window.removeEventListener('message', onMessage);
114
- doc.removeEventListener('keydown', onKeyDown);
115
- overlay.remove();
116
- doc.body.style.overflow = previousOverflow;
117
- };
118
- const close = () => {
119
- if (done)
120
- return;
121
- done = true;
122
- teardown();
123
- options.onClose?.();
124
- };
125
- const complete = (checkoutId) => {
126
- if (done)
127
- return;
128
- done = true;
129
- teardown();
130
- options.onComplete?.({ checkoutId });
131
- };
132
- function onMessage(event) {
133
- if (event.origin !== origin || event.source !== frame.contentWindow)
134
- return;
135
- if (!isCheckoutMessage(event.data))
136
- return;
137
- if (event.data.type === 'checkout.completed') {
138
- complete(event.data.checkout_id);
139
- }
140
- else {
141
- close();
142
- }
143
- }
144
- function onKeyDown(event) {
145
- if (event.key === 'Escape')
146
- close();
147
- }
148
- window.addEventListener('message', onMessage);
149
- doc.addEventListener('keydown', onKeyDown);
150
- closeButton.addEventListener('click', close);
151
- overlay.addEventListener('click', (event) => {
152
- if (event.target === overlay)
153
- close();
154
- });
155
- return { close };
156
- }
157
- //# sourceMappingURL=web.js.map
1
+ /*! munim-billing © Munim, Inc. All rights reserved. Use is subject to the Munim Billing SDK License (LICENSE). */
2
+ "use strict";var u=Object.defineProperty;var k=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var w=Object.prototype.hasOwnProperty;var C=(t,e)=>{for(var s in e)u(t,s,{get:e[s],enumerable:!0})},v=(t,e,s,l)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of x(e))!w.call(t,o)&&o!==s&&u(t,o,{get:()=>e[o],enumerable:!(l=k(e,o))||l.enumerable});return t};var E=t=>v(u({},"__esModule",{value:!0}),t);var O={};C(O,{isCheckoutMessage:()=>b,openCheckout:()=>L,redirectToCheckout:()=>S});module.exports=E(O);function S(t){m(t),window.location.assign(t)}function m(t){let e;try{e=new URL(t)}catch{throw new Error(`munim-billing: not a checkout URL: ${t}`)}if(e.protocol!=="https:"&&e.hostname!=="localhost"&&e.hostname!=="127.0.0.1")throw new Error("munim-billing: checkout URLs must be https.");return e}function b(t){if(!t||typeof t!="object")return!1;let e=t;return e.source==="munim-billing"&&(e.type==="checkout.completed"||e.type==="checkout.closed")&&typeof e.checkout_id=="string"}function L(t,e={}){let s=m(t),l=s.origin;s.searchParams.set("embed","1");let o=window.document,n=o.createElement("div");n.setAttribute("role","dialog"),n.setAttribute("aria-modal","true"),n.setAttribute("aria-label","Checkout"),n.setAttribute("data-munim-billing-overlay",""),Object.assign(n.style,{position:"fixed",inset:"0",zIndex:String(e.zIndex??2147483e3),background:"rgba(15, 15, 20, 0.55)",display:"flex",alignItems:"center",justifyContent:"center"});let r=o.createElement("iframe");r.src=s.toString(),r.title="Checkout",r.setAttribute("allow","payment *"),Object.assign(r.style,{width:"100%",height:"100%",maxWidth:"480px",maxHeight:"760px",border:"0",borderRadius:"14px",background:"#ffffff",boxShadow:"0 20px 60px rgba(0,0,0,0.35)"}),window.matchMedia?.("(max-width: 520px)").matches&&(r.style.maxWidth="none",r.style.maxHeight="none",r.style.borderRadius="0");let a=o.createElement("button");a.type="button",a.setAttribute("aria-label","Close checkout"),a.textContent="\xD7",Object.assign(a.style,{position:"absolute",top:"12px",right:"12px",width:"36px",height:"36px",borderRadius:"18px",border:"0",background:"rgba(255,255,255,0.92)",color:"#111",fontSize:"24px",lineHeight:"36px",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.25)"}),n.appendChild(r),n.appendChild(a);let f=o.body.style.overflow;o.body.style.overflow="hidden",o.body.appendChild(n);let d=!1,p=()=>{window.removeEventListener("message",h),o.removeEventListener("keydown",g),n.remove(),o.body.style.overflow=f},c=()=>{d||(d=!0,p(),e.onClose?.())},y=i=>{d||(d=!0,p(),e.onComplete?.({checkoutId:i}))};function h(i){i.origin!==l||i.source!==r.contentWindow||b(i.data)&&(i.data.type==="checkout.completed"?y(i.data.checkout_id):c())}function g(i){i.key==="Escape"&&c()}return window.addEventListener("message",h),o.addEventListener("keydown",g),a.addEventListener("click",c),n.addEventListener("click",i=>{i.target===n&&c()}),{close:c}}
@@ -0,0 +1,2 @@
1
+ /*! munim-billing © Munim, Inc. All rights reserved. Use is subject to the Munim Billing SDK License (LICENSE). */
2
+ var f=a=>{throw TypeError(a)};var g=(a=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(a,{get:(b,c)=>(typeof require<"u"?require:b)[c]}):a)(function(a){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+a+'" is not supported')});var d=(a,b,c)=>b.has(a)||f("Cannot "+c);var h=(a,b,c)=>(d(a,b,"read from private field"),c?c.call(a):b.get(a)),i=(a,b,c)=>b.has(a)?f("Cannot add the same private member more than once"):b instanceof WeakSet?b.add(a):b.set(a,c),j=(a,b,c,e)=>(d(a,b,"write to private field"),e?e.call(a,c):b.set(a,c),c),k=(a,b,c)=>(d(a,b,"access private method"),c);export{g as a,h as b,i as c,j as d,k as e};
@@ -128,4 +128,3 @@ export declare class MunimBilling {
128
128
  };
129
129
  }
130
130
  export {};
131
- //# sourceMappingURL=client.d.ts.map
@@ -19,4 +19,3 @@ export declare class MunimBillingError extends Error {
19
19
  }
20
20
  /** Builds the error for a non-2xx response from its parsed body (if any). */
21
21
  export declare function errorFromResponse(status: number, body: unknown): MunimBillingError;
22
- //# sourceMappingURL=errors.d.ts.map
@@ -7,4 +7,3 @@ export type { VerifyWebhookOptions } from './webhooks.js';
7
7
  export { EVENT_TYPES } from './types.js';
8
8
  export type * from './types.js';
9
9
  export { VERSION } from './version.js';
10
- //# sourceMappingURL=index.d.ts.map
package/lib/esm/index.js CHANGED
@@ -1,6 +1,2 @@
1
- export { MunimBilling, baseUrlForKey, modeForKey, paginate, LIVE_BASE_URL, TEST_BASE_URL, } from './client.js';
2
- export { MunimBillingError, errorFromResponse } from './errors.js';
3
- export { verifyWebhook, signWebhookPayload, computeSignature, parseSignatureHeader, timingSafeEqual, webhooks, SIGNATURE_HEADER, EVENT_ID_HEADER, DEFAULT_TOLERANCE_SECONDS, } from './webhooks.js';
4
- export { EVENT_TYPES } from './types.js';
5
- export { VERSION } from './version.js';
6
- //# sourceMappingURL=index.js.map
1
+ /*! munim-billing © Munim, Inc. All rights reserved. Use is subject to the Munim Billing SDK License (LICENSE). */
2
+ import{b as _,c as P,d as T,e as s}from"./chunks/57OHO4KT.js";var a=class extends Error{constructor(t,r){super(t),this.name="MunimBillingError",this.type=r.type,this.status=r.status??null,this.param=r.param??null,r.cause!==void 0&&(this.cause=r.cause)}},K=new Set(["invalid_request","authentication","not_found","conflict","processor","internal"]);function z(e){return e===401||e===403?"authentication":e===404?"not_found":e===409?"conflict":e===402||e===502?"processor":e>=500?"internal":"invalid_request"}function R(e,t){let r=t&&typeof t=="object"&&"error"in t?t.error:void 0,n=r?.type&&K.has(r.type)?r.type:z(e);return new a(r?.message||`Munim Billing request failed with status ${e}`,{type:n,status:e,param:r?.param??null})}var O="0.3.0";var k="Munim-Signature",q="Munim-Event-Id",I=300,$=new TextEncoder;function N(){let e=globalThis.crypto?.subtle;if(!e)throw new a("Web Crypto (crypto.subtle) is not available in this runtime. Use Node 20+ or another runtime with WebCrypto.",{type:"internal"});return e}function X(e){return Array.from(new Uint8Array(e),t=>t.toString(16).padStart(2,"0")).join("")}function F(e){return typeof e=="string"?e:new TextDecoder().decode(e)}async function C(e,t,r){let n=await N().importKey("raw",$.encode(e),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),u=await N().sign("HMAC",n,$.encode(`${r}.${F(t)}`));return X(u)}async function W(e,t,r=Math.floor(Date.now()/1e3)){let n=Math.floor(r);return`t=${n},v1=${await C(e,t,n)}`}function B(e){let t=null,r=[];for(let n of e.split(",")){let u=n.indexOf("=");if(u<0)continue;let d=n.slice(0,u).trim(),l=n.slice(u+1).trim();d==="t"&&/^\d+$/.test(l)?t=Number(l):d==="v1"&&l&&r.push(l.toLowerCase())}return{timestamp:t,signatures:r}}function D(e,t){if(e.length!==t.length)return!1;let r=0;for(let n=0;n<e.length;n++)r|=e.charCodeAt(n)^t.charCodeAt(n);return r===0}function v(e){throw new a(e,{type:"signature_verification",status:400})}async function V(e,t,r,n={}){r||v("No webhook secret was given."),t||v(`Missing ${k} header.`);let{timestamp:u,signatures:d}=B(t);(u===null||d.length===0)&&v(`Malformed ${k} header.`);let l=await C(r,e,u);d.some(m=>D(m,l))||v("Webhook signature does not match. Check the secret and that the body is the raw, unparsed request body.");let g=n.toleranceSeconds??I;if(g>0){let m=Math.floor((n.now??Date.now())/1e3);Math.abs(m-u)>g&&v("Webhook timestamp is outside the tolerance.")}try{return JSON.parse(F(e))}catch(m){throw new a("Webhook body is not valid JSON.",{type:"signature_verification",status:400,cause:m})}}var M={verify:V,sign:W,computeSignature:C,parseHeader:B,SIGNATURE_HEADER:k,EVENT_ID_HEADER:q};var H="https://billing-api.munimtech.com",G="https://billing-sandbox-api.munimtech.com";function U(e){return e.startsWith("mb_test_")?"test":e.startsWith("mb_live_")?"live":null}function J(e){let t=U(e);if(t==="test")return G;if(t==="live")return H;throw new a("Munim Billing secret keys start with mb_test_sk_ or mb_live_sk_. Find yours at https://munimtech.com/billing/dashboard.",{type:"authentication"})}async function*Q(e,t={}){let r=t.cursor;for(;;){let n=await e({...t,cursor:r});for(let u of n.data)yield u;if(!n.has_more||!n.next_cursor)return;r=n.next_cursor}}function y(e){let t=(r=>e(r??{}));return t.all=r=>Q(e,r??{}),t}function Z(){let e=globalThis;return typeof e.window<"u"&&typeof e.document<"u"||e.navigator?.product==="ReactNative"}function c(e){if(!e)throw new a("An id is required.",{type:"invalid_request",param:"id"});return encodeURIComponent(e)}var x,S,b,i,o,p,L=class{constructor(t,r={}){P(this,i);this.webhooks=M;P(this,x);P(this,S);P(this,b);this.products={create:t=>s(this,i,p).call(this,"/v1/products",t),list:y(t=>s(this,i,o).call(this,"/v1/products",t)),retrieve:t=>s(this,i,o).call(this,`/v1/products/${c(t)}`),update:(t,r)=>s(this,i,p).call(this,`/v1/products/${c(t)}`,r)};this.prices={create:t=>s(this,i,p).call(this,"/v1/prices",t),list:y(t=>s(this,i,o).call(this,"/v1/prices",t)),retrieve:t=>s(this,i,o).call(this,`/v1/prices/${c(t)}`),update:(t,r)=>s(this,i,p).call(this,`/v1/prices/${c(t)}`,r)};this.checkouts={create:t=>s(this,i,p).call(this,"/v1/checkouts",t),retrieve:t=>s(this,i,o).call(this,`/v1/checkouts/${c(t)}`)};this.customers={list:y(t=>s(this,i,o).call(this,"/v1/customers",t)),retrieve:t=>s(this,i,o).call(this,`/v1/customers/${c(t)}`)};this.transactions={list:y(t=>s(this,i,o).call(this,"/v1/transactions",t)),retrieve:t=>s(this,i,o).call(this,`/v1/transactions/${c(t)}`),refund:(t,r={})=>s(this,i,p).call(this,`/v1/transactions/${c(t)}/refund`,r)};this.subscriptions={list:y(t=>s(this,i,o).call(this,"/v1/subscriptions",t)),retrieve:t=>s(this,i,o).call(this,`/v1/subscriptions/${c(t)}`),cancel:(t,r={})=>s(this,i,p).call(this,`/v1/subscriptions/${c(t)}/cancel`,r),manageUrl:t=>s(this,i,p).call(this,`/v1/subscriptions/${c(t)}/manage_url`)};this.balance={retrieve:()=>s(this,i,o).call(this,"/v1/balance")};this.payouts={list:y(t=>s(this,i,o).call(this,"/v1/payouts",t))};this.subscribers={retrieve:t=>s(this,i,o).call(this,`/v1/subscribers/${c(t)}`)};this.receipts={apple:t=>s(this,i,p).call(this,"/v1/receipts/apple",t),google:t=>s(this,i,p).call(this,"/v1/receipts/google",t)};this.storeSubscriptions={list:y(t=>s(this,i,o).call(this,"/v1/store_subscriptions",t))};this.entitlements={list:()=>s(this,i,o).call(this,"/v1/entitlements")};if(!t||typeof t!="string")throw new a("A Munim Billing secret key is required.",{type:"authentication"});if(!r.dangerouslyAllowBrowser&&Z())throw new a("MunimBilling uses your secret key and must run on your server. In a browser or app, create the checkout on your server and open its url with munim-billing/web or munim-billing/react-native.",{type:"invalid_request"});T(this,x,t),this.mode=U(t),this.baseUrl=(r.baseUrl??J(t)).replace(/\/+$/,"");let n=r.fetch??globalThis.fetch;if(!n)throw new a("No fetch is available. Pass one with options.fetch.",{type:"internal"});T(this,S,n),T(this,b,r.timeoutMs??3e4)}async request(t,r,n={}){let u=`${this.baseUrl}${r}`;if(n.query){let E=new URLSearchParams;for(let[Y,A]of Object.entries(n.query))A!=null&&E.append(Y,String(A));let w=E.toString();w&&(u+=`?${w}`)}let d={Authorization:`Bearer ${_(this,x)}`,Accept:"application/json","Munim-Billing-Client":`munim-billing-js/${O}`},l;t==="POST"&&(d["Content-Type"]="application/json",l=JSON.stringify(n.body??{}));let g=typeof AbortController<"u"?new AbortController:void 0,m=g?setTimeout(()=>g.abort(),_(this,b)):void 0,h;try{h=await _(this,S).call(this,u,{method:t,headers:d,body:l,signal:g?.signal})}catch(E){let w=g?.signal.aborted;throw new a(w?`Munim Billing request timed out after ${_(this,b)} ms.`:"Could not reach Munim Billing.",{type:"connection",cause:E})}finally{m&&clearTimeout(m)}let j=await h.text(),f;if(j)try{f=JSON.parse(j)}catch{f=void 0}if(!h.ok)throw R(h.status,f);if(f===void 0)throw new a("Munim Billing returned a response that is not JSON.",{type:"internal",status:h.status});return f}};x=new WeakMap,S=new WeakMap,b=new WeakMap,i=new WeakSet,o=function(t,r){return this.request("GET",t,{query:r})},p=function(t,r){return this.request("POST",t,{body:r})},L.webhooks=M;var tt=["checkout.completed","transaction.completed","transaction.refunded","transaction.disputed","subscription.created","subscription.updated","subscription.canceled","payout.paid","payout.failed"];export{I as DEFAULT_TOLERANCE_SECONDS,q as EVENT_ID_HEADER,tt as EVENT_TYPES,H as LIVE_BASE_URL,L as MunimBilling,a as MunimBillingError,k as SIGNATURE_HEADER,G as TEST_BASE_URL,O as VERSION,J as baseUrlForKey,C as computeSignature,R as errorFromResponse,U as modeForKey,Q as paginate,B as parseSignatureHeader,W as signWebhookPayload,D as timingSafeEqual,V as verifyWebhook,M as webhooks};
@@ -69,4 +69,3 @@ export declare function parseCheckoutReturnUrl(url: string): CheckoutReturn;
69
69
  * the browser; the result arrives later as a deep link to your app.
70
70
  */
71
71
  export declare function openCheckout(url: string, options: OpenCheckoutOptions): Promise<OpenCheckoutResult>;
72
- //# sourceMappingURL=react-native.d.ts.map
@@ -1,114 +1,2 @@
1
- /**
2
- * munim-billing/react-native: open a Munim checkout from a React Native or
3
- * Expo app.
4
- *
5
- * The checkout opens in an in-app sheet (ASWebAuthenticationSession on iOS,
6
- * a Custom Tab on Android) through `expo-web-browser`, the same kind of
7
- * sheet munim-venmo uses. The sheet closes when the checkout redirects to
8
- * your app's scheme, so create the checkout **on your server** with
9
- * `success_url` and `cancel_url` set to that scheme:
10
- *
11
- * success_url: 'myapp://billing/done'
12
- * cancel_url: 'myapp://billing/canceled'
13
- *
14
- * Never ship your secret key in an app.
15
- */
16
- function loadWebBrowser() {
17
- try {
18
- // Optional peer dependency, looked up only when it's needed.
19
- const mod = (typeof require === 'function' ? require('expo-web-browser') : undefined);
20
- return mod && typeof mod.openAuthSessionAsync === 'function' ? mod : null;
21
- }
22
- catch {
23
- return null;
24
- }
25
- }
26
- function loadLinking() {
27
- try {
28
- const mod = (typeof require === 'function' ? require('react-native') : undefined);
29
- return mod?.Linking ?? null;
30
- }
31
- catch {
32
- return null;
33
- }
34
- }
35
- /** Reads a URL's query (and fragment) without `URL.searchParams`, which React Native doesn't implement. */
36
- function queryParams(url) {
37
- const params = new Map();
38
- const start = url.indexOf('?');
39
- const hash = url.indexOf('#');
40
- const parts = [];
41
- if (start >= 0)
42
- parts.push(url.slice(start + 1, hash > start ? hash : undefined));
43
- if (hash >= 0)
44
- parts.push(url.slice(hash + 1));
45
- for (const part of parts) {
46
- for (const pair of part.split('&')) {
47
- if (!pair)
48
- continue;
49
- const eq = pair.indexOf('=');
50
- const rawKey = eq >= 0 ? pair.slice(0, eq) : pair;
51
- const rawValue = eq >= 0 ? pair.slice(eq + 1) : '';
52
- try {
53
- const key = decodeURIComponent(rawKey.replace(/\+/g, ' ')).toLowerCase();
54
- if (!params.has(key))
55
- params.set(key, decodeURIComponent(rawValue.replace(/\+/g, ' ')));
56
- }
57
- catch {
58
- // A malformed escape: skip that pair.
59
- }
60
- }
61
- }
62
- return params;
63
- }
64
- /**
65
- * Reads the URL the checkout returned to. `checkout_id` means it was paid;
66
- * `canceled=true` (or no `checkout_id`) means it wasn't.
67
- */
68
- export function parseCheckoutReturnUrl(url) {
69
- const params = queryParams(url);
70
- const checkoutId = params.get('checkout_id') || undefined;
71
- const canceled = params.get('canceled') ?? params.get('cancelled');
72
- if (canceled === 'true' || canceled === '1' || !checkoutId) {
73
- return checkoutId ? { status: 'canceled', checkoutId } : { status: 'canceled' };
74
- }
75
- return { status: 'completed', checkoutId };
76
- }
77
- /**
78
- * Opens a checkout `url` (from `munim.checkouts.create` on your server) in an
79
- * in-app sheet and resolves when the customer comes back.
80
- *
81
- * - `completed`: the checkout redirected to your `success_url`. Confirm on
82
- * your server (the `checkout.completed` webhook, or
83
- * `munim.checkouts.retrieve(checkoutId)`) before granting anything.
84
- * - `canceled`: the customer closed the sheet or hit cancel.
85
- * - `opened`: `expo-web-browser` isn't installed, so the checkout opened in
86
- * the browser; the result arrives later as a deep link to your app.
87
- */
88
- export async function openCheckout(url, options) {
89
- if (!url)
90
- throw new Error('munim-billing: openCheckout needs the checkout url.');
91
- if (!options?.returnUrl || !/^[a-z][a-z0-9+.-]*:/i.test(options.returnUrl)) {
92
- throw new Error("munim-billing: openCheckout needs a returnUrl like 'myapp://billing'.");
93
- }
94
- const browser = options.webBrowser ?? loadWebBrowser();
95
- if (browser) {
96
- const result = await browser.openAuthSessionAsync(url, options.returnUrl, {
97
- preferEphemeralSession: options.preferEphemeralSession ?? false,
98
- });
99
- if (result.type === 'success' && result.url) {
100
- const parsed = parseCheckoutReturnUrl(result.url);
101
- return parsed.status === 'completed'
102
- ? { status: 'completed', checkoutId: parsed.checkoutId, url: result.url }
103
- : { status: 'canceled', checkoutId: parsed.checkoutId, url: result.url };
104
- }
105
- return { status: 'canceled' };
106
- }
107
- const linking = loadLinking();
108
- if (!linking) {
109
- throw new Error('munim-billing: install expo-web-browser (or run inside React Native) to open a checkout.');
110
- }
111
- await linking.openURL(url);
112
- return { status: 'opened' };
113
- }
114
- //# sourceMappingURL=react-native.js.map
1
+ /*! munim-billing © Munim, Inc. All rights reserved. Use is subject to the Munim Billing SDK License (LICENSE). */
2
+ import{a as u}from"./chunks/57OHO4KT.js";function d(){try{let e=typeof u=="function"?u("expo-web-browser"):void 0;return e&&typeof e.openAuthSessionAsync=="function"?e:null}catch{return null}}function h(){try{return(typeof u=="function"?u("react-native"):void 0)?.Linking??null}catch{return null}}function f(e){let n=new Map,t=e.indexOf("?"),r=e.indexOf("#"),s=[];t>=0&&s.push(e.slice(t+1,r>t?r:void 0)),r>=0&&s.push(e.slice(r+1));for(let o of s)for(let c of o.split("&")){if(!c)continue;let i=c.indexOf("="),a=i>=0?c.slice(0,i):c,p=i>=0?c.slice(i+1):"";try{let l=decodeURIComponent(a.replace(/\+/g," ")).toLowerCase();n.has(l)||n.set(l,decodeURIComponent(p.replace(/\+/g," ")))}catch{}}return n}function k(e){let n=f(e),t=n.get("checkout_id")||void 0,r=n.get("canceled")??n.get("cancelled");return r==="true"||r==="1"||!t?t?{status:"canceled",checkoutId:t}:{status:"canceled"}:{status:"completed",checkoutId:t}}async function g(e,n){if(!e)throw new Error("munim-billing: openCheckout needs the checkout url.");if(!n?.returnUrl||!/^[a-z][a-z0-9+.-]*:/i.test(n.returnUrl))throw new Error("munim-billing: openCheckout needs a returnUrl like 'myapp://billing'.");let t=n.webBrowser??d();if(t){let s=await t.openAuthSessionAsync(e,n.returnUrl,{preferEphemeralSession:n.preferEphemeralSession??!1});if(s.type==="success"&&s.url){let o=k(s.url);return o.status==="completed"?{status:"completed",checkoutId:o.checkoutId,url:s.url}:{status:"canceled",checkoutId:o.checkoutId,url:s.url}}return{status:"canceled"}}let r=h();if(!r)throw new Error("munim-billing: install expo-web-browser (or run inside React Native) to open a checkout.");return await r.openURL(e),{status:"opened"}}export{g as openCheckout,k as parseCheckoutReturnUrl};
@@ -37,6 +37,8 @@ export type Price = {
37
37
  metadata: Metadata;
38
38
  created_at: number;
39
39
  };
40
+ /** sheet: mobile sheet (default); split: desktop two-column; compact: embeds and small sheets. */
41
+ export type CheckoutTemplate = 'sheet' | 'split' | 'compact';
40
42
  export type Checkout = {
41
43
  id: string;
42
44
  object: 'checkout';
@@ -53,6 +55,7 @@ export type Checkout = {
53
55
  amount_total: number;
54
56
  currency: Currency;
55
57
  mode: 'payment' | 'subscription';
58
+ template: CheckoutTemplate | null;
56
59
  customer_id: string | null;
57
60
  customer_email: string | null;
58
61
  success_url: string | null;
@@ -211,6 +214,8 @@ export type CheckoutCreateParams = {
211
214
  cancel_url?: string;
212
215
  /** Your own user id, so this purchase counts toward that user's entitlements (`subscribers.retrieve`). */
213
216
  app_user_id?: string;
217
+ /** Checkout look for this checkout; your dashboard default otherwise. */
218
+ template?: CheckoutTemplate;
214
219
  metadata?: Metadata;
215
220
  };
216
221
  export type CustomerListParams = ListParams & {
@@ -295,4 +300,3 @@ export type StoreSubscriptionListParams = ListParams & {
295
300
  app_user_id?: string;
296
301
  };
297
302
  export {};
298
- //# sourceMappingURL=types.d.ts.map
@@ -1,3 +1,2 @@
1
1
  /** Sent as `Munim-Billing-Client: munim-billing-js/<VERSION>`. */
2
- export declare const VERSION = "0.1.0";
3
- //# sourceMappingURL=version.d.ts.map
2
+ export declare const VERSION = "0.3.0";
package/lib/esm/web.d.ts CHANGED
@@ -37,4 +37,3 @@ export declare function isCheckoutMessage(data: unknown): data is CheckoutMessag
37
37
  * work: the checkout page handles those itself.
38
38
  */
39
39
  export declare function openCheckout(url: string, options?: OpenCheckoutOptions): CheckoutHandle;
40
- //# sourceMappingURL=web.d.ts.map
package/lib/esm/web.js CHANGED
@@ -1,152 +1,2 @@
1
- /**
2
- * munim-billing/web: open a Munim checkout from a web page.
3
- *
4
- * Create the checkout on your server (`munim.checkouts.create`) and pass its
5
- * `url` here. Never put your secret key in browser code.
6
- */
7
- /** Sends the whole page to the checkout. */
8
- export function redirectToCheckout(url) {
9
- assertCheckoutUrl(url);
10
- window.location.assign(url);
11
- }
12
- function assertCheckoutUrl(url) {
13
- let parsed;
14
- try {
15
- parsed = new URL(url);
16
- }
17
- catch {
18
- throw new Error(`munim-billing: not a checkout URL: ${url}`);
19
- }
20
- if (parsed.protocol !== 'https:' && parsed.hostname !== 'localhost' && parsed.hostname !== '127.0.0.1') {
21
- throw new Error('munim-billing: checkout URLs must be https.');
22
- }
23
- return parsed;
24
- }
25
- /** Whether a `postMessage` payload is one of the checkout page's messages. */
26
- export function isCheckoutMessage(data) {
27
- if (!data || typeof data !== 'object')
28
- return false;
29
- const message = data;
30
- return (message.source === 'munim-billing' &&
31
- (message.type === 'checkout.completed' || message.type === 'checkout.closed') &&
32
- typeof message.checkout_id === 'string');
33
- }
34
- /**
35
- * Shows the checkout in a full-screen overlay on top of your page.
36
- *
37
- * The checkout page tells the overlay when the customer has paid (or wants
38
- * out) with `postMessage`; only messages from the checkout's own origin
39
- * count. Card wallets that need the top window (some bank redirects) still
40
- * work: the checkout page handles those itself.
41
- */
42
- export function openCheckout(url, options = {}) {
43
- const parsed = assertCheckoutUrl(url);
44
- const origin = parsed.origin;
45
- // Tell the page it's embedded, so it posts messages instead of redirecting.
46
- parsed.searchParams.set('embed', '1');
47
- const doc = window.document;
48
- const overlay = doc.createElement('div');
49
- overlay.setAttribute('role', 'dialog');
50
- overlay.setAttribute('aria-modal', 'true');
51
- overlay.setAttribute('aria-label', 'Checkout');
52
- overlay.setAttribute('data-munim-billing-overlay', '');
53
- Object.assign(overlay.style, {
54
- position: 'fixed',
55
- inset: '0',
56
- zIndex: String(options.zIndex ?? 2147483000),
57
- background: 'rgba(15, 15, 20, 0.55)',
58
- display: 'flex',
59
- alignItems: 'center',
60
- justifyContent: 'center',
61
- });
62
- const frame = doc.createElement('iframe');
63
- frame.src = parsed.toString();
64
- frame.title = 'Checkout';
65
- // Payment Request (Apple Pay, Google Pay) needs this inside an iframe.
66
- frame.setAttribute('allow', 'payment *');
67
- Object.assign(frame.style, {
68
- width: '100%',
69
- height: '100%',
70
- maxWidth: '480px',
71
- maxHeight: '760px',
72
- border: '0',
73
- borderRadius: '14px',
74
- background: '#ffffff',
75
- boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
76
- });
77
- if (window.matchMedia?.('(max-width: 520px)').matches) {
78
- frame.style.maxWidth = 'none';
79
- frame.style.maxHeight = 'none';
80
- frame.style.borderRadius = '0';
81
- }
82
- const closeButton = doc.createElement('button');
83
- closeButton.type = 'button';
84
- closeButton.setAttribute('aria-label', 'Close checkout');
85
- closeButton.textContent = '×';
86
- Object.assign(closeButton.style, {
87
- position: 'absolute',
88
- top: '12px',
89
- right: '12px',
90
- width: '36px',
91
- height: '36px',
92
- borderRadius: '18px',
93
- border: '0',
94
- background: 'rgba(255,255,255,0.92)',
95
- color: '#111',
96
- fontSize: '24px',
97
- lineHeight: '36px',
98
- cursor: 'pointer',
99
- boxShadow: '0 2px 8px rgba(0,0,0,0.25)',
100
- });
101
- overlay.appendChild(frame);
102
- overlay.appendChild(closeButton);
103
- const previousOverflow = doc.body.style.overflow;
104
- doc.body.style.overflow = 'hidden';
105
- doc.body.appendChild(overlay);
106
- let done = false;
107
- const teardown = () => {
108
- window.removeEventListener('message', onMessage);
109
- doc.removeEventListener('keydown', onKeyDown);
110
- overlay.remove();
111
- doc.body.style.overflow = previousOverflow;
112
- };
113
- const close = () => {
114
- if (done)
115
- return;
116
- done = true;
117
- teardown();
118
- options.onClose?.();
119
- };
120
- const complete = (checkoutId) => {
121
- if (done)
122
- return;
123
- done = true;
124
- teardown();
125
- options.onComplete?.({ checkoutId });
126
- };
127
- function onMessage(event) {
128
- if (event.origin !== origin || event.source !== frame.contentWindow)
129
- return;
130
- if (!isCheckoutMessage(event.data))
131
- return;
132
- if (event.data.type === 'checkout.completed') {
133
- complete(event.data.checkout_id);
134
- }
135
- else {
136
- close();
137
- }
138
- }
139
- function onKeyDown(event) {
140
- if (event.key === 'Escape')
141
- close();
142
- }
143
- window.addEventListener('message', onMessage);
144
- doc.addEventListener('keydown', onKeyDown);
145
- closeButton.addEventListener('click', close);
146
- overlay.addEventListener('click', (event) => {
147
- if (event.target === overlay)
148
- close();
149
- });
150
- return { close };
151
- }
152
- //# sourceMappingURL=web.js.map
1
+ /*! munim-billing © Munim, Inc. All rights reserved. Use is subject to the Munim Billing SDK License (LICENSE). */
2
+ import"./chunks/57OHO4KT.js";function y(t){h(t),window.location.assign(t)}function h(t){let e;try{e=new URL(t)}catch{throw new Error(`munim-billing: not a checkout URL: ${t}`)}if(e.protocol!=="https:"&&e.hostname!=="localhost"&&e.hostname!=="127.0.0.1")throw new Error("munim-billing: checkout URLs must be https.");return e}function f(t){if(!t||typeof t!="object")return!1;let e=t;return e.source==="munim-billing"&&(e.type==="checkout.completed"||e.type==="checkout.closed")&&typeof e.checkout_id=="string"}function k(t,e={}){let l=h(t),g=l.origin;l.searchParams.set("embed","1");let i=window.document,o=i.createElement("div");o.setAttribute("role","dialog"),o.setAttribute("aria-modal","true"),o.setAttribute("aria-label","Checkout"),o.setAttribute("data-munim-billing-overlay",""),Object.assign(o.style,{position:"fixed",inset:"0",zIndex:String(e.zIndex??2147483e3),background:"rgba(15, 15, 20, 0.55)",display:"flex",alignItems:"center",justifyContent:"center"});let r=i.createElement("iframe");r.src=l.toString(),r.title="Checkout",r.setAttribute("allow","payment *"),Object.assign(r.style,{width:"100%",height:"100%",maxWidth:"480px",maxHeight:"760px",border:"0",borderRadius:"14px",background:"#ffffff",boxShadow:"0 20px 60px rgba(0,0,0,0.35)"}),window.matchMedia?.("(max-width: 520px)").matches&&(r.style.maxWidth="none",r.style.maxHeight="none",r.style.borderRadius="0");let s=i.createElement("button");s.type="button",s.setAttribute("aria-label","Close checkout"),s.textContent="\xD7",Object.assign(s.style,{position:"absolute",top:"12px",right:"12px",width:"36px",height:"36px",borderRadius:"18px",border:"0",background:"rgba(255,255,255,0.92)",color:"#111",fontSize:"24px",lineHeight:"36px",cursor:"pointer",boxShadow:"0 2px 8px rgba(0,0,0,0.25)"}),o.appendChild(r),o.appendChild(s);let m=i.body.style.overflow;i.body.style.overflow="hidden",i.body.appendChild(o);let c=!1,d=()=>{window.removeEventListener("message",u),i.removeEventListener("keydown",p),o.remove(),i.body.style.overflow=m},a=()=>{c||(c=!0,d(),e.onClose?.())},b=n=>{c||(c=!0,d(),e.onComplete?.({checkoutId:n}))};function u(n){n.origin!==g||n.source!==r.contentWindow||f(n.data)&&(n.data.type==="checkout.completed"?b(n.data.checkout_id):a())}function p(n){n.key==="Escape"&&a()}return window.addEventListener("message",u),i.addEventListener("keydown",p),s.addEventListener("click",a),o.addEventListener("click",n=>{n.target===o&&a()}),{close:a}}export{f as isCheckoutMessage,k as openCheckout,y as redirectToCheckout};
@@ -56,4 +56,3 @@ export declare const webhooks: {
56
56
  readonly SIGNATURE_HEADER: "Munim-Signature";
57
57
  readonly EVENT_ID_HEADER: "Munim-Event-Id";
58
58
  };
59
- //# sourceMappingURL=webhooks.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "munim-billing",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Munim Billing: take payments with Munim, Inc. as your merchant of record. Cards, Apple Pay, Google Pay, PayPal and Venmo through one API; Munim handles the payment, keeps its fee and pays you out to your bank or PayPal. Server SDK, webhook verification, and checkout helpers for the web and React Native / Expo",
5
5
  "main": "./lib/cjs/index.js",
6
6
  "module": "./lib/esm/index.js",
@@ -28,14 +28,18 @@
28
28
  },
29
29
  "typesVersions": {
30
30
  "*": {
31
- "web": ["./lib/esm/web.d.ts"],
32
- "react-native": ["./lib/esm/react-native.d.ts"]
31
+ "web": [
32
+ "./lib/esm/web.d.ts"
33
+ ],
34
+ "react-native": [
35
+ "./lib/esm/react-native.d.ts"
36
+ ]
33
37
  }
34
38
  },
35
39
  "scripts": {
36
40
  "typecheck": "tsc --noEmit -p tsconfig.json",
37
41
  "clean": "rm -rf lib",
38
- "build": "npm run clean && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node scripts/write-module-types.mjs",
42
+ "build": "npm run clean && node scripts/build.mjs && tsc -p tsconfig.types.json",
39
43
  "test": "vitest run",
40
44
  "release": "semantic-release"
41
45
  },
@@ -58,22 +62,12 @@
58
62
  "munim-technologies"
59
63
  ],
60
64
  "files": [
61
- "src",
62
- "!src/__tests__",
63
65
  "lib",
64
66
  "README.md",
65
- "CHANGELOG.md",
66
67
  "LICENSE"
67
68
  ],
68
- "repository": {
69
- "type": "git",
70
- "url": "git+https://github.com/munimtechnologies/munim-billing.git"
71
- },
72
- "author": "sheehanmunim <support@munimtech.com> (https://github.com/sheehanmunim)",
73
- "license": "Apache-2.0",
74
- "bugs": {
75
- "url": "https://github.com/munimtechnologies/munim-billing/issues"
76
- },
69
+ "author": "Munim, Inc. <support@munimtech.com> (https://munimtech.com)",
70
+ "license": "SEE LICENSE IN LICENSE",
77
71
  "homepage": "https://munimtech.com/billing",
78
72
  "publishConfig": {
79
73
  "access": "public",
@@ -98,6 +92,7 @@
98
92
  "@semantic-release/changelog": "^6.0.3",
99
93
  "@semantic-release/git": "^10.0.1",
100
94
  "conventional-changelog-conventionalcommits": "^9.3.1",
95
+ "esbuild": "^0.28.1",
101
96
  "happy-dom": "^21.0.4",
102
97
  "semantic-release": "^25.0.9",
103
98
  "typescript": "^5.8.3",