@qonto/embed-sdk 0.14.0 → 0.15.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.
- package/dist/beneficiaries/beneficiaries.d.ts +40 -1
- package/dist/beneficiaries/beneficiaries.d.ts.map +1 -1
- package/dist/beneficiaries/beneficiaries.validate.d.ts +1 -1
- package/dist/beneficiaries/beneficiaries.validate.d.ts.map +1 -1
- package/dist/common/constants.d.ts +1 -0
- package/dist/common/constants.d.ts.map +1 -1
- package/dist/index.umd.js +1 -1
- package/dist/src/beneficiaries/beneficiaries.js +1 -1
- package/dist/src/beneficiaries/beneficiaries.validate.js +1 -1
- package/dist/src/common/constants.js +1 -1
- package/dist/src/validation/operation-settings-validation.js +1 -1
- package/dist/validation/operation-settings-validation.d.ts.map +1 -1
- package/package.json +1 -1
|
@@ -1,5 +1,23 @@
|
|
|
1
1
|
import type { Beneficiary, GetBeneficiariesResponse, NewBeneficiary } from './beneficiaries.types';
|
|
2
2
|
import type { PaginationSettings } from '@common/api-pagination/api-pagination.types';
|
|
3
|
+
import { type OperationSettings } from '@validation/operation-settings-validation';
|
|
4
|
+
/**
|
|
5
|
+
* This is the common parameter format most of the beneficiaries functions expect
|
|
6
|
+
* as their only parameter. It consists of a `beneficiarySettings` object and an
|
|
7
|
+
* optional `operationSettings` object. The `beneficiarySettings` object's
|
|
8
|
+
* properties will be different depending on the function being called. Read the
|
|
9
|
+
* docs of each beneficiaries related function to see the expected properties of
|
|
10
|
+
* the `beneficiarySettings` object.
|
|
11
|
+
*/
|
|
12
|
+
export interface BeneficiaryParams<T> {
|
|
13
|
+
/**
|
|
14
|
+
* An object with the parameters relevant to different beneficiary operations.
|
|
15
|
+
* Read the documentation of each function to see the expected properties of
|
|
16
|
+
* this object.
|
|
17
|
+
*/
|
|
18
|
+
beneficiarySettings: T;
|
|
19
|
+
operationSettings?: OperationSettings;
|
|
20
|
+
}
|
|
3
21
|
/**
|
|
4
22
|
* Fetches the list of beneficiaries for the current user.
|
|
5
23
|
* @param getBeneficiariesParams - An optional object with the accessToken
|
|
@@ -52,7 +70,28 @@ export declare function addBeneficiary({ beneficiary, accessToken, stagingToken,
|
|
|
52
70
|
accessToken?: string;
|
|
53
71
|
stagingToken?: string;
|
|
54
72
|
}): Promise<Beneficiary>;
|
|
55
|
-
|
|
73
|
+
/**
|
|
74
|
+
* Trusts a list of beneficiaries in the current user's account.
|
|
75
|
+
*
|
|
76
|
+
* @param trustBeneficiariesParams - An object containing:
|
|
77
|
+
* - `beneficiarySettings`: An object with the list of beneficiary IDs to
|
|
78
|
+
* trust (e.g., `{ beneficiaryIds: string[] }`).
|
|
79
|
+
* - `operationSettings`: An object with operation-level settings such as
|
|
80
|
+
* `accessToken`, `stagingToken`, `parentElementId`, and other optional
|
|
81
|
+
* parameters. See {@link BeneficiaryParams}.
|
|
82
|
+
*
|
|
83
|
+
* @returns A promise that resolves to an array of trusted beneficiaries.
|
|
84
|
+
*
|
|
85
|
+
* @throws \{AuthenticationError\} If the access token is invalid or missing.
|
|
86
|
+
* Ensure initialize has been called before using this function if you are not
|
|
87
|
+
* passing the access token.
|
|
88
|
+
* @throws \{InvalidParametersError\} If the `beneficiaryIds` parameter is not an
|
|
89
|
+
* array of strings or is missing.
|
|
90
|
+
* @throws \{EmbedApiError\} If the API request fails or returns an error.
|
|
91
|
+
*/
|
|
92
|
+
export declare function trustBeneficiaries({ beneficiarySettings, operationSettings, }: BeneficiaryParams<{
|
|
93
|
+
beneficiaryIds: string[];
|
|
94
|
+
}>): Promise<Beneficiary[]>;
|
|
56
95
|
/**
|
|
57
96
|
* Untrusts a list of beneficiaries in the current user's account.
|
|
58
97
|
* @param Object - An object containing the list of beneficiary IDs and optional
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"beneficiaries.d.ts","sourceRoot":"","sources":["../../src/beneficiaries/beneficiaries.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,wBAAwB,EACxB,cAAc,EACf,MAAM,uBAAuB,CAAC;AAc/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;
|
|
1
|
+
{"version":3,"file":"beneficiaries.d.ts","sourceRoot":"","sources":["../../src/beneficiaries/beneficiaries.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EACV,WAAW,EACX,wBAAwB,EACxB,cAAc,EACf,MAAM,uBAAuB,CAAC;AAc/B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,6CAA6C,CAAC;AAGtF,OAAO,EACL,KAAK,iBAAiB,EAEvB,MAAM,2CAA2C,CAAC;AAEnD;;;;;;;GAOG;AACH,MAAM,WAAW,iBAAiB,CAAC,CAAC;IAClC;;;;OAIG;IACH,mBAAmB,EAAE,CAAC,CAAC;IACvB,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAsB,gBAAgB,CAAC,sBAAsB,CAAC,EAAE;IAC9D,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,kBAAkB,CAAC,EAAE,kBAAkB,CAAC;CACzC,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAqBpC;AAED;;;;;;;;;;;GAWG;AACH,wBAAsB,cAAc,CAAC,EACnC,aAAa,EACb,WAAW,EACX,YAAY,GACb,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,WAAW,CAAC,CASvB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,cAAc,CAAC,EACnC,WAAW,EACX,WAAW,EACX,YAAY,GACb,EAAE;IACD,WAAW,EAAE,cAAc,CAAC;IAC5B,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,WAAW,CAAC,CASvB;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAsB,kBAAkB,CAAC,EACvC,mBAAmB,EACnB,iBAAiB,GAClB,EAAE,iBAAiB,CAAC;IACnB,cAAc,EAAE,MAAM,EAAE,CAAC;CAC1B,CAAC,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAsB1B;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,oBAAoB,CAAC,EACzC,cAAc,EACd,WAAW,EACX,YAAY,GACb,EAAE;IACD,cAAc,EAAE,MAAM,EAAE,CAAC;IACzB,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CASzB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { NewBeneficiary } from '@beneficiaries/beneficiaries.types';
|
|
2
2
|
export declare function validateGetBeneficiaryParams(beneficiaryId: string): string;
|
|
3
3
|
export declare function validateAddBeneficiaryParams(beneficiary: NewBeneficiary): NewBeneficiary;
|
|
4
|
-
export declare function
|
|
4
|
+
export declare function validateTrustBeneficiariesParams(beneficiaryIds: string[]): string[];
|
|
5
5
|
//# sourceMappingURL=beneficiaries.validate.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"beneficiaries.validate.d.ts","sourceRoot":"","sources":["../../src/beneficiaries/beneficiaries.validate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAMzE,wBAAgB,4BAA4B,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAU1E;AAED,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,cAAc,GAC1B,cAAc,CAyBhB;AAED,wBAAgB,
|
|
1
|
+
{"version":3,"file":"beneficiaries.validate.d.ts","sourceRoot":"","sources":["../../src/beneficiaries/beneficiaries.validate.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oCAAoC,CAAC;AAMzE,wBAAgB,4BAA4B,CAAC,aAAa,EAAE,MAAM,GAAG,MAAM,CAU1E;AAED,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,cAAc,GAC1B,cAAc,CAyBhB;AAED,wBAAgB,gCAAgC,CAC9C,cAAc,EAAE,MAAM,EAAE,GACvB,MAAM,EAAE,CAeV"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB;;OAEG;;CAEJ,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,OAAO
|
|
1
|
+
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../src/common/constants.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,eAAO,MAAM,aAAa;IACxB;;OAEG;;CAEJ,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,OAAO;;;;;;;;;CASnB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY;;;;CAIxB,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,QAAQ;;;;CAIpB,CAAC;AAEF,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAgCzB,CAAC;AAEF,eAAO,MAAM,oBAAoB;;;;CAIhC,CAAC;AAEF,eAAO,MAAM,OAAO;;;;;;;CAOnB,CAAC;AAEF,eAAO,MAAM,wBAAwB;;;;;;;;CAQpC,CAAC;AAEF,eAAO,MAAM,iBAAiB;;;;;;CAM7B,CAAC;AAEF,eAAO,MAAM,WAAW;;;;CAIvB,CAAC"}
|
package/dist/index.umd.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).QontoEmbed={})}(this,(function(e){"use strict";class t{constructor(){this.accessToken=null,this.stagingToken=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}setAccessToken(e){this.accessToken=e}getAccessToken(){return this.accessToken}hasAccessToken(){return null!==this.accessToken&&""!==this.accessToken}clearAccessToken(){this.accessToken=null}setStagingToken(e){this.stagingToken=e}getStagingToken(){return this.stagingToken}hasStagingToken(){return null!==this.stagingToken&&""!==this.stagingToken}clearStagingToken(){this.stagingToken=null}}const n=t.getInstance();class i extends Error{constructor(){super(),this.stack=""}toString(){return`${this.name}: ${this.message}`}}class a extends i{constructor(){super(),this.name="AuthenticationError",this.message="Authentication failed due to missing or invalid access token.\nEnsure you have called the initialize function with a valid access token."}}function r(){if(!n.hasAccessToken())throw new a;return n.getAccessToken()}class s extends i{constructor(e){super(),this.name="InvalidParametersError",this.invalidParameters=Array.isArray(e)?e:[e],this.message=`Invalid parameters were passed to the function:\n${this.invalidParameters.map((e=>e)).join("\n")}`}}const o={READY:"qonto.ready"},c={CARD_SEE:"card.see",CARD_SEE_DETAILS:"card.see-details",CARD_ORDER:"card.order",CARD_UNLOCK:"card.unlock",CARD_SHOW_PIN:"card.show.pin",CARD_SET_PIN:"card.set.pin",TRANSFER_SINGLE_CREATE:"transfer.single.create"},d={PRODUCTION:"production",STAGING:"staging",LOCAL:"local"},m={MASTER:"master",SANDBOX:"sandbox",QA:"qa"},l={EN:"en",FR:"fr",DE:"de",ES:"es",IT:"it",PT:"pt"},u={PASSKEY:"passkey",SMS_OTP:"sms-otp",PAIRED_DEVICE:"paired-device"};var f=Object.freeze({__proto__:null,ACTIONS:c,ACTIVITY_TAGS:{ATM:"atm",FALLBACK:"fallback",FEES:"fees",FINANCE:"finance",FOOD_AND_GROCERY:"food_and_grocery",GAS_STATION:"gas_station",HARDWARE_AND_EQUIPMENT:"hardware_and_equipment",HOTEL_AND_LODGING:"hotel_and_lodging",INSURANCE:"insurance",IT_AND_ELECTRONICS:"it_and_electronics",LEGAL_AND_ACCOUNTING:"legal_and_accounting",LOGISTICS:"logistics",MANUFACTURING:"manufacturing",MARKETING:"marketing",OFFICE_RENTAL:"office_rental",OFFICE_SUPPLY:"office_supply",ONLINE_SERVICE:"online_service",OTHER_EXPENSE:"other_expense",OTHER_INCOME:"other_income",OTHER_SERVICE:"other_service",PENDING:"pending",REFUND:"refund",RESTAURANT_AND_BAR:"restaurant_and_bar",SALES:"sales",SALARY:"salary",SUBSCRIPTION:"subscription",TAX:"tax",TRANSPORT:"transport",TREASURY_AND_INTERCO:"treasury_and_interco",UTILITY:"utility",VOUCHER:"voucher"},BENEFICIARY_STATUSES:{PENDING:"pending",VALIDATED:"validated",DECLINED:"declined"},BRANCHES:m,ENVIRONMENTS:d,IFRAME_EVENTS:o,LOCALES:l,MFA_METHODS:u,TRANSFER_DECLINE_REASONS:{BENEFICIARY_BIC_INVALID:"beneficiary_bic_invalid",BENEFICIARY_IBAN_INVALID:"beneficiary_iban_invalid",BENEFICIARY_STATUS:"beneficiary_status",BENEFICIARY_NETWORK_RULES_ERROR:"beneficiary_network_rules_error",ORGANISATION_COMPLIANCE_REASONS:"organisation_compliance_reasons",DEBIT_ACCOUNT_INSUFFICIENT_FUNDS:"debit_account_insufficient_funds",QONTO_PROCESSING_FAILED:"qonto_processing_failed"},TRANSFER_STATUSES:{PENDING:"pending",PROCESSING:"processing",CANCELED:"canceled",DECLINED:"declined",SETTLED:"settled"}});class g{constructor(){this.uiParentElementId=null,this.mfaPreference=u.PASSKEY,this.debugMode=!1}static getInstance(){return g.instance||(g.instance=new g),g.instance}setSettings(e){e.uiParentElementId&&(this.uiParentElementId=e.uiParentElementId),e.mfaPreference&&(this.mfaPreference=e.mfaPreference),e.debugMode&&(this.debugMode=e.debugMode)}getUIParentElementId(){return this.uiParentElementId}getMFAPreference(){return this.mfaPreference}getDebugMode(){return this.debugMode}clearSettings(){this.uiParentElementId=null,this.mfaPreference=u.PASSKEY}}const p=g.getInstance();function h(e){const t=e?.uiParentElementId||p.getUIParentElementId();if(!t)throw new s("operationSettings parameter must have a uiParentElementId for the called function.\nYou can pass it either to the initialize function or in a per function basis.");const n=e?.mfaPreference||p.getMFAPreference();if(n&&!Object.values(u).includes(n))throw new s("operationSettings.mfaPreference must be one of passkey, paired-device or sms-otp.");const i=e?.debugMode||p.getDebugMode();if(void 0!==i&&"boolean"!=typeof i)throw new s("operationSettings.debugMode must be a boolean.");return{uiParentElementId:t,mfaPreference:n,debugMode:i}}const _=Object.values(l);function y(e){if(!function(e){return _.includes(e)}(e))throw new s(`Unsupported locale: ${e}. The locale must be one of: ${_.join(", ")}.`);return e}function T(e){if(!e?.accessToken)throw new s("Access token is required when calling initialize()");return e?.operationSettings&&h(e.operationSettings),function(e){if(e.environment){if(!["production","staging","local"].includes(e.environment))throw new s('If provided, environment must be either "production" or "staging"\nYou can "import constants from @qonto/embed-sdk/common" and then use "constants.environment.PRODUCTION" or "constants.environment.STAGING"');if(e.branch&&!["master","sandbox","qa"].includes(e.branch))throw new s('If provided, branch must be either "master", "sandbox" or "qa"\nYou can "import constants from @qonto/embed-sdk/common" and then use "constants.branch.MASTER" or "constants.environment.SANDBOX" and so on')}}(e),e.locale&&y(e.locale),e}const I="https://embed.qonto.com",E="https://embed-js{branch}.staging.qonto.co",b="https://embed.dev.qonto.co",w={[d.PRODUCTION]:{IFRAME_BASE_URL:I,IFRAME_URL:`${I}/connect`,THIRD_PARTY_API_URL:"https://thirdparty.qonto.com"},[d.STAGING]:{IFRAME_BASE_URL:E,IFRAME_URL:`${E}/connect`,THIRD_PARTY_API_URL:"https://thirdparty{branch}.staging.qonto.co"},[d.LOCAL]:{IFRAME_BASE_URL:b,IFRAME_URL:`${b}/connect`,THIRD_PARTY_API_URL:"https://thirdparty{branch}.staging.qonto.co"}};class A{constructor(){this.environment=d.PRODUCTION,this.branch=m.SANDBOX;const e=process.env.QONTO_EMBED_ENVIRONMENT,t=process.env.QONTO_EMBED_BRANCH;this.environment=Object.values(d).includes(e)?e:d.PRODUCTION,this.branch=Object.values(m).includes(t)?t:m.SANDBOX}static getInstance(){return A.instance||(A.instance=new A),A.instance}setEnvironment(e){this.environment=e}getEnvironment(){return this.environment}setBranch(e){this.branch=e}getBranch(){return this.branch}clear(){this.environment=d.PRODUCTION,this.branch=m.MASTER}getEnvironmentUrls(){if(this.environment===d.PRODUCTION)return w.production;{const e=w[this.environment];return Object.entries(e).reduce(((e,[t,n])=>({...e,[t]:n.replace("{branch}",`-${this.branch}`)})),{})}}}const L=A.getInstance();class R{constructor(){this.currentLocale="en"}static getInstance(){return R.instance||(R.instance=new R),R.instance}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}setDefaultLocale(){this.currentLocale="en"}}const k=R.getInstance();const S={initialize:function(e){const{accessToken:t,stagingToken:i,operationSettings:a,environment:r,branch:s,locale:o}=T(e);n.setAccessToken(t),i&&n.setStagingToken(i),o&&k.setLocale(o),a&&p.setSettings(a),r&&(L.setEnvironment(r),s&&L.setBranch(s))},logout:function(){n.clearAccessToken(),n.clearStagingToken(),k.setDefaultLocale()},constants:f},{initialize:v,logout:D,constants:P}=S;class O extends i{constructor(e){super();const t=Array.isArray(e)?e.join("\n"):e;this.name="EmbedApiError",this.message=`The call to the Embed API failed with the following errors:\n${t}`}}function N({accessToken:e,stagingToken:t,idempotencyKey:i,mfaPreference:a}){const r=new Headers;r.append("Authorization",`Bearer ${e}`);const s=t||n.getStagingToken();s&&r.append("X-Qonto-Staging-Token",s),i&&r.append("X-Qonto-Idempotency-Key",i);const o=a||p.getMFAPreference();return o&&r.append("X-Qonto-2fa-Preference",o),r.append("Content-Type","application/json"),r.append("Accept-Language",k.getLocale()),r}async function U(e,t,n){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=L.getEnvironmentUrls().THIRD_PARTY_API_URL,r=await fetch(`${a}/v2/cards/${e.cardId}/data_view`,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return function(e,t){const n=new URL(e);return"boolean"==typeof t.allowPinReveal&&n.searchParams.set("canSeePin",t.allowPinReveal?"true":"false"),"boolean"==typeof t.allowBlocking&&n.searchParams.set("canBlock",t.allowBlocking?"true":"false"),n.toString()}(s.iframe_url,e)}var C;!function(e){e.PENDING="pending",e.ONHOLD="onhold",e.ORDER_CANCELED="order_canceled",e.LIVE="live",e.PAUSED="paused",e.STOLEN="stolen",e.LOST="lost",e.PIN_BLOCKED="pin_blocked",e.DELETED="deleted",e.PRE_EXPIRED="pre_expired",e.EXPIRED="expired",e.DISCARDED="discarded",e.SHIPPED_LOST="shipped_lost",e.ABUSIVE="abusive"}(C||(C={}));const M={TRANSPORT:"transport",RESTAURANT_AND_BAR:"restaurant_and_bar",FOOD_AND_GROCERY:"food_and_grocery",IT_AND_ELECTRONICS:"it_and_electronics",UTILITY:"utility",TAX:"tax",LEGAL_AND_ACCOUNTING:"legal_and_accounting",ATM:"atm",OFFICE_SUPPLY:"office_supply",HARDWARE_AND_EQUIPMENT:"hardware_and_equipment",FINANCE:"finance"};var $,B;function F(e,t){const n=t.filter((t=>t.requiredIfPresent?!e[t.name]&&e[t.requiredIfPresent]:void 0===e[t.name])).map((e=>e.name));if(n.length>0)throw new s(n.map((e=>`Missing required parameter: ${e}`)))}function j(e){return Object.entries(e).filter((([,e])=>void 0!==e)).filter((([,e])=>"string"!=typeof e)).map((([e])=>`${e} must be a string`))}function Y(e){return Object.entries(e).filter((([,e])=>void 0!==e&&!1!==e&&!0!==e)).map((([e])=>`${e} must be a boolean`))}function G(e){return Object.entries(e).filter((([,e])=>void 0!==e)).filter((([,e])=>"number"!=typeof e)).map((([e])=>`${e} must be a number`))}!function(e){e.VIRTUAL="virtual"}($||($={})),function(e){e.METAL="metal",e.PLUS="plus",e.STANDARD="standard"}(B||(B={}));const q=[{name:"organizationId"},{name:"membershipId"},{name:"bankAccountId"},{name:"monthlyLimit"},{name:"cardLevel"}],x=[...q,{name:"atmDailyLimit",requiredIfPresent:"hasAtmDailyLimit"},{name:"hasAtmDailyLimit",requiredIfPresent:"hasAtmOption"},{name:"atmMonthlyLimit",requiredIfPresent:"hasAtmOption"},{name:"shipToBusiness"},{name:"cardLevel"}];function H(e){if(!e)throw new s("cardSettings parameter is required for the called function");return"virtual"===e.cardLevel?function(e){return F(e,q),function(e){const{membershipId:t,organizationId:n,bankAccountId:i,hasDailyLimit:a,hasTransactionLimit:r,monthlyLimit:o,dailyLimit:c,transactionLimit:d,activeDays:m,categories:l,cardLevel:u}=e,f=function(e){return"virtual"!==e?['cardLevel must be "virtual"']:[]}(u),g=j({membershipId:t,organizationId:n,bankAccountId:i}),p=Y({hasDailyLimit:a,hasTransactionLimit:r}),h=G({monthlyLimit:o,dailyLimit:c,transactionLimit:d}),_=z(m),y=K(l),T=[...f,...g,...p,...h,..._,...y];if(T.length>0)throw new s(T)}(e),e}(e):function(e){F(e,x),function(e){const{membershipId:t,organizationId:n,bankAccountId:i,hasDailyLimit:a,hasTransactionLimit:r,monthlyLimit:o,dailyLimit:c,transactionLimit:d,activeDays:m,categories:l,cardLevel:u,hasNfcOption:f,hasForeignPaymentOption:g,hasOnlinePaymentOption:p,shipToBusiness:h,hasAtmOption:_,hasAtmDailyLimit:y,atmDailyLimit:T,atmMonthlyLimit:I,address:E,cardDesign:b,typeOfPrint:w}=e,A=function(e){return Object.values(B).includes(e)?[]:['cardLevel must be one of "standard", "plus", "metal"']}(u),L=function(e){const t=null!=e&&"string"!=typeof e,n=!["print","embossed",void 0,null].includes(e);return t||n?['typeOfPrint must be one of "print", "embossed" or null']:[]}(w),R=j({membershipId:t,organizationId:n,bankAccountId:i}),k=Y({hasDailyLimit:a,hasTransactionLimit:r,hasAtmOption:_,hasNfcOption:f,hasForeignPaymentOption:g,hasOnlinePaymentOption:p,hasAtmDailyLimit:y,shipToBusiness:h}),S=G({monthlyLimit:o,dailyLimit:c,transactionLimit:d,atmDailyLimit:T,atmMonthlyLimit:I}),v=z(m),D=K(l),P=function(e){return["undefined","string"].includes(typeof e)?[]:["cardDesign must be a string"]}(b),O=function(e,t){if(t)return[];return!e||e.contactName&&e.firstLine&&e.zipCode&&e.city&&e.country?[]:["address must contain at least contactName, firstLine, zipCode, city and country properties"]}(E,h),N=[...A,...R,...k,...S,...v,...D,...L,...P,...O];if(N.length>0)throw new s(N)}(e)}(e)}function z(e){const t=!Array.isArray(e)||!e.every((e=>Number.isInteger(e)&&e>0&&e<8));return void 0!==e&&t?["activeDays must be an array of integers between 1 and 7"]:[]}function K(e){const t=!Array.isArray(e)||e.some((e=>"string"!=typeof e));return void 0!==e&&t?["categories must be an array of strings"]:[]}class V extends i{constructor(e){super(),this.name="EmbedOperationError",this.message=e}}class X{constructor(e){this.options=e,this.iframe=null,this.parentElement=null,this.messageListeners=new Map,this.defaultTimeout=3e4;const t=new URL(e.iframeUrl);this.targetOrigin=`${t.protocol}//${t.host}`}async initialize(){if(this.iframe)return this;if(this.parentElement=document.getElementById(this.options.parentElementId),!this.parentElement)throw new V(`Could not install the authentication UI because the parent element with id ${this.options.parentElementId} was not found.\nPlease make sure to pass a valid parentElementId when calling the method.`);return new Promise(((e,t)=>{this.iframe=document.createElement("iframe"),this.iframe.src=this.options.iframeUrl,this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.border="none";const n=this.options.timeout||this.defaultTimeout,i=setTimeout((()=>{window.removeEventListener("message",a),t(new V(`Could not install the authentication UI because the timeout of ${n}ms was reached.\nPlease make sure the application can reach the Internet.`))}),n),a=t=>{t.data.eventId===o.READY&&(clearTimeout(i),window.removeEventListener("message",a),e(this))};window.addEventListener("message",a),this.parentElement?.appendChild(this.iframe)}))}postMessage(e){return this.iframe&&this.iframe.contentWindow?new Promise(((t,n)=>{const i=a=>{if(a.data?.actionId===e.actionId){if("error"===a.data.status)return this.removeMessageListener(e.actionId,i),n(new V(`An error occurred when performing the action ${e.actionId}.\n${JSON.stringify(a.data.payload)}`));this.removeMessageListener(e.actionId,i),t(a.data.payload)}};this.addMessageListener(e.actionId,i),this.iframe?.contentWindow?.postMessage(e,this.targetOrigin)})):Promise.reject(new V("Attempted to perform an Embed operation without having the authentication UI initialized."))}addMessageListener(e,t){this.messageListeners.has(e)||this.messageListeners.set(e,[]);this.messageListeners.get(e).push(t),window.addEventListener("message",t)}removeMessageListener(e,t){const n=this.messageListeners.get(e);if(n){const e=n.indexOf(t);-1!==e&&(n.splice(e,1),window.removeEventListener("message",t))}}destroy(){this.messageListeners.forEach((e=>{e.forEach((e=>{window.removeEventListener("message",e)}))})),this.messageListeners.clear(),this.iframe&&this.parentElement&&(this.parentElement.removeChild(this.iframe),this.iframe=null)}}function Q({accessToken:e,stagingToken:t,locale:n,debugMode:i}){const a=i||!1,r=n||k.getLocale(),s=L.getEnvironmentUrls().IFRAME_URL,o=t?`;staging_token=${encodeURIComponent(t)}`:"";return`${s}?debug=${a}&lang=${encodeURIComponent(r)}#access_token=${encodeURIComponent(e)}${o}`}function W({parentElementId:e,iframeUrl:t}){return new X({parentElementId:e,iframeUrl:t}).initialize()}const J=[];for(let e=0;e<256;++e)J.push((e+256).toString(16).slice(1));let Z;const ee=new Uint8Array(16);var te={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ne(e,t,n){if(te.randomUUID&&!e)return te.randomUUID();const i=(e=e||{}).random??e.rng?.()??function(){if(!Z){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Z=crypto.getRandomValues.bind(crypto)}return Z(ee)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(J[e[t+0]]+J[e[t+1]]+J[e[t+2]]+J[e[t+3]]+"-"+J[e[t+4]]+J[e[t+5]]+"-"+J[e[t+6]]+J[e[t+7]]+"-"+J[e[t+8]]+J[e[t+9]]+"-"+J[e[t+10]]+J[e[t+11]]+J[e[t+12]]+J[e[t+13]]+J[e[t+14]]+J[e[t+15]]).toLowerCase()}(i)}function ie(e){return"virtual"===e.cardLevel?function(e){const t=re(e.categories);return{actionId:c.CARD_ORDER,actionData:{idempotencyKey:ne(),body:{card:{payment_monthly_limit:e.monthlyLimit,payment_daily_limit:e.dailyLimit,payment_daily_limit_option:e.hasDailyLimit,payment_transaction_limit:e.transactionLimit,payment_transaction_limit_option:e.hasTransactionLimit,active_days:e.activeDays||[],holder_id:e.membershipId,organization_id:e.organizationId,bank_account_id:e.bankAccountId,categories:t,card_level:e.cardLevel}}}}}(e):function(e){const t=re(e.categories);return{actionId:c.CARD_ORDER,actionData:{idempotencyKey:ne(),body:{card:{payment_monthly_limit:e.monthlyLimit,payment_daily_limit:e.dailyLimit,payment_daily_limit_option:e.hasDailyLimit,payment_transaction_limit:e.transactionLimit,payment_transaction_limit_option:e.hasTransactionLimit,active_days:e.activeDays||[],holder_id:e.membershipId,organization_id:e.organizationId,bank_account_id:e.bankAccountId,categories:t,card_level:e.cardLevel,card_design:e.cardDesign,..."plus"===e.cardLevel&&{type_of_print:e.typeOfPrint},ship_to_business_address:e.shipToBusiness,atm_option:e.hasAtmOption,nfc_option:e.hasNfcOption,foreign_option:e.hasForeignPaymentOption,online_option:e.hasOnlinePaymentOption,atm_daily_limit:e.atmDailyLimit,atm_monthly_limit:e.atmMonthlyLimit,...!e.shipToBusiness&&{address:{contact_name:e.address?.contactName,first_line:e.address?.firstLine,second_line:e.address?.secondLine,third_line:e.address?.thirdLine,zipcode:e.address?.zipCode,city:e.address?.city,country:e.address?.country}}}}}}}(e)}function ae(e){return{id:e.id,nickname:e.nickname,embossedName:e.embossed_name,status:e.status,maskPan:e.mask_pan,expMonth:parseInt(e.exp_month,10),expYear:parseInt(e.exp_year,10),lastActivityAt:new Date(e.last_activity_at),lastDigits:e.last_digits,shipToBusiness:e.ship_to_business,atmOption:e.atm_option,atmDailyLimitOption:e.atm_daily_limit_option,nfcOption:e.nfc_option,onlineOption:e.online_option,foreignOption:e.foreign_option,atmMonthlyLimit:e.atm_monthly_limit,atmMonthlySpent:e.atm_monthly_spent,atmDailyLimit:e.atm_daily_limit,atmDailySpent:e.atm_daily_spent,paymentMonthlyLimit:e.payment_monthly_limit,paymentMonthlySpent:e.payment_monthly_spent,paymentDailyLimit:e.payment_daily_limit,paymentDailySpent:e.payment_daily_spent,paymentDailyLimitOption:e.payment_daily_limit_option,paymentTransactionLimit:e.payment_transaction_limit,paymentTransactionLimitOption:e.payment_transaction_limit_option,activeDays:e.active_days,holderId:e.holder_id,bankAccountId:e.bank_account_id,organizationId:e.organization_id,updatedAt:new Date(e.updated_at),createdAt:new Date(e.created_at),shippedAt:new Date(e.shipped_at),cardType:e.card_type,cardLevel:e.card_level,paymentLifespanLimit:e.payment_lifespan_limit,paymentLifespanSpent:e.payment_lifespan_spent,preExpiresAt:new Date(e.pre_expires_at),categories:e.categories,renewed:e.renewed,renewal:e.renewal,...e.parent_card_summary&&{parentCardSummary:{id:e.parent_card_summary.id,lastDigits:e.parent_card_summary.last_digits}},hadOperation:e.had_operation,hadPinOperation:e.had_pin_operation,cardDesign:e.card_design,typeOfPrint:e.type_of_print,upsold:e.upsold,upsell:e.upsell,discardOn:new Date(e.discard_on),reordered:e.reordered}}function re(e){const t=Object.values(M);return(e||[]).filter((e=>t.includes(e)))}const se={getCards:async function({membershipId:e,accessToken:t,stagingToken:n}){try{const i=t||r();if(e&&"string"!=typeof e)throw new s("membershipId must be a string");const a=await async function({membershipId:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=L.getEnvironmentUrls().THIRD_PARTY_API_URL,r=e?`${a}/v2/cards?holder_ids[]=${e}`:`${a}/v2/cards`,s=await fetch(r,i),o=await s.json();if(o.errors)throw new O(o.errors.map((e=>`${e.code}: ${e.detail}`)));return o.cards}({membershipId:e,accessToken:i,stagingToken:n});return a.map((e=>ae(e)))}catch(e){return Promise.reject(e)}},getCard:async function({cardId:e,accessToken:t,stagingToken:n}){try{const i=t||r();if(e&&"string"!=typeof e)throw new s("cardId must be a string");const a=await async function({cardId:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}/v2/cards?ids[]=${e}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.cards[0]}({cardId:e,accessToken:i,stagingToken:n});return ae(a)}catch(e){return Promise.reject(e)}},orderCard:async function(e){try{const t=r(),{uiParentElementId:i,debugMode:a}=h(e.operationSettings);H(e.cardSettings);const s=Q({accessToken:t,stagingToken:n.getStagingToken()||void 0,debugMode:a}),o=await W({iframeUrl:s,parentElementId:i}),c=ie(e.cardSettings),d=await o.postMessage(c);return o.destroy(),ae(d)}catch(e){return Promise.reject(e)}},unlockCard:async function(e){try{const t=r(),{uiParentElementId:i,debugMode:a}=h(e.operationSettings);!function(e){if(!e)throw new s("cardSettings parameter is required for the called function");if(!e.cardId)throw new s("cardId is required for the called function");const t=j({cardId:e.cardId});if(t.length>0)throw new s(t)}(e.cardSettings);const o=Q({accessToken:t,stagingToken:n.getStagingToken()||void 0,debugMode:a}),d=await W({iframeUrl:o,parentElementId:i}),m=function(e){return{actionId:c.CARD_UNLOCK,actionData:{cardId:e.cardSettings.cardId}}}(e),l=await d.postMessage(m);return d.destroy(),ae(l)}catch(e){return Promise.reject(e)}},displayCard:async function(e){try{const t=r(),{uiParentElementId:n}=h(e.operationSettings);!function(e){if(!e)throw new s("cardSettings parameter is required for the called function");if(!e.cardId)throw new s("cardId is required for the called function");const t=j({cardId:e.cardId});if(t.length>0)throw new s(t);let n={};void 0!==e.allowPinReveal&&(n={allowPinReveal:e.allowPinReveal}),void 0!==e.allowBlocking&&(n={...n,allowBlocking:e.allowBlocking});const i=Y(n);if(i.length>0)throw new s(i)}(e.cardSettings);const i=await U(e.cardSettings,t),a=await W({iframeUrl:i,parentElementId:n});return{destroyEmbedUI:()=>{a.destroy()}}}catch(e){return Promise.reject(e)}}},oe=se;function ce({endpointUrl:e,paginationSettings:t}){const n=new URL(e);return t?.page&&n.searchParams.set("page",t.page.toString()),t?.itemsPerPage&&n.searchParams.set("per_page",t.itemsPerPage.toString()),n}function de(e){if(e)return{totalItems:e?.total_count,totalPages:e?.total_pages,currentPage:e?.current_page,itemsPerPage:e?.per_page,previousPage:e?.prev_page||null,nextPage:e?.next_page||null}}function me(e){return{id:e.id,name:e.name,email:e.email,activityTag:e.activity_tag,iban:e.iban,bic:e.bic,currency:e.currency,status:e.status,trusted:e.trusted,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function le(e){return{name:e.name,...e.email&&{email:e.email},...e.activityTag&&{activity_tag:e.activityTag},iban:e.iban,...e.bic&&{bic:e.bic}}}const ue="/v2/sepa/beneficiaries";async function fe({accessToken:e,stagingToken:t,beneficiaryId:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}/${n}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiary}const ge=[{name:"name"},{name:"iban"}];const pe={getBeneficiaries:async function(e){const t=e?.accessToken||r(),n=await async function({paginationSettings:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=ce({endpointUrl:new URL(L.getEnvironmentUrls().THIRD_PARTY_API_URL+ue),paginationSettings:e}),r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return{beneficiaries:s.beneficiaries,meta:s.meta}}({accessToken:t,stagingToken:e?.stagingToken,paginationSettings:e?.paginationSettings}),i=n.beneficiaries.map((e=>me(e))),a=de(n.meta);return{beneficiaries:i,...a?{meta:a}:{}}},getBeneficiary:async function({beneficiaryId:e,accessToken:t,stagingToken:n}){const i=t||r();return function(e){if(!e)throw new s("beneficiaryId parameter is required for the called function");if(e&&"string"!=typeof e)throw new s("beneficiaryId must be a string")}(e),me(await fe({beneficiaryId:e,accessToken:i,stagingToken:n}))},addBeneficiary:async function({beneficiary:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("beneficiary parameter is required for the called function");if("object"!=typeof e)throw new s("beneficiary must be an object");F(e,ge);const t=j({name:e.name,iban:e.iban,email:e.email,activityTag:e.activityTag,bic:e.bic});if(t.length>0)throw new s(t)}(e);return me(await async function({beneficiary:e,accessToken:t,stagingToken:n}){const i={method:"POST",headers:N({accessToken:t,stagingToken:n,idempotencyKey:ne()}),body:JSON.stringify({beneficiary:le(e)})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiary}({beneficiary:e,accessToken:i,stagingToken:n}))},untrustBeneficiaries:async function({beneficiaryIds:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("beneficiaryIds parameter is required for the called function");if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new s("beneficiaryIds must be an array of strings")}(e);return(await async function({beneficiaryIds:e,accessToken:t,stagingToken:n}){const i={method:"PATCH",headers:N({accessToken:t,stagingToken:n}),body:JSON.stringify({ids:e})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}/untrust`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiaries}({beneficiaryIds:e,accessToken:i,stagingToken:n})).map(me)}};function he(e){return{id:e.id,initiatorId:e.initiator_id,bankAccountId:e.bank_account_id,amount:Number(e.amount),amountCents:Number(e.amount_cents),amountCurrency:e.amount_currency,status:e.status,beneficiaryId:e.beneficiary_id,reference:e.reference,note:e.note,declinedReason:e.declined_reason,scheduledDate:new Date(e.scheduled_date),createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at),processedAt:new Date(e.processed_at),completedAt:new Date(e.completed_at),transactionId:e.transaction_id}}function _e(e){const t=e.beneficiaryId||e.beneficiary?.id;return{bank_account_id:e.bankAccountId,beneficiary_id:t,amount:e.amount.toString(),reference:e.reference,...e.note?{note:e.note}:{},...e.scheduledDate?{scheduled_date:e.scheduledDate.toISOString().split("T")[0]}:{},...e.attachments?{attachments:e.attachments}:{}}}const ye="/v2/sepa/transfers";const Te=[{name:"bankAccountId"},{name:"reference"},{name:"amount"}];async function Ie({sepaTransferSettings:e,operationSettings:t}){if(e.beneficiary)return e.beneficiary;return me(await fe({beneficiaryId:e.beneficiaryId,accessToken:t?.accessToken,stagingToken:t?.stagingToken}))}const Ee="browser",be="server";class we extends Error{constructor(e){switch(super(),this.name="InvalidRuntimeError",e){case Ee:this.message="This code is running in a browser environment, but it is expected to run in a server environment.";break;case be:this.message="This code is running in a server environment, but it is expected to run in a browser environment.";break;default:this.message="This code is not expected to run in this environment. Check if the function was server-only or browser-only."}}}const Ae={getSepaTransfers:async function(e={}){const t=e?.accessToken||r(),n=await async function({accessToken:e,stagingToken:t,paginationSettings:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=ce({endpointUrl:new URL(L.getEnvironmentUrls().THIRD_PARTY_API_URL+ye),paginationSettings:n}),r=await fetch(a,i);if(!r.ok)throw new O("Failed to fetch SEPA transfers");const s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return{transfers:s.transfers,meta:s.meta}}({accessToken:t,stagingToken:e?.stagingToken,paginationSettings:e?.paginationSettings}),i=n.transfers.map((e=>he(e))),a=de(n.meta);return{transfers:i,...a?{meta:a}:{}}},getSepaTransfer:async function({sepaTransferId:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("sepaTransferId parameter is required for the called function");if(e&&"string"!=typeof e)throw new s("sepaTransferId must be a string")}(e);return he(await async function({accessToken:e,stagingToken:t,sepaTransferId:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ye}/${n}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.external_transfer}({sepaTransferId:e,accessToken:i,stagingToken:n}))},createSepaTransfer:async function({sepaTransferSettings:e,operationSettings:t}){const i=t?.accessToken||r(),a=t?.stagingToken||n.getStagingToken(),o=t?.idempotencyKey||ne();let d;!function(e){if(!e)throw new s("sepaTransferSettings parameter is required for the called function");if("object"!=typeof e)throw new s("sepaTransferSettings must be an object");if(F(e,Te),!e.beneficiaryId&&!e.beneficiary)throw new s("Either beneficiaryId or beneficiary must be provided");const t=[...j({beneficiaryId:e.beneficiaryId,bankAccountId:e.bankAccountId,note:e.note,reference:e.reference}),...G({amount:e.amount})].flat();if(t.length>0)throw new s(t);if(e.amount>3e4&&(!e.attachments||0===e.attachments.length))throw new s("Attachments are required for transfers over €30,000")}(e);const m={...e,beneficiary:await Ie({sepaTransferSettings:e,operationSettings:{accessToken:i,stagingToken:a||void 0}})};if(m.beneficiary.trusted)d=await async function({transfer:e,accessToken:t,stagingToken:n,idempotencyKey:i}){const a=_e(e),r={method:"POST",headers:N({accessToken:t,stagingToken:n,idempotencyKey:i}),body:JSON.stringify({transfer:a})},s=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ye}`,o=await fetch(s,r),c=await o.json();if(c.errors)throw new O(c.errors.map((e=>`${e.code}: ${e.detail}`)));return c.transfer}({transfer:m,accessToken:i,stagingToken:a||void 0,idempotencyKey:o});else{if("undefined"==typeof window||"undefined"==typeof document)throw new we(Ee);const{uiParentElementId:e,debugMode:n}=h(t);let r;try{const t=Q({accessToken:i,stagingToken:a||void 0,debugMode:n});r=await W({iframeUrl:t,parentElementId:e});const s=_e(m);d=await r.postMessage({actionId:c.TRANSFER_SINGLE_CREATE,actionData:{body:{transfer:{...s}},idempotencyKey:o}})}finally{r?.destroy()}}return he(d)}};e.beneficiaries=pe,e.cards=oe,e.constants=P,e.initialize=v,e.logout=D,e.sepaTransfers=Ae}));
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).QontoEmbed={})}(this,(function(e){"use strict";class t{constructor(){this.accessToken=null,this.stagingToken=null}static getInstance(){return t.instance||(t.instance=new t),t.instance}setAccessToken(e){this.accessToken=e}getAccessToken(){return this.accessToken}hasAccessToken(){return null!==this.accessToken&&""!==this.accessToken}clearAccessToken(){this.accessToken=null}setStagingToken(e){this.stagingToken=e}getStagingToken(){return this.stagingToken}hasStagingToken(){return null!==this.stagingToken&&""!==this.stagingToken}clearStagingToken(){this.stagingToken=null}}const n=t.getInstance();class i extends Error{constructor(){super(),this.stack=""}toString(){return`${this.name}: ${this.message}`}}class a extends i{constructor(){super(),this.name="AuthenticationError",this.message="Authentication failed due to missing or invalid access token.\nEnsure you have called the initialize function with a valid access token."}}function r(){if(!n.hasAccessToken())throw new a;return n.getAccessToken()}class s extends i{constructor(e){super(),this.name="InvalidParametersError",this.invalidParameters=Array.isArray(e)?e:[e],this.message=`Invalid parameters were passed to the function:\n${this.invalidParameters.map((e=>e)).join("\n")}`}}const o={READY:"qonto.ready"},c={CARD_SEE:"card.see",CARD_SEE_DETAILS:"card.see-details",CARD_ORDER:"card.order",CARD_UNLOCK:"card.unlock",CARD_SHOW_PIN:"card.show.pin",CARD_SET_PIN:"card.set.pin",TRANSFER_SINGLE_CREATE:"transfer.single.create",BENEFICIARIES_TRUST:"beneficiary.trust"},d={PRODUCTION:"production",STAGING:"staging",LOCAL:"local"},m={MASTER:"master",SANDBOX:"sandbox",QA:"qa"},l={EN:"en",FR:"fr",DE:"de",ES:"es",IT:"it",PT:"pt"},u={PASSKEY:"passkey",SMS_OTP:"sms-otp",PAIRED_DEVICE:"paired-device"};var f=Object.freeze({__proto__:null,ACTIONS:c,ACTIVITY_TAGS:{ATM:"atm",FALLBACK:"fallback",FEES:"fees",FINANCE:"finance",FOOD_AND_GROCERY:"food_and_grocery",GAS_STATION:"gas_station",HARDWARE_AND_EQUIPMENT:"hardware_and_equipment",HOTEL_AND_LODGING:"hotel_and_lodging",INSURANCE:"insurance",IT_AND_ELECTRONICS:"it_and_electronics",LEGAL_AND_ACCOUNTING:"legal_and_accounting",LOGISTICS:"logistics",MANUFACTURING:"manufacturing",MARKETING:"marketing",OFFICE_RENTAL:"office_rental",OFFICE_SUPPLY:"office_supply",ONLINE_SERVICE:"online_service",OTHER_EXPENSE:"other_expense",OTHER_INCOME:"other_income",OTHER_SERVICE:"other_service",PENDING:"pending",REFUND:"refund",RESTAURANT_AND_BAR:"restaurant_and_bar",SALES:"sales",SALARY:"salary",SUBSCRIPTION:"subscription",TAX:"tax",TRANSPORT:"transport",TREASURY_AND_INTERCO:"treasury_and_interco",UTILITY:"utility",VOUCHER:"voucher"},BENEFICIARY_STATUSES:{PENDING:"pending",VALIDATED:"validated",DECLINED:"declined"},BRANCHES:m,ENVIRONMENTS:d,IFRAME_EVENTS:o,LOCALES:l,MFA_METHODS:u,TRANSFER_DECLINE_REASONS:{BENEFICIARY_BIC_INVALID:"beneficiary_bic_invalid",BENEFICIARY_IBAN_INVALID:"beneficiary_iban_invalid",BENEFICIARY_STATUS:"beneficiary_status",BENEFICIARY_NETWORK_RULES_ERROR:"beneficiary_network_rules_error",ORGANISATION_COMPLIANCE_REASONS:"organisation_compliance_reasons",DEBIT_ACCOUNT_INSUFFICIENT_FUNDS:"debit_account_insufficient_funds",QONTO_PROCESSING_FAILED:"qonto_processing_failed"},TRANSFER_STATUSES:{PENDING:"pending",PROCESSING:"processing",CANCELED:"canceled",DECLINED:"declined",SETTLED:"settled"}});class g{constructor(){this.uiParentElementId=null,this.mfaPreference=u.PASSKEY,this.debugMode=!1}static getInstance(){return g.instance||(g.instance=new g),g.instance}setSettings(e){e.uiParentElementId&&(this.uiParentElementId=e.uiParentElementId),e.mfaPreference&&(this.mfaPreference=e.mfaPreference),e.debugMode&&(this.debugMode=e.debugMode)}getUIParentElementId(){return this.uiParentElementId}getMFAPreference(){return this.mfaPreference}getDebugMode(){return this.debugMode}clearSettings(){this.uiParentElementId=null,this.mfaPreference=u.PASSKEY}}const p=g.getInstance();function h(e){const t=e?.uiParentElementId||p.getUIParentElementId();if(!t)throw new s("operationSettings parameter must have a uiParentElementId for the called function.\nYou can pass it either to the initialize function or in a per function basis.");const n=e?.mfaPreference||p.getMFAPreference();if(n&&!Object.values(u).includes(n))throw new s("operationSettings.mfaPreference must be one of passkey, paired-device or sms-otp.");const i=e?.debugMode||p.getDebugMode();if(void 0!==i&&"boolean"!=typeof i)throw new s("operationSettings.debugMode must be a boolean.");return{uiParentElementId:t,mfaPreference:n,debugMode:i,...e}}const _=Object.values(l);function y(e){if(!function(e){return _.includes(e)}(e))throw new s(`Unsupported locale: ${e}. The locale must be one of: ${_.join(", ")}.`);return e}function T(e){if(!e?.accessToken)throw new s("Access token is required when calling initialize()");return e?.operationSettings&&h(e.operationSettings),function(e){if(e.environment){if(!["production","staging","local"].includes(e.environment))throw new s('If provided, environment must be either "production" or "staging"\nYou can "import constants from @qonto/embed-sdk/common" and then use "constants.environment.PRODUCTION" or "constants.environment.STAGING"');if(e.branch&&!["master","sandbox","qa"].includes(e.branch))throw new s('If provided, branch must be either "master", "sandbox" or "qa"\nYou can "import constants from @qonto/embed-sdk/common" and then use "constants.branch.MASTER" or "constants.environment.SANDBOX" and so on')}}(e),e.locale&&y(e.locale),e}const I="https://embed.qonto.com",E="https://embed-js{branch}.staging.qonto.co",b="https://embed.dev.qonto.co",w={[d.PRODUCTION]:{IFRAME_BASE_URL:I,IFRAME_URL:`${I}/connect`,THIRD_PARTY_API_URL:"https://thirdparty.qonto.com"},[d.STAGING]:{IFRAME_BASE_URL:E,IFRAME_URL:`${E}/connect`,THIRD_PARTY_API_URL:"https://thirdparty{branch}.staging.qonto.co"},[d.LOCAL]:{IFRAME_BASE_URL:b,IFRAME_URL:`${b}/connect`,THIRD_PARTY_API_URL:"https://thirdparty{branch}.staging.qonto.co"}};class A{constructor(){this.environment=d.PRODUCTION,this.branch=m.SANDBOX;const e=process.env.QONTO_EMBED_ENVIRONMENT,t=process.env.QONTO_EMBED_BRANCH;this.environment=Object.values(d).includes(e)?e:d.PRODUCTION,this.branch=Object.values(m).includes(t)?t:m.SANDBOX}static getInstance(){return A.instance||(A.instance=new A),A.instance}setEnvironment(e){this.environment=e}getEnvironment(){return this.environment}setBranch(e){this.branch=e}getBranch(){return this.branch}clear(){this.environment=d.PRODUCTION,this.branch=m.MASTER}getEnvironmentUrls(){if(this.environment===d.PRODUCTION)return w.production;{const e=w[this.environment];return Object.entries(e).reduce(((e,[t,n])=>({...e,[t]:n.replace("{branch}",`-${this.branch}`)})),{})}}}const L=A.getInstance();class R{constructor(){this.currentLocale="en"}static getInstance(){return R.instance||(R.instance=new R),R.instance}setLocale(e){this.currentLocale=e}getLocale(){return this.currentLocale}setDefaultLocale(){this.currentLocale="en"}}const k=R.getInstance();const S={initialize:function(e){const{accessToken:t,stagingToken:i,operationSettings:a,environment:r,branch:s,locale:o}=T(e);n.setAccessToken(t),i&&n.setStagingToken(i),o&&k.setLocale(o),a&&p.setSettings(a),r&&(L.setEnvironment(r),s&&L.setBranch(s))},logout:function(){n.clearAccessToken(),n.clearStagingToken(),k.setDefaultLocale()},constants:f},{initialize:v,logout:D,constants:P}=S;class O extends i{constructor(e){super();const t=Array.isArray(e)?e.join("\n"):e;this.name="EmbedApiError",this.message=`The call to the Embed API failed with the following errors:\n${t}`}}function N({accessToken:e,stagingToken:t,idempotencyKey:i,mfaPreference:a}){const r=new Headers;r.append("Authorization",`Bearer ${e}`);const s=t||n.getStagingToken();s&&r.append("X-Qonto-Staging-Token",s),i&&r.append("X-Qonto-Idempotency-Key",i);const o=a||p.getMFAPreference();return o&&r.append("X-Qonto-2fa-Preference",o),r.append("Content-Type","application/json"),r.append("Accept-Language",k.getLocale()),r}async function U(e,t,n){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=L.getEnvironmentUrls().THIRD_PARTY_API_URL,r=await fetch(`${a}/v2/cards/${e.cardId}/data_view`,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return function(e,t){const n=new URL(e);return"boolean"==typeof t.allowPinReveal&&n.searchParams.set("canSeePin",t.allowPinReveal?"true":"false"),"boolean"==typeof t.allowBlocking&&n.searchParams.set("canBlock",t.allowBlocking?"true":"false"),n.toString()}(s.iframe_url,e)}var C;!function(e){e.PENDING="pending",e.ONHOLD="onhold",e.ORDER_CANCELED="order_canceled",e.LIVE="live",e.PAUSED="paused",e.STOLEN="stolen",e.LOST="lost",e.PIN_BLOCKED="pin_blocked",e.DELETED="deleted",e.PRE_EXPIRED="pre_expired",e.EXPIRED="expired",e.DISCARDED="discarded",e.SHIPPED_LOST="shipped_lost",e.ABUSIVE="abusive"}(C||(C={}));const M={TRANSPORT:"transport",RESTAURANT_AND_BAR:"restaurant_and_bar",FOOD_AND_GROCERY:"food_and_grocery",IT_AND_ELECTRONICS:"it_and_electronics",UTILITY:"utility",TAX:"tax",LEGAL_AND_ACCOUNTING:"legal_and_accounting",ATM:"atm",OFFICE_SUPPLY:"office_supply",HARDWARE_AND_EQUIPMENT:"hardware_and_equipment",FINANCE:"finance"};var $,B;function F(e,t){const n=t.filter((t=>t.requiredIfPresent?!e[t.name]&&e[t.requiredIfPresent]:void 0===e[t.name])).map((e=>e.name));if(n.length>0)throw new s(n.map((e=>`Missing required parameter: ${e}`)))}function j(e){return Object.entries(e).filter((([,e])=>void 0!==e)).filter((([,e])=>"string"!=typeof e)).map((([e])=>`${e} must be a string`))}function Y(e){return Object.entries(e).filter((([,e])=>void 0!==e&&!1!==e&&!0!==e)).map((([e])=>`${e} must be a boolean`))}function G(e){return Object.entries(e).filter((([,e])=>void 0!==e)).filter((([,e])=>"number"!=typeof e)).map((([e])=>`${e} must be a number`))}!function(e){e.VIRTUAL="virtual"}($||($={})),function(e){e.METAL="metal",e.PLUS="plus",e.STANDARD="standard"}(B||(B={}));const q=[{name:"organizationId"},{name:"membershipId"},{name:"bankAccountId"},{name:"monthlyLimit"},{name:"cardLevel"}],x=[...q,{name:"atmDailyLimit",requiredIfPresent:"hasAtmDailyLimit"},{name:"hasAtmDailyLimit",requiredIfPresent:"hasAtmOption"},{name:"atmMonthlyLimit",requiredIfPresent:"hasAtmOption"},{name:"shipToBusiness"},{name:"cardLevel"}];function H(e){if(!e)throw new s("cardSettings parameter is required for the called function");return"virtual"===e.cardLevel?function(e){return F(e,q),function(e){const{membershipId:t,organizationId:n,bankAccountId:i,hasDailyLimit:a,hasTransactionLimit:r,monthlyLimit:o,dailyLimit:c,transactionLimit:d,activeDays:m,categories:l,cardLevel:u}=e,f=function(e){return"virtual"!==e?['cardLevel must be "virtual"']:[]}(u),g=j({membershipId:t,organizationId:n,bankAccountId:i}),p=Y({hasDailyLimit:a,hasTransactionLimit:r}),h=G({monthlyLimit:o,dailyLimit:c,transactionLimit:d}),_=z(m),y=K(l),T=[...f,...g,...p,...h,..._,...y];if(T.length>0)throw new s(T)}(e),e}(e):function(e){F(e,x),function(e){const{membershipId:t,organizationId:n,bankAccountId:i,hasDailyLimit:a,hasTransactionLimit:r,monthlyLimit:o,dailyLimit:c,transactionLimit:d,activeDays:m,categories:l,cardLevel:u,hasNfcOption:f,hasForeignPaymentOption:g,hasOnlinePaymentOption:p,shipToBusiness:h,hasAtmOption:_,hasAtmDailyLimit:y,atmDailyLimit:T,atmMonthlyLimit:I,address:E,cardDesign:b,typeOfPrint:w}=e,A=function(e){return Object.values(B).includes(e)?[]:['cardLevel must be one of "standard", "plus", "metal"']}(u),L=function(e){const t=null!=e&&"string"!=typeof e,n=!["print","embossed",void 0,null].includes(e);return t||n?['typeOfPrint must be one of "print", "embossed" or null']:[]}(w),R=j({membershipId:t,organizationId:n,bankAccountId:i}),k=Y({hasDailyLimit:a,hasTransactionLimit:r,hasAtmOption:_,hasNfcOption:f,hasForeignPaymentOption:g,hasOnlinePaymentOption:p,hasAtmDailyLimit:y,shipToBusiness:h}),S=G({monthlyLimit:o,dailyLimit:c,transactionLimit:d,atmDailyLimit:T,atmMonthlyLimit:I}),v=z(m),D=K(l),P=function(e){return["undefined","string"].includes(typeof e)?[]:["cardDesign must be a string"]}(b),O=function(e,t){if(t)return[];return!e||e.contactName&&e.firstLine&&e.zipCode&&e.city&&e.country?[]:["address must contain at least contactName, firstLine, zipCode, city and country properties"]}(E,h),N=[...A,...R,...k,...S,...v,...D,...L,...P,...O];if(N.length>0)throw new s(N)}(e)}(e)}function z(e){const t=!Array.isArray(e)||!e.every((e=>Number.isInteger(e)&&e>0&&e<8));return void 0!==e&&t?["activeDays must be an array of integers between 1 and 7"]:[]}function K(e){const t=!Array.isArray(e)||e.some((e=>"string"!=typeof e));return void 0!==e&&t?["categories must be an array of strings"]:[]}class V extends i{constructor(e){super(),this.name="EmbedOperationError",this.message=e}}class X{constructor(e){this.options=e,this.iframe=null,this.parentElement=null,this.messageListeners=new Map,this.defaultTimeout=3e4;const t=new URL(e.iframeUrl);this.targetOrigin=`${t.protocol}//${t.host}`}async initialize(){if(this.iframe)return this;if(this.parentElement=document.getElementById(this.options.parentElementId),!this.parentElement)throw new V(`Could not install the authentication UI because the parent element with id ${this.options.parentElementId} was not found.\nPlease make sure to pass a valid parentElementId when calling the method.`);return new Promise(((e,t)=>{this.iframe=document.createElement("iframe"),this.iframe.src=this.options.iframeUrl,this.iframe.style.width="100%",this.iframe.style.height="100%",this.iframe.style.border="none";const n=this.options.timeout||this.defaultTimeout,i=setTimeout((()=>{window.removeEventListener("message",a),t(new V(`Could not install the authentication UI because the timeout of ${n}ms was reached.\nPlease make sure the application can reach the Internet.`))}),n),a=t=>{t.data.eventId===o.READY&&(clearTimeout(i),window.removeEventListener("message",a),e(this))};window.addEventListener("message",a),this.parentElement?.appendChild(this.iframe)}))}postMessage(e){return this.iframe&&this.iframe.contentWindow?new Promise(((t,n)=>{const i=a=>{if(a.data?.actionId===e.actionId){if("error"===a.data.status)return this.removeMessageListener(e.actionId,i),n(new V(`An error occurred when performing the action ${e.actionId}.\n${JSON.stringify(a.data.payload)}`));this.removeMessageListener(e.actionId,i),t(a.data.payload)}};this.addMessageListener(e.actionId,i),this.iframe?.contentWindow?.postMessage(e,this.targetOrigin)})):Promise.reject(new V("Attempted to perform an Embed operation without having the authentication UI initialized."))}addMessageListener(e,t){this.messageListeners.has(e)||this.messageListeners.set(e,[]);this.messageListeners.get(e).push(t),window.addEventListener("message",t)}removeMessageListener(e,t){const n=this.messageListeners.get(e);if(n){const e=n.indexOf(t);-1!==e&&(n.splice(e,1),window.removeEventListener("message",t))}}destroy(){this.messageListeners.forEach((e=>{e.forEach((e=>{window.removeEventListener("message",e)}))})),this.messageListeners.clear(),this.iframe&&this.parentElement&&(this.parentElement.removeChild(this.iframe),this.iframe=null)}}function Q({accessToken:e,stagingToken:t,locale:n,debugMode:i}){const a=i||!1,r=n||k.getLocale(),s=L.getEnvironmentUrls().IFRAME_URL,o=t?`;staging_token=${encodeURIComponent(t)}`:"";return`${s}?debug=${a}&lang=${encodeURIComponent(r)}#access_token=${encodeURIComponent(e)}${o}`}function W({parentElementId:e,iframeUrl:t}){return new X({parentElementId:e,iframeUrl:t}).initialize()}const J=[];for(let e=0;e<256;++e)J.push((e+256).toString(16).slice(1));let Z;const ee=new Uint8Array(16);var te={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function ne(e,t,n){if(te.randomUUID&&!e)return te.randomUUID();const i=(e=e||{}).random??e.rng?.()??function(){if(!Z){if("undefined"==typeof crypto||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");Z=crypto.getRandomValues.bind(crypto)}return Z(ee)}();if(i.length<16)throw new Error("Random bytes length must be >= 16");return i[6]=15&i[6]|64,i[8]=63&i[8]|128,function(e,t=0){return(J[e[t+0]]+J[e[t+1]]+J[e[t+2]]+J[e[t+3]]+"-"+J[e[t+4]]+J[e[t+5]]+"-"+J[e[t+6]]+J[e[t+7]]+"-"+J[e[t+8]]+J[e[t+9]]+"-"+J[e[t+10]]+J[e[t+11]]+J[e[t+12]]+J[e[t+13]]+J[e[t+14]]+J[e[t+15]]).toLowerCase()}(i)}function ie(e){return"virtual"===e.cardLevel?function(e){const t=re(e.categories);return{actionId:c.CARD_ORDER,actionData:{idempotencyKey:ne(),body:{card:{payment_monthly_limit:e.monthlyLimit,payment_daily_limit:e.dailyLimit,payment_daily_limit_option:e.hasDailyLimit,payment_transaction_limit:e.transactionLimit,payment_transaction_limit_option:e.hasTransactionLimit,active_days:e.activeDays||[],holder_id:e.membershipId,organization_id:e.organizationId,bank_account_id:e.bankAccountId,categories:t,card_level:e.cardLevel}}}}}(e):function(e){const t=re(e.categories);return{actionId:c.CARD_ORDER,actionData:{idempotencyKey:ne(),body:{card:{payment_monthly_limit:e.monthlyLimit,payment_daily_limit:e.dailyLimit,payment_daily_limit_option:e.hasDailyLimit,payment_transaction_limit:e.transactionLimit,payment_transaction_limit_option:e.hasTransactionLimit,active_days:e.activeDays||[],holder_id:e.membershipId,organization_id:e.organizationId,bank_account_id:e.bankAccountId,categories:t,card_level:e.cardLevel,card_design:e.cardDesign,..."plus"===e.cardLevel&&{type_of_print:e.typeOfPrint},ship_to_business_address:e.shipToBusiness,atm_option:e.hasAtmOption,nfc_option:e.hasNfcOption,foreign_option:e.hasForeignPaymentOption,online_option:e.hasOnlinePaymentOption,atm_daily_limit:e.atmDailyLimit,atm_monthly_limit:e.atmMonthlyLimit,...!e.shipToBusiness&&{address:{contact_name:e.address?.contactName,first_line:e.address?.firstLine,second_line:e.address?.secondLine,third_line:e.address?.thirdLine,zipcode:e.address?.zipCode,city:e.address?.city,country:e.address?.country}}}}}}}(e)}function ae(e){return{id:e.id,nickname:e.nickname,embossedName:e.embossed_name,status:e.status,maskPan:e.mask_pan,expMonth:parseInt(e.exp_month,10),expYear:parseInt(e.exp_year,10),lastActivityAt:new Date(e.last_activity_at),lastDigits:e.last_digits,shipToBusiness:e.ship_to_business,atmOption:e.atm_option,atmDailyLimitOption:e.atm_daily_limit_option,nfcOption:e.nfc_option,onlineOption:e.online_option,foreignOption:e.foreign_option,atmMonthlyLimit:e.atm_monthly_limit,atmMonthlySpent:e.atm_monthly_spent,atmDailyLimit:e.atm_daily_limit,atmDailySpent:e.atm_daily_spent,paymentMonthlyLimit:e.payment_monthly_limit,paymentMonthlySpent:e.payment_monthly_spent,paymentDailyLimit:e.payment_daily_limit,paymentDailySpent:e.payment_daily_spent,paymentDailyLimitOption:e.payment_daily_limit_option,paymentTransactionLimit:e.payment_transaction_limit,paymentTransactionLimitOption:e.payment_transaction_limit_option,activeDays:e.active_days,holderId:e.holder_id,bankAccountId:e.bank_account_id,organizationId:e.organization_id,updatedAt:new Date(e.updated_at),createdAt:new Date(e.created_at),shippedAt:new Date(e.shipped_at),cardType:e.card_type,cardLevel:e.card_level,paymentLifespanLimit:e.payment_lifespan_limit,paymentLifespanSpent:e.payment_lifespan_spent,preExpiresAt:new Date(e.pre_expires_at),categories:e.categories,renewed:e.renewed,renewal:e.renewal,...e.parent_card_summary&&{parentCardSummary:{id:e.parent_card_summary.id,lastDigits:e.parent_card_summary.last_digits}},hadOperation:e.had_operation,hadPinOperation:e.had_pin_operation,cardDesign:e.card_design,typeOfPrint:e.type_of_print,upsold:e.upsold,upsell:e.upsell,discardOn:new Date(e.discard_on),reordered:e.reordered}}function re(e){const t=Object.values(M);return(e||[]).filter((e=>t.includes(e)))}const se={getCards:async function({membershipId:e,accessToken:t,stagingToken:n}){try{const i=t||r();if(e&&"string"!=typeof e)throw new s("membershipId must be a string");const a=await async function({membershipId:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=L.getEnvironmentUrls().THIRD_PARTY_API_URL,r=e?`${a}/v2/cards?holder_ids[]=${e}`:`${a}/v2/cards`,s=await fetch(r,i),o=await s.json();if(o.errors)throw new O(o.errors.map((e=>`${e.code}: ${e.detail}`)));return o.cards}({membershipId:e,accessToken:i,stagingToken:n});return a.map((e=>ae(e)))}catch(e){return Promise.reject(e)}},getCard:async function({cardId:e,accessToken:t,stagingToken:n}){try{const i=t||r();if(e&&"string"!=typeof e)throw new s("cardId must be a string");const a=await async function({cardId:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}/v2/cards?ids[]=${e}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.cards[0]}({cardId:e,accessToken:i,stagingToken:n});return ae(a)}catch(e){return Promise.reject(e)}},orderCard:async function(e){try{const t=r(),{uiParentElementId:i,debugMode:a}=h(e.operationSettings);H(e.cardSettings);const s=Q({accessToken:t,stagingToken:n.getStagingToken()||void 0,debugMode:a}),o=await W({iframeUrl:s,parentElementId:i}),c=ie(e.cardSettings),d=await o.postMessage(c);return o.destroy(),ae(d)}catch(e){return Promise.reject(e)}},unlockCard:async function(e){try{const t=r(),{uiParentElementId:i,debugMode:a}=h(e.operationSettings);!function(e){if(!e)throw new s("cardSettings parameter is required for the called function");if(!e.cardId)throw new s("cardId is required for the called function");const t=j({cardId:e.cardId});if(t.length>0)throw new s(t)}(e.cardSettings);const o=Q({accessToken:t,stagingToken:n.getStagingToken()||void 0,debugMode:a}),d=await W({iframeUrl:o,parentElementId:i}),m=function(e){return{actionId:c.CARD_UNLOCK,actionData:{cardId:e.cardSettings.cardId}}}(e),l=await d.postMessage(m);return d.destroy(),ae(l)}catch(e){return Promise.reject(e)}},displayCard:async function(e){try{const t=r(),{uiParentElementId:n}=h(e.operationSettings);!function(e){if(!e)throw new s("cardSettings parameter is required for the called function");if(!e.cardId)throw new s("cardId is required for the called function");const t=j({cardId:e.cardId});if(t.length>0)throw new s(t);let n={};void 0!==e.allowPinReveal&&(n={allowPinReveal:e.allowPinReveal}),void 0!==e.allowBlocking&&(n={...n,allowBlocking:e.allowBlocking});const i=Y(n);if(i.length>0)throw new s(i)}(e.cardSettings);const i=await U(e.cardSettings,t),a=await W({iframeUrl:i,parentElementId:n});return{destroyEmbedUI:()=>{a.destroy()}}}catch(e){return Promise.reject(e)}}},oe=se;function ce({endpointUrl:e,paginationSettings:t}){const n=new URL(e);return t?.page&&n.searchParams.set("page",t.page.toString()),t?.itemsPerPage&&n.searchParams.set("per_page",t.itemsPerPage.toString()),n}function de(e){if(e)return{totalItems:e?.total_count,totalPages:e?.total_pages,currentPage:e?.current_page,itemsPerPage:e?.per_page,previousPage:e?.prev_page||null,nextPage:e?.next_page||null}}function me(e){return{id:e.id,name:e.name,email:e.email,activityTag:e.activity_tag,iban:e.iban,bic:e.bic,currency:e.currency,status:e.status,trusted:e.trusted,createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at)}}function le(e){return{name:e.name,...e.email&&{email:e.email},...e.activityTag&&{activity_tag:e.activityTag},iban:e.iban,...e.bic&&{bic:e.bic}}}const ue="/v2/sepa/beneficiaries";async function fe({accessToken:e,stagingToken:t,beneficiaryId:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}/${n}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiary}const ge=[{name:"name"},{name:"iban"}];const pe={getBeneficiaries:async function(e){const t=e?.accessToken||r(),n=await async function({paginationSettings:e,accessToken:t,stagingToken:n}){const i={method:"GET",headers:N({accessToken:t,stagingToken:n})},a=ce({endpointUrl:new URL(L.getEnvironmentUrls().THIRD_PARTY_API_URL+ue),paginationSettings:e}),r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return{beneficiaries:s.beneficiaries,meta:s.meta}}({accessToken:t,stagingToken:e?.stagingToken,paginationSettings:e?.paginationSettings}),i=n.beneficiaries.map((e=>me(e))),a=de(n.meta);return{beneficiaries:i,...a?{meta:a}:{}}},getBeneficiary:async function({beneficiaryId:e,accessToken:t,stagingToken:n}){const i=t||r();return function(e){if(!e)throw new s("beneficiaryId parameter is required for the called function");if(e&&"string"!=typeof e)throw new s("beneficiaryId must be a string")}(e),me(await fe({beneficiaryId:e,accessToken:i,stagingToken:n}))},addBeneficiary:async function({beneficiary:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("beneficiary parameter is required for the called function");if("object"!=typeof e)throw new s("beneficiary must be an object");F(e,ge);const t=j({name:e.name,iban:e.iban,email:e.email,activityTag:e.activityTag,bic:e.bic});if(t.length>0)throw new s(t)}(e);return me(await async function({beneficiary:e,accessToken:t,stagingToken:n}){const i={method:"POST",headers:N({accessToken:t,stagingToken:n,idempotencyKey:ne()}),body:JSON.stringify({beneficiary:le(e)})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiary}({beneficiary:e,accessToken:i,stagingToken:n}))},untrustBeneficiaries:async function({beneficiaryIds:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("beneficiaryIds parameter is required for the called function");if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new s("beneficiaryIds must be an array of strings")}(e);return(await async function({beneficiaryIds:e,accessToken:t,stagingToken:n}){const i={method:"PATCH",headers:N({accessToken:t,stagingToken:n}),body:JSON.stringify({ids:e})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ue}/untrust`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.beneficiaries}({beneficiaryIds:e,accessToken:i,stagingToken:n})).map(me)}};function he(e){return{id:e.id,initiatorId:e.initiator_id,bankAccountId:e.bank_account_id,amount:Number(e.amount),amountCents:Number(e.amount_cents),amountCurrency:e.amount_currency,status:e.status,beneficiaryId:e.beneficiary_id,reference:e.reference,note:e.note,declinedReason:e.declined_reason,scheduledDate:new Date(e.scheduled_date),createdAt:new Date(e.created_at),updatedAt:new Date(e.updated_at),processedAt:new Date(e.processed_at),completedAt:new Date(e.completed_at),transactionId:e.transaction_id}}function _e(e){const t=e.beneficiaryId||e.beneficiary?.id;return{bank_account_id:e.bankAccountId,beneficiary_id:t,amount:e.amount.toString(),reference:e.reference,...e.note?{note:e.note}:{},...e.scheduledDate?{scheduled_date:e.scheduledDate.toISOString().split("T")[0]}:{},...e.attachments?{attachments:e.attachments}:{}}}const ye="/v2/sepa/transfers";const Te=[{name:"bankAccountId"},{name:"reference"},{name:"amount"}];async function Ie({sepaTransferSettings:e,operationSettings:t}){if(e.beneficiary)return e.beneficiary;return me(await fe({beneficiaryId:e.beneficiaryId,accessToken:t?.accessToken,stagingToken:t?.stagingToken}))}const Ee="browser",be="server";class we extends Error{constructor(e){switch(super(),this.name="InvalidRuntimeError",e){case Ee:this.message="This code is running in a browser environment, but it is expected to run in a server environment.";break;case be:this.message="This code is running in a server environment, but it is expected to run in a browser environment.";break;default:this.message="This code is not expected to run in this environment. Check if the function was server-only or browser-only."}}}const Ae={getSepaTransfers:async function(e={}){const t=e?.accessToken||r(),n=await async function({accessToken:e,stagingToken:t,paginationSettings:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=ce({endpointUrl:new URL(L.getEnvironmentUrls().THIRD_PARTY_API_URL+ye),paginationSettings:n}),r=await fetch(a,i);if(!r.ok)throw new O("Failed to fetch SEPA transfers");const s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return{transfers:s.transfers,meta:s.meta}}({accessToken:t,stagingToken:e?.stagingToken,paginationSettings:e?.paginationSettings}),i=n.transfers.map((e=>he(e))),a=de(n.meta);return{transfers:i,...a?{meta:a}:{}}},getSepaTransfer:async function({sepaTransferId:e,accessToken:t,stagingToken:n}){const i=t||r();!function(e){if(!e)throw new s("sepaTransferId parameter is required for the called function");if(e&&"string"!=typeof e)throw new s("sepaTransferId must be a string")}(e);return he(await async function({accessToken:e,stagingToken:t,sepaTransferId:n}){const i={method:"GET",headers:N({accessToken:e,stagingToken:t})},a=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ye}/${n}`,r=await fetch(a,i),s=await r.json();if(s.errors)throw new O(s.errors.map((e=>`${e.code}: ${e.detail}`)));return s.external_transfer}({sepaTransferId:e,accessToken:i,stagingToken:n}))},createSepaTransfer:async function({sepaTransferSettings:e,operationSettings:t}){const i=t?.accessToken||r(),a=t?.stagingToken||n.getStagingToken(),o=t?.idempotencyKey||ne();let d;!function(e){if(!e)throw new s("sepaTransferSettings parameter is required for the called function");if("object"!=typeof e)throw new s("sepaTransferSettings must be an object");if(F(e,Te),!e.beneficiaryId&&!e.beneficiary)throw new s("Either beneficiaryId or beneficiary must be provided");const t=[...j({beneficiaryId:e.beneficiaryId,bankAccountId:e.bankAccountId,note:e.note,reference:e.reference}),...G({amount:e.amount})].flat();if(t.length>0)throw new s(t);if(e.amount>3e4&&(!e.attachments||0===e.attachments.length))throw new s("Attachments are required for transfers over €30,000")}(e);const m={...e,beneficiary:await Ie({sepaTransferSettings:e,operationSettings:{accessToken:i,stagingToken:a||void 0}})};if(m.beneficiary.trusted)d=await async function({transfer:e,accessToken:t,stagingToken:n,idempotencyKey:i}){const a=_e(e),r={method:"POST",headers:N({accessToken:t,stagingToken:n,idempotencyKey:i}),body:JSON.stringify({transfer:a})},s=`${L.getEnvironmentUrls().THIRD_PARTY_API_URL}${ye}`,o=await fetch(s,r),c=await o.json();if(c.errors)throw new O(c.errors.map((e=>`${e.code}: ${e.detail}`)));return c.transfer}({transfer:m,accessToken:i,stagingToken:a||void 0,idempotencyKey:o});else{if("undefined"==typeof window||"undefined"==typeof document)throw new we(Ee);const{uiParentElementId:e,debugMode:n}=h(t);let r;try{const t=Q({accessToken:i,stagingToken:a||void 0,debugMode:n});r=await W({iframeUrl:t,parentElementId:e});const s=_e(m);d=await r.postMessage({actionId:c.TRANSFER_SINGLE_CREATE,actionData:{body:{transfer:{...s}},idempotencyKey:o}})}finally{r?.destroy()}}return he(d)}};e.beneficiaries=pe,e.cards=oe,e.constants=P,e.initialize=v,e.logout=D,e.sepaTransfers=Ae}));
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import"../common/auth/auth.js";import{validatePresenceOfAuthToken as
|
|
1
|
+
import"../common/auth/auth.js";import{validatePresenceOfAuthToken as n}from"../common/auth/auth.validate.js";import{untrustBeneficiaries as e,addBeneficiary as i,getBeneficiary as a,getBeneficiaries as o}from"./beneficiaries.api.js";import{serializeBeneficiary as s}from"./beneficiaries.serializer.js";import{validateTrustBeneficiariesParams as t,validateAddBeneficiaryParams as c,validateGetBeneficiaryParams as r}from"./beneficiaries.validate.js";import{serializePaginationResponse as m}from"../common/api-pagination/api-pagination.js";import"../common/environment/environment-manager.js";import"../common/locale/locale-manager.js";import"../common/operation-settings/operation-settings.js";async function g(e){const i=e?.accessToken||n(),a=await o({accessToken:i,stagingToken:e?.stagingToken,paginationSettings:e?.paginationSettings}),t=a.beneficiaries.map((n=>s(n))),c=m(a.meta);return{beneficiaries:t,...c?{meta:c}:{}}}async function f({beneficiaryId:e,accessToken:i,stagingToken:o}){const t=i||n();r(e);const c=await a({beneficiaryId:e,accessToken:t,stagingToken:o});return s(c)}async function p({beneficiary:e,accessToken:a,stagingToken:o}){const t=a||n();c(e);const r=await i({beneficiary:e,accessToken:t,stagingToken:o});return s(r)}async function k({beneficiaryIds:i,accessToken:a,stagingToken:o}){const c=a||n();t(i);return(await e({beneficiaryIds:i,accessToken:c,stagingToken:o})).map(s)}export{p as addBeneficiary,g as getBeneficiaries,f as getBeneficiary,k as untrustBeneficiaries};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{InvalidParametersError as e}from"../errors/InvalidParametersError.js";import{validatePresenceOfRequiredParams as r,validateExpectedStringValues as i}from"../validation/input-param-validation.js";const n=[{name:"name"},{name:"iban"}];function t(r){if(!r)throw new e("beneficiaryId parameter is required for the called function");if(r&&"string"!=typeof r)throw new e("beneficiaryId must be a string");return r}function a(t){if(!t)throw new e("beneficiary parameter is required for the called function");if("object"!=typeof t)throw new e("beneficiary must be an object");r(t,n);const a=i({name:t.name,iban:t.iban,email:t.email,activityTag:t.activityTag,bic:t.bic});if(a.length>0)throw new e(a);return t}function o(r){if(!r)throw new e("beneficiaryIds parameter is required for the called function");if(!Array.isArray(r)||!r.every((e=>"string"==typeof e)))throw new e("beneficiaryIds must be an array of strings");return r}export{a as validateAddBeneficiaryParams,t as validateGetBeneficiaryParams,o as
|
|
1
|
+
import{InvalidParametersError as e}from"../errors/InvalidParametersError.js";import{validatePresenceOfRequiredParams as r,validateExpectedStringValues as i}from"../validation/input-param-validation.js";const n=[{name:"name"},{name:"iban"}];function t(r){if(!r)throw new e("beneficiaryId parameter is required for the called function");if(r&&"string"!=typeof r)throw new e("beneficiaryId must be a string");return r}function a(t){if(!t)throw new e("beneficiary parameter is required for the called function");if("object"!=typeof t)throw new e("beneficiary must be an object");r(t,n);const a=i({name:t.name,iban:t.iban,email:t.email,activityTag:t.activityTag,bic:t.bic});if(a.length>0)throw new e(a);return t}function o(r){if(!r)throw new e("beneficiaryIds parameter is required for the called function");if(!Array.isArray(r)||!r.every((e=>"string"==typeof e)))throw new e("beneficiaryIds must be an array of strings");return r}export{a as validateAddBeneficiaryParams,t as validateGetBeneficiaryParams,o as validateTrustBeneficiariesParams};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
const e={READY:"qonto.ready"},
|
|
1
|
+
const e={READY:"qonto.ready"},E={CARD_SEE:"card.see",CARD_SEE_DETAILS:"card.see-details",CARD_ORDER:"card.order",CARD_UNLOCK:"card.unlock",CARD_SHOW_PIN:"card.show.pin",CARD_SET_PIN:"card.set.pin",TRANSFER_SINGLE_CREATE:"transfer.single.create",BENEFICIARIES_TRUST:"beneficiary.trust"},_={PRODUCTION:"production",STAGING:"staging",LOCAL:"local"},n={MASTER:"master",SANDBOX:"sandbox",QA:"qa"},N={ATM:"atm",FALLBACK:"fallback",FEES:"fees",FINANCE:"finance",FOOD_AND_GROCERY:"food_and_grocery",GAS_STATION:"gas_station",HARDWARE_AND_EQUIPMENT:"hardware_and_equipment",HOTEL_AND_LODGING:"hotel_and_lodging",INSURANCE:"insurance",IT_AND_ELECTRONICS:"it_and_electronics",LEGAL_AND_ACCOUNTING:"legal_and_accounting",LOGISTICS:"logistics",MANUFACTURING:"manufacturing",MARKETING:"marketing",OFFICE_RENTAL:"office_rental",OFFICE_SUPPLY:"office_supply",ONLINE_SERVICE:"online_service",OTHER_EXPENSE:"other_expense",OTHER_INCOME:"other_income",OTHER_SERVICE:"other_service",PENDING:"pending",REFUND:"refund",RESTAURANT_AND_BAR:"restaurant_and_bar",SALES:"sales",SALARY:"salary",SUBSCRIPTION:"subscription",TAX:"tax",TRANSPORT:"transport",TREASURY_AND_INTERCO:"treasury_and_interco",UTILITY:"utility",VOUCHER:"voucher"},a={PENDING:"pending",VALIDATED:"validated",DECLINED:"declined"},A={EN:"en",FR:"fr",DE:"de",ES:"es",IT:"it",PT:"pt"},I={BENEFICIARY_BIC_INVALID:"beneficiary_bic_invalid",BENEFICIARY_IBAN_INVALID:"beneficiary_iban_invalid",BENEFICIARY_STATUS:"beneficiary_status",BENEFICIARY_NETWORK_RULES_ERROR:"beneficiary_network_rules_error",ORGANISATION_COMPLIANCE_REASONS:"organisation_compliance_reasons",DEBIT_ACCOUNT_INSUFFICIENT_FUNDS:"debit_account_insufficient_funds",QONTO_PROCESSING_FAILED:"qonto_processing_failed"},i={PENDING:"pending",PROCESSING:"processing",CANCELED:"canceled",DECLINED:"declined",SETTLED:"settled"},r={PASSKEY:"passkey",SMS_OTP:"sms-otp",PAIRED_DEVICE:"paired-device"};export{E as ACTIONS,N as ACTIVITY_TAGS,a as BENEFICIARY_STATUSES,n as BRANCHES,_ as ENVIRONMENTS,e as IFRAME_EVENTS,A as LOCALES,r as MFA_METHODS,I as TRANSFER_DECLINE_REASONS,i as TRANSFER_STATUSES};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{InvalidParametersError as e}from"../errors/InvalidParametersError.js";import{operationSettingsManager as t}from"../common/operation-settings/operation-settings.js";import{MFA_METHODS as o}from"../common/constants.js";function n(n){const r=n?.uiParentElementId||t.getUIParentElementId();if(!r)throw new e("operationSettings parameter must have a uiParentElementId for the called function.\nYou can pass it either to the initialize function or in a per function basis.");const i=n?.mfaPreference||t.getMFAPreference();if(i&&!Object.values(o).includes(i))throw new e("operationSettings.mfaPreference must be one of passkey, paired-device or sms-otp.");const a=n?.debugMode||t.getDebugMode();if(void 0!==a&&"boolean"!=typeof a)throw new e("operationSettings.debugMode must be a boolean.");return{uiParentElementId:r,mfaPreference:i,debugMode:a}}export{n as validateOperationSettingsParams};
|
|
1
|
+
import{InvalidParametersError as e}from"../errors/InvalidParametersError.js";import{operationSettingsManager as t}from"../common/operation-settings/operation-settings.js";import{MFA_METHODS as o}from"../common/constants.js";function n(n){const r=n?.uiParentElementId||t.getUIParentElementId();if(!r)throw new e("operationSettings parameter must have a uiParentElementId for the called function.\nYou can pass it either to the initialize function or in a per function basis.");const i=n?.mfaPreference||t.getMFAPreference();if(i&&!Object.values(o).includes(i))throw new e("operationSettings.mfaPreference must be one of passkey, paired-device or sms-otp.");const a=n?.debugMode||t.getDebugMode();if(void 0!==a&&"boolean"!=typeof a)throw new e("operationSettings.debugMode must be a boolean.");return{uiParentElementId:r,mfaPreference:i,debugMode:a,...n}}export{n as validateOperationSettingsParams};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"operation-settings-validation.d.ts","sourceRoot":"","sources":["../../src/validation/operation-settings-validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qDAAqD,CAAC;AAGrF;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;OAIG;IACH,aAAa,CAAC,EAAE,SAAS,CAAC;IAC1B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,iBAAiB,GAAG,SAAS,GACpC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"operation-settings-validation.d.ts","sourceRoot":"","sources":["../../src/validation/operation-settings-validation.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qDAAqD,CAAC;AAGrF;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;OAGG;IACH,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B;;;;OAIG;IACH,aAAa,CAAC,EAAE,SAAS,CAAC;IAC1B;;;;;OAKG;IACH,SAAS,CAAC,EAAE,OAAO,CAAC;IACpB;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB;;;;;OAKG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,wBAAgB,+BAA+B,CAC7C,MAAM,EAAE,iBAAiB,GAAG,SAAS,GACpC,iBAAiB,CA+BnB"}
|