@antom-tech/node 0.0.0-stage → 0.1.2-beta.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/LEGAL.md +7 -0
- package/README.md +227 -2
- package/dist/cjs/amount-rules-data.js +1 -0
- package/dist/cjs/amount.d.ts +34 -0
- package/dist/cjs/amount.js +165 -0
- package/dist/cjs/client.d.ts +14 -0
- package/dist/cjs/client.js +164 -0
- package/dist/cjs/errors.d.ts +11 -0
- package/dist/cjs/errors.js +21 -0
- package/dist/cjs/generated/index.d.ts +344 -0
- package/dist/cjs/generated/index.js +2 -0
- package/dist/cjs/generated/model/authapplytoken.d.ts +2 -0
- package/dist/cjs/generated/model/authapplytoken.js +2 -0
- package/dist/cjs/generated/model/authconsult.d.ts +59 -0
- package/dist/cjs/generated/model/authconsult.js +2 -0
- package/dist/cjs/generated/model/billingsubscriptioncancel.d.ts +5 -0
- package/dist/cjs/generated/model/billingsubscriptioncancel.js +2 -0
- package/dist/cjs/generated/model/billingsubscriptioncreate.d.ts +5 -0
- package/dist/cjs/generated/model/billingsubscriptioncreate.js +2 -0
- package/dist/cjs/generated/model/billingsubscriptioninquiredetails.d.ts +17 -0
- package/dist/cjs/generated/model/billingsubscriptioninquiredetails.js +2 -0
- package/dist/cjs/generated/model/billingsubscriptioninquirelist.d.ts +24 -0
- package/dist/cjs/generated/model/billingsubscriptioninquirelist.js +2 -0
- package/dist/cjs/generated/model/billingsubscriptionupdate.d.ts +17 -0
- package/dist/cjs/generated/model/billingsubscriptionupdate.js +2 -0
- package/dist/cjs/generated/model/couponcreate.d.ts +22 -0
- package/dist/cjs/generated/model/couponcreate.js +2 -0
- package/dist/cjs/generated/model/couponinquiredetails.d.ts +13 -0
- package/dist/cjs/generated/model/couponinquiredetails.js +2 -0
- package/dist/cjs/generated/model/couponinquirelist.d.ts +13 -0
- package/dist/cjs/generated/model/couponinquirelist.js +2 -0
- package/dist/cjs/generated/model/creditnotecreate.d.ts +10 -0
- package/dist/cjs/generated/model/creditnotecreate.js +2 -0
- package/dist/cjs/generated/model/creditnoteinquirelist.d.ts +17 -0
- package/dist/cjs/generated/model/creditnoteinquirelist.js +2 -0
- package/dist/cjs/generated/model/customerinquirelist.d.ts +12 -0
- package/dist/cjs/generated/model/customerinquirelist.js +2 -0
- package/dist/cjs/generated/model/downloaddisputeevidence.d.ts +4 -0
- package/dist/cjs/generated/model/downloaddisputeevidence.js +2 -0
- package/dist/cjs/generated/model/inquireaccountinfo.d.ts +11 -0
- package/dist/cjs/generated/model/inquireaccountinfo.js +2 -0
- package/dist/cjs/generated/model/inquirecard.d.ts +10 -0
- package/dist/cjs/generated/model/inquirecard.js +2 -0
- package/dist/cjs/generated/model/inquirecardsensitiveinfo.d.ts +18 -0
- package/dist/cjs/generated/model/inquirecardsensitiveinfo.js +2 -0
- package/dist/cjs/generated/model/inquirecardtransactionevent.d.ts +4 -0
- package/dist/cjs/generated/model/inquirecardtransactionevent.js +2 -0
- package/dist/cjs/generated/model/inquirecardtransactionlifecycle.d.ts +17 -0
- package/dist/cjs/generated/model/inquirecardtransactionlifecycle.js +2 -0
- package/dist/cjs/generated/model/inquirecardtransactionlifecycledetail.d.ts +18 -0
- package/dist/cjs/generated/model/inquirecardtransactionlifecycledetail.js +2 -0
- package/dist/cjs/generated/model/inquireexchangerate.d.ts +14 -0
- package/dist/cjs/generated/model/inquireexchangerate.js +2 -0
- package/dist/cjs/generated/model/inquireholdlist.d.ts +11 -0
- package/dist/cjs/generated/model/inquireholdlist.js +2 -0
- package/dist/cjs/generated/model/inquirepaymentmethod.d.ts +19 -0
- package/dist/cjs/generated/model/inquirepaymentmethod.js +2 -0
- package/dist/cjs/generated/model/inquirepaymenttoken.d.ts +10 -0
- package/dist/cjs/generated/model/inquirepaymenttoken.js +2 -0
- package/dist/cjs/generated/model/inquirerulelist.d.ts +16 -0
- package/dist/cjs/generated/model/inquirerulelist.js +2 -0
- package/dist/cjs/generated/model/inquiresubscriptionpayment.d.ts +13 -0
- package/dist/cjs/generated/model/inquiresubscriptionpayment.js +2 -0
- package/dist/cjs/generated/model/inquiryrate.d.ts +11 -0
- package/dist/cjs/generated/model/inquiryrate.js +2 -0
- package/dist/cjs/generated/model/inquirystatement.d.ts +7 -0
- package/dist/cjs/generated/model/inquirystatement.js +2 -0
- package/dist/cjs/generated/model/inquirystatementlist.d.ts +5 -0
- package/dist/cjs/generated/model/inquirystatementlist.js +2 -0
- package/dist/cjs/generated/model/invoicecreate.d.ts +35 -0
- package/dist/cjs/generated/model/invoicecreate.js +2 -0
- package/dist/cjs/generated/model/invoiceinquiredetails.d.ts +26 -0
- package/dist/cjs/generated/model/invoiceinquiredetails.js +2 -0
- package/dist/cjs/generated/model/invoiceinquirelist.d.ts +23 -0
- package/dist/cjs/generated/model/invoiceinquirelist.js +2 -0
- package/dist/cjs/generated/model/invoiceupdate.d.ts +5 -0
- package/dist/cjs/generated/model/invoiceupdate.js +2 -0
- package/dist/cjs/generated/model/pay.d.ts +24 -0
- package/dist/cjs/generated/model/pay.js +2 -0
- package/dist/cjs/generated/model/payconsult.d.ts +103 -0
- package/dist/cjs/generated/model/payconsult.js +2 -0
- package/dist/cjs/generated/model/paymentsession.d.ts +91 -0
- package/dist/cjs/generated/model/paymentsession.js +2 -0
- package/dist/cjs/generated/model/payquery.d.ts +43 -0
- package/dist/cjs/generated/model/payquery.js +2 -0
- package/dist/cjs/generated/model/productinquirelist.d.ts +15 -0
- package/dist/cjs/generated/model/productinquirelist.js +2 -0
- package/dist/cjs/generated/model/promotioncodecreate.d.ts +5 -0
- package/dist/cjs/generated/model/promotioncodecreate.js +2 -0
- package/dist/cjs/generated/model/promotioncodeinquiredetails.d.ts +5 -0
- package/dist/cjs/generated/model/promotioncodeinquiredetails.js +2 -0
- package/dist/cjs/generated/model/promotioncodeinquirelist.d.ts +10 -0
- package/dist/cjs/generated/model/promotioncodeinquirelist.js +2 -0
- package/dist/cjs/generated/model/receiptinquiredetails.d.ts +19 -0
- package/dist/cjs/generated/model/receiptinquiredetails.js +2 -0
- package/dist/cjs/generated/model/receiptinquirelist.d.ts +44 -0
- package/dist/cjs/generated/model/receiptinquirelist.js +2 -0
- package/dist/cjs/generated/model/refund.d.ts +14 -0
- package/dist/cjs/generated/model/refund.js +2 -0
- package/dist/cjs/generated/model/register.d.ts +104 -0
- package/dist/cjs/generated/model/register.js +2 -0
- package/dist/cjs/generated/model/settle.d.ts +8 -0
- package/dist/cjs/generated/model/settle.js +2 -0
- package/dist/cjs/generated/model/submitattachment.d.ts +2 -0
- package/dist/cjs/generated/model/submitattachment.js +2 -0
- package/dist/cjs/generated/model/subscriptioncreate.d.ts +8 -0
- package/dist/cjs/generated/model/subscriptioncreate.js +2 -0
- package/dist/cjs/generated/model/subscriptionupdate.d.ts +6 -0
- package/dist/cjs/generated/model/subscriptionupdate.js +2 -0
- package/dist/cjs/generated/model/supplyevidence.d.ts +7 -0
- package/dist/cjs/generated/model/supplyevidence.js +2 -0
- package/dist/cjs/generated/model/taxcalculate.d.ts +50 -0
- package/dist/cjs/generated/model/taxcalculate.js +2 -0
- package/dist/cjs/generated/model/taxinquireregistrationlist.d.ts +12 -0
- package/dist/cjs/generated/model/taxinquireregistrationlist.js +2 -0
- package/dist/cjs/generated/model/taxinquiretransactionlist.d.ts +14 -0
- package/dist/cjs/generated/model/taxinquiretransactionlist.js +2 -0
- package/dist/cjs/generated/model/vaultsfetchnonce.d.ts +9 -0
- package/dist/cjs/generated/model/vaultsfetchnonce.js +2 -0
- package/dist/cjs/generated/model/verifyandcompletepayment.d.ts +5 -0
- package/dist/cjs/generated/model/verifyandcompletepayment.js +2 -0
- package/dist/cjs/generated/resource/aba.d.ts +450 -0
- package/dist/cjs/generated/resource/aba.js +78 -0
- package/dist/cjs/generated/resource/agentic.d.ts +89 -0
- package/dist/cjs/generated/resource/agentic.js +24 -0
- package/dist/cjs/generated/resource/auth.d.ts +81 -0
- package/dist/cjs/generated/resource/auth.js +21 -0
- package/dist/cjs/generated/resource/billing.d.ts +1656 -0
- package/dist/cjs/generated/resource/billing.js +217 -0
- package/dist/cjs/generated/resource/dispute.d.ts +66 -0
- package/dist/cjs/generated/resource/dispute.js +24 -0
- package/dist/cjs/generated/resource/index.d.ts +315 -0
- package/dist/cjs/generated/resource/index.js +319 -0
- package/dist/cjs/generated/resource/marketplace.d.ts +117 -0
- package/dist/cjs/generated/resource/marketplace.js +33 -0
- package/dist/cjs/generated/resource/notification.d.ts +37 -0
- package/dist/cjs/generated/resource/notification.js +18 -0
- package/dist/cjs/generated/resource/pay.d.ts +674 -0
- package/dist/cjs/generated/resource/pay.js +90 -0
- package/dist/cjs/generated/resource/subscription.d.ts +171 -0
- package/dist/cjs/generated/resource/subscription.js +36 -0
- package/dist/cjs/generated/share.d.ts +1159 -0
- package/dist/cjs/generated/share.js +2 -0
- package/dist/cjs/index.d.ts +12 -0
- package/dist/cjs/index.js +23 -0
- package/dist/cjs/resources.d.ts +42 -0
- package/dist/cjs/resources.js +42 -0
- package/dist/cjs/signature.d.ts +24 -0
- package/dist/cjs/signature.js +117 -0
- package/dist/cjs/special.d.ts +78 -0
- package/dist/cjs/special.js +288 -0
- package/dist/cjs/types.d.ts +60 -0
- package/dist/cjs/types.js +29 -0
- package/dist/esm/amount-rules-data.js +1 -0
- package/dist/esm/amount.js +158 -0
- package/dist/esm/client.js +160 -0
- package/dist/esm/errors.js +17 -0
- package/dist/esm/generated/index.js +1 -0
- package/dist/esm/generated/model/authapplytoken.js +1 -0
- package/dist/esm/generated/model/authconsult.js +1 -0
- package/dist/esm/generated/model/billingsubscriptioncancel.js +1 -0
- package/dist/esm/generated/model/billingsubscriptioncreate.js +1 -0
- package/dist/esm/generated/model/billingsubscriptioninquiredetails.js +1 -0
- package/dist/esm/generated/model/billingsubscriptioninquirelist.js +1 -0
- package/dist/esm/generated/model/billingsubscriptionupdate.js +1 -0
- package/dist/esm/generated/model/couponcreate.js +1 -0
- package/dist/esm/generated/model/couponinquiredetails.js +1 -0
- package/dist/esm/generated/model/couponinquirelist.js +1 -0
- package/dist/esm/generated/model/creditnotecreate.js +1 -0
- package/dist/esm/generated/model/creditnoteinquirelist.js +1 -0
- package/dist/esm/generated/model/customerinquirelist.js +1 -0
- package/dist/esm/generated/model/downloaddisputeevidence.js +1 -0
- package/dist/esm/generated/model/inquireaccountinfo.js +1 -0
- package/dist/esm/generated/model/inquirecard.js +1 -0
- package/dist/esm/generated/model/inquirecardsensitiveinfo.js +1 -0
- package/dist/esm/generated/model/inquirecardtransactionevent.js +1 -0
- package/dist/esm/generated/model/inquirecardtransactionlifecycle.js +1 -0
- package/dist/esm/generated/model/inquirecardtransactionlifecycledetail.js +1 -0
- package/dist/esm/generated/model/inquireexchangerate.js +1 -0
- package/dist/esm/generated/model/inquireholdlist.js +1 -0
- package/dist/esm/generated/model/inquirepaymentmethod.js +1 -0
- package/dist/esm/generated/model/inquirepaymenttoken.js +1 -0
- package/dist/esm/generated/model/inquirerulelist.js +1 -0
- package/dist/esm/generated/model/inquiresubscriptionpayment.js +1 -0
- package/dist/esm/generated/model/inquiryrate.js +1 -0
- package/dist/esm/generated/model/inquirystatement.js +1 -0
- package/dist/esm/generated/model/inquirystatementlist.js +1 -0
- package/dist/esm/generated/model/invoicecreate.js +1 -0
- package/dist/esm/generated/model/invoiceinquiredetails.js +1 -0
- package/dist/esm/generated/model/invoiceinquirelist.js +1 -0
- package/dist/esm/generated/model/invoiceupdate.js +1 -0
- package/dist/esm/generated/model/pay.js +1 -0
- package/dist/esm/generated/model/payconsult.js +1 -0
- package/dist/esm/generated/model/paymentsession.js +1 -0
- package/dist/esm/generated/model/payquery.js +1 -0
- package/dist/esm/generated/model/productinquirelist.js +1 -0
- package/dist/esm/generated/model/promotioncodecreate.js +1 -0
- package/dist/esm/generated/model/promotioncodeinquiredetails.js +1 -0
- package/dist/esm/generated/model/promotioncodeinquirelist.js +1 -0
- package/dist/esm/generated/model/receiptinquiredetails.js +1 -0
- package/dist/esm/generated/model/receiptinquirelist.js +1 -0
- package/dist/esm/generated/model/refund.js +1 -0
- package/dist/esm/generated/model/register.js +1 -0
- package/dist/esm/generated/model/settle.js +1 -0
- package/dist/esm/generated/model/submitattachment.js +1 -0
- package/dist/esm/generated/model/subscriptioncreate.js +1 -0
- package/dist/esm/generated/model/subscriptionupdate.js +1 -0
- package/dist/esm/generated/model/supplyevidence.js +1 -0
- package/dist/esm/generated/model/taxcalculate.js +1 -0
- package/dist/esm/generated/model/taxinquireregistrationlist.js +1 -0
- package/dist/esm/generated/model/taxinquiretransactionlist.js +1 -0
- package/dist/esm/generated/model/vaultsfetchnonce.js +1 -0
- package/dist/esm/generated/model/verifyandcompletepayment.js +1 -0
- package/dist/esm/generated/resource/aba.js +74 -0
- package/dist/esm/generated/resource/agentic.js +20 -0
- package/dist/esm/generated/resource/auth.js +17 -0
- package/dist/esm/generated/resource/billing.js +212 -0
- package/dist/esm/generated/resource/dispute.js +20 -0
- package/dist/esm/generated/resource/index.js +315 -0
- package/dist/esm/generated/resource/marketplace.js +29 -0
- package/dist/esm/generated/resource/notification.js +14 -0
- package/dist/esm/generated/resource/pay.js +86 -0
- package/dist/esm/generated/resource/subscription.js +32 -0
- package/dist/esm/generated/share.js +1 -0
- package/dist/esm/index.d.ts +171 -0
- package/dist/esm/index.js +7 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/resources.js +38 -0
- package/dist/esm/signature.js +112 -0
- package/dist/esm/special.js +284 -0
- package/dist/esm/types.js +24 -0
- package/package.json +49 -4
- package/resources/amount-currency-rules.json +44 -0
|
@@ -0,0 +1,288 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.uploadMeterEvents = uploadMeterEvents;
|
|
4
|
+
exports.uploadProductImage = uploadProductImage;
|
|
5
|
+
/** Dedicated transports for APIs whose wire format differs from signed JSON requests. */
|
|
6
|
+
const node_crypto_1 = require("node:crypto");
|
|
7
|
+
const node_http2_1 = require("node:http2");
|
|
8
|
+
const errors_js_1 = require("./errors.js");
|
|
9
|
+
const signature_js_1 = require("./signature.js");
|
|
10
|
+
const types_js_1 = require("./types.js");
|
|
11
|
+
const METER_PATH = '/ams/api/v1/meter/uploadEvent';
|
|
12
|
+
const IMAGE_PATH = '/ams/api/v1/billing/product/uploadImage';
|
|
13
|
+
const MAX_IMAGE_BYTES = 2 * 1024 * 1024;
|
|
14
|
+
const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;
|
|
15
|
+
const UPLOAD_HOSTS = {
|
|
16
|
+
'open-sea-global.alipay.com': 'open-big-sea.alipay.com',
|
|
17
|
+
'open-sea.alipay.com': 'open-big-sea.alipay.com',
|
|
18
|
+
'open-na-global.alipay.com': 'open-big-na.alipay.com',
|
|
19
|
+
'open-na.alipay.com': 'open-big-na.alipay.com',
|
|
20
|
+
'open-de-global.alipay.com': 'open-big-de-global.alipay.com',
|
|
21
|
+
};
|
|
22
|
+
function httpsOrigin(value) {
|
|
23
|
+
let url;
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(value);
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'Gateway must be an HTTPS origin.');
|
|
29
|
+
}
|
|
30
|
+
if (url.protocol !== 'https:' || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
|
|
31
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'Gateway must be an HTTPS origin without credentials or a path.');
|
|
32
|
+
}
|
|
33
|
+
return url;
|
|
34
|
+
}
|
|
35
|
+
function cancellation(timeout = 30000, signal) {
|
|
36
|
+
if (!Number.isInteger(timeout) || timeout <= 0 || timeout > 2147483647) {
|
|
37
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'timeout must be a positive 32-bit integer in milliseconds.');
|
|
38
|
+
}
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
const timer = setTimeout(() => controller.abort(new DOMException('Request timed out.', 'TimeoutError')), timeout);
|
|
41
|
+
return {
|
|
42
|
+
signal: signal ? AbortSignal.any([controller.signal, signal]) : controller.signal,
|
|
43
|
+
dispose: () => clearTimeout(timer),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
function abortError(signal) {
|
|
47
|
+
const timeout = signal.reason instanceof Error && signal.reason.name === 'TimeoutError';
|
|
48
|
+
return new errors_js_1.AlipaySdkError(timeout ? 'TIMEOUT' : 'ABORTED', timeout ? 'Request timed out.' : 'Request was cancelled.');
|
|
49
|
+
}
|
|
50
|
+
function parseResponse(text) {
|
|
51
|
+
let value;
|
|
52
|
+
try {
|
|
53
|
+
value = JSON.parse(text);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
throw new errors_js_1.AlipaySdkError('INVALID_RESPONSE', 'Response is not valid JSON.');
|
|
57
|
+
}
|
|
58
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || !('result' in value) ||
|
|
59
|
+
!value.result || typeof value.result !== 'object' || Array.isArray(value.result)) {
|
|
60
|
+
throw new errors_js_1.AlipaySdkError('INVALID_RESPONSE', 'Response must contain a result object.');
|
|
61
|
+
}
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Upload meter events once over HTTP/2 using a session from the createSession API.
|
|
66
|
+
* @param options HTTPS gateway, session ID, cancellation, and optional transport adapter.
|
|
67
|
+
* @param body Event batches sent without RSA signing or sandbox path rewriting.
|
|
68
|
+
* @returns The unmodified result and any server retry guidance.
|
|
69
|
+
*/
|
|
70
|
+
async function uploadMeterEvents(options, body) {
|
|
71
|
+
const origin = httpsOrigin(options.gatewayUrl).origin;
|
|
72
|
+
if (typeof options.sessionId !== 'string' || !options.sessionId.trim() || /[\r\n]/.test(options.sessionId)) {
|
|
73
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'sessionId must be a nonempty header value.');
|
|
74
|
+
}
|
|
75
|
+
if (!body || !Array.isArray(body.meters)) {
|
|
76
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'meters must be an array.');
|
|
77
|
+
}
|
|
78
|
+
let requestBody;
|
|
79
|
+
try {
|
|
80
|
+
requestBody = JSON.stringify(body);
|
|
81
|
+
if (typeof requestBody !== 'string' || !requestBody.startsWith('{'))
|
|
82
|
+
throw new Error();
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'Meter events must be JSON serializable.');
|
|
86
|
+
}
|
|
87
|
+
const abort = cancellation(options.timeout, options.signal);
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
let session;
|
|
90
|
+
let stream;
|
|
91
|
+
let settled = false;
|
|
92
|
+
let status = 0;
|
|
93
|
+
let size = 0;
|
|
94
|
+
const chunks = [];
|
|
95
|
+
const finish = (error, response) => {
|
|
96
|
+
if (settled)
|
|
97
|
+
return;
|
|
98
|
+
settled = true;
|
|
99
|
+
abort.dispose();
|
|
100
|
+
abort.signal.removeEventListener('abort', onAbort);
|
|
101
|
+
if (error) {
|
|
102
|
+
stream?.close(node_http2_1.constants.NGHTTP2_CANCEL);
|
|
103
|
+
session?.destroy();
|
|
104
|
+
reject(error);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
session?.close();
|
|
108
|
+
resolve(response);
|
|
109
|
+
}
|
|
110
|
+
};
|
|
111
|
+
const onAbort = () => finish(abortError(abort.signal));
|
|
112
|
+
abort.signal.addEventListener('abort', onAbort, { once: true });
|
|
113
|
+
if (abort.signal.aborted) {
|
|
114
|
+
onAbort();
|
|
115
|
+
return;
|
|
116
|
+
}
|
|
117
|
+
try {
|
|
118
|
+
session = (options.connect ?? node_http2_1.connect)(origin);
|
|
119
|
+
session.once('error', () => finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'HTTP/2 connection failed.')));
|
|
120
|
+
session.once('close', () => {
|
|
121
|
+
if (!settled)
|
|
122
|
+
finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'HTTP/2 connection closed before a response.'));
|
|
123
|
+
});
|
|
124
|
+
session.once('connect', () => {
|
|
125
|
+
if (settled)
|
|
126
|
+
return;
|
|
127
|
+
if (session.alpnProtocol !== 'h2') {
|
|
128
|
+
finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'This API requires HTTP/2.'));
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
try {
|
|
132
|
+
stream = session.request({
|
|
133
|
+
':method': 'POST', ':path': METER_PATH,
|
|
134
|
+
'x-session-id': options.sessionId,
|
|
135
|
+
'content-type': 'application/json; charset=UTF-8',
|
|
136
|
+
accept: 'application/json', 'user-agent': types_js_1.SDK_USER_AGENT,
|
|
137
|
+
});
|
|
138
|
+
stream.on('response', headers => { status = Number(headers[':status']); });
|
|
139
|
+
stream.on('data', (chunk) => {
|
|
140
|
+
size += chunk.length;
|
|
141
|
+
if (size > MAX_RESPONSE_BYTES) {
|
|
142
|
+
finish(new errors_js_1.AlipaySdkError('INVALID_RESPONSE', 'HTTP/2 response exceeds the size limit.'));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
chunks.push(Buffer.from(chunk));
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
stream.once('error', () => finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'HTTP/2 request failed.')));
|
|
149
|
+
stream.once('aborted', () => finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'HTTP/2 stream was aborted.')));
|
|
150
|
+
stream.once('close', () => {
|
|
151
|
+
if (!settled)
|
|
152
|
+
finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'HTTP/2 stream closed before a response.'));
|
|
153
|
+
});
|
|
154
|
+
stream.once('end', () => {
|
|
155
|
+
if (settled)
|
|
156
|
+
return;
|
|
157
|
+
if (status !== 200) {
|
|
158
|
+
finish(new errors_js_1.AlipaySdkError('HTTP_ERROR', 'HTTP/2 request returned a non-200 status.', status));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
try {
|
|
162
|
+
finish(undefined, parseResponse(Buffer.concat(chunks).toString('utf8')));
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
finish(error);
|
|
166
|
+
}
|
|
167
|
+
});
|
|
168
|
+
stream.end(requestBody);
|
|
169
|
+
}
|
|
170
|
+
catch {
|
|
171
|
+
finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'Unable to start the HTTP/2 request.'));
|
|
172
|
+
}
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
finish(new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'Unable to connect using HTTP/2.'));
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
function uploadOrigin(options) {
|
|
181
|
+
if (options.uploadGatewayUrl)
|
|
182
|
+
return httpsOrigin(options.uploadGatewayUrl).origin;
|
|
183
|
+
const gateway = httpsOrigin(options.gatewayUrl);
|
|
184
|
+
const host = UPLOAD_HOSTS[gateway.hostname];
|
|
185
|
+
if (!host || gateway.port) {
|
|
186
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'No upload gateway mapping; configure uploadGatewayUrl explicitly.');
|
|
187
|
+
}
|
|
188
|
+
return `https://${host}`;
|
|
189
|
+
}
|
|
190
|
+
function multipart(request, body) {
|
|
191
|
+
const boundary = `----AntomBoundary${(0, node_crypto_1.randomUUID)().replaceAll('-', '')}`;
|
|
192
|
+
const filename = request.filename.replaceAll('\\', '/').split('/').at(-1).replace(/["\x00-\x1f\x7f]/g, '_');
|
|
193
|
+
if (!filename.trim())
|
|
194
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'The filename must contain a basename.');
|
|
195
|
+
const mimeTypes = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', gif: 'image/gif', webp: 'image/webp' };
|
|
196
|
+
const contentType = request.contentType ?? mimeTypes[filename.split('.').at(-1).toLowerCase()] ?? 'application/octet-stream';
|
|
197
|
+
if (!/^[\w!#$&^.+-]+\/[\w!#$&^.+-]+$/.test(contentType)) {
|
|
198
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'contentType must be a MIME type without parameters.');
|
|
199
|
+
}
|
|
200
|
+
const chunks = [Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="body"\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n${body}\r\n`)];
|
|
201
|
+
// Both file aliases are required for compatibility with the existing multipart SDKs.
|
|
202
|
+
for (const name of ['file', 'imageFile']) {
|
|
203
|
+
chunks.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="${name}"; filename="${filename}"\r\nContent-Type: ${contentType}\r\nContent-Transfer-Encoding: binary\r\n\r\n`), Buffer.from(request.file), Buffer.from('\r\n'));
|
|
204
|
+
}
|
|
205
|
+
chunks.push(Buffer.from(`--${boundary}--\r\n`));
|
|
206
|
+
return { contentType: `multipart/form-data; boundary=${boundary}`, payload: Buffer.concat(chunks) };
|
|
207
|
+
}
|
|
208
|
+
/**
|
|
209
|
+
* Upload a product image once using the signed JSON body part and duplicate binary parts.
|
|
210
|
+
* @param options RSA credentials, regional gateway, and optional upload gateway override.
|
|
211
|
+
* @param request Product ID, image bytes, filename, and optional MIME type.
|
|
212
|
+
* @returns The verified upload result, including the image URL when provided by Antom.
|
|
213
|
+
*/
|
|
214
|
+
async function uploadProductImage(options, request) {
|
|
215
|
+
if (!request || typeof request.productId !== 'string' || !request.productId.trim() || request.productId.length > 64 ||
|
|
216
|
+
!(request.file instanceof Uint8Array) || request.file.byteLength === 0 || request.file.byteLength > MAX_IMAGE_BYTES ||
|
|
217
|
+
typeof request.filename !== 'string' || !request.filename.trim()) {
|
|
218
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'A product ID of at most 64 characters, filename, and image of 1 to 2097152 bytes are required.');
|
|
219
|
+
}
|
|
220
|
+
if (typeof options.clientId !== 'string' || !/^[\x21-\x7e]+$/.test(options.clientId) ||
|
|
221
|
+
!options.merchantPrivateKey || !options.alipayPublicKey ||
|
|
222
|
+
(options.agentToken && !/^[\x20-\x7e]+$/.test(options.agentToken))) {
|
|
223
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'Valid client identity, merchant/Antom keys, and agent token are required.');
|
|
224
|
+
}
|
|
225
|
+
const origin = uploadOrigin(options);
|
|
226
|
+
const path = options.clientId.startsWith('SANDBOX_') ? IMAGE_PATH.replace('/ams/api', '/ams/sandbox/api') : IMAGE_PATH;
|
|
227
|
+
const body = JSON.stringify({ productId: request.productId, fileSha256: (0, node_crypto_1.createHash)('sha256').update(request.file).digest('hex') });
|
|
228
|
+
const time = new Date().toISOString();
|
|
229
|
+
const payload = multipart(request, body);
|
|
230
|
+
const headers = new Headers({
|
|
231
|
+
'Content-Type': payload.contentType,
|
|
232
|
+
Accept: 'application/json',
|
|
233
|
+
'User-Agent': types_js_1.SDK_USER_AGENT,
|
|
234
|
+
'Client-Id': options.clientId,
|
|
235
|
+
'Request-Time': time,
|
|
236
|
+
Signature: (0, signature_js_1.signRequest)({ method: 'POST', path, clientId: options.clientId, time, body }, options.merchantPrivateKey, options.keyVersion),
|
|
237
|
+
});
|
|
238
|
+
if (options.agentToken)
|
|
239
|
+
headers.set('Agent-Token', options.agentToken);
|
|
240
|
+
const abort = cancellation(options.timeout, options.signal);
|
|
241
|
+
let cancel;
|
|
242
|
+
const cancelled = new Promise((_resolve, reject) => {
|
|
243
|
+
cancel = () => reject(abortError(abort.signal));
|
|
244
|
+
abort.signal.addEventListener('abort', cancel, { once: true });
|
|
245
|
+
});
|
|
246
|
+
try {
|
|
247
|
+
if (abort.signal.aborted)
|
|
248
|
+
throw abortError(abort.signal);
|
|
249
|
+
const send = async () => {
|
|
250
|
+
const response = await (options.fetch ?? globalThis.fetch)(`${origin}${path}`, {
|
|
251
|
+
method: 'POST', headers, body: new Uint8Array(payload.payload), signal: abort.signal, redirect: 'error',
|
|
252
|
+
});
|
|
253
|
+
if (response.status !== 200) {
|
|
254
|
+
await response.body?.cancel();
|
|
255
|
+
throw new errors_js_1.AlipaySdkError('HTTP_ERROR', 'Image upload returned a non-200 status.', response.status);
|
|
256
|
+
}
|
|
257
|
+
const rawBody = await response.text();
|
|
258
|
+
const signature = response.headers.get('Signature');
|
|
259
|
+
const responseTime = response.headers.get('Response-Time');
|
|
260
|
+
const clientId = response.headers.get('Client-Id');
|
|
261
|
+
if (((signature !== null || responseTime !== null) && (!signature || !responseTime)) ||
|
|
262
|
+
(clientId !== null && clientId !== options.clientId)) {
|
|
263
|
+
throw new errors_js_1.AlipaySdkError('SIGNATURE_ERROR', 'Image response signature headers are incomplete or inconsistent.');
|
|
264
|
+
}
|
|
265
|
+
if (signature && responseTime && !(0, signature_js_1.verifySignature)({ method: 'POST', path, clientId: options.clientId, time: responseTime, body: rawBody }, signature, options.alipayPublicKey)) {
|
|
266
|
+
throw new errors_js_1.AlipaySdkError('SIGNATURE_ERROR', 'Image response signature verification failed.');
|
|
267
|
+
}
|
|
268
|
+
const result = parseResponse(rawBody);
|
|
269
|
+
if (!signature && result.result.resultStatus !== 'F') {
|
|
270
|
+
throw new errors_js_1.AlipaySdkError('SIGNATURE_ERROR', 'An unsigned image response must be a failure.');
|
|
271
|
+
}
|
|
272
|
+
return result;
|
|
273
|
+
};
|
|
274
|
+
return await Promise.race([send(), cancelled]);
|
|
275
|
+
}
|
|
276
|
+
catch (error) {
|
|
277
|
+
if (error instanceof errors_js_1.AlipaySdkError)
|
|
278
|
+
throw error;
|
|
279
|
+
if (abort.signal.aborted)
|
|
280
|
+
throw abortError(abort.signal);
|
|
281
|
+
throw new errors_js_1.AlipaySdkError('TRANSPORT_ERROR', 'Image upload transport failed.');
|
|
282
|
+
}
|
|
283
|
+
finally {
|
|
284
|
+
abort.dispose();
|
|
285
|
+
if (cancel)
|
|
286
|
+
abort.signal.removeEventListener('abort', cancel);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/** SDK identification shared by JSON and special transports. */
|
|
2
|
+
export declare const SDK_USER_AGENT = "antomsdk-nodejs/0.1.0";
|
|
3
|
+
declare const OPERATION_TYPES: unique symbol;
|
|
4
|
+
/** A generated POST operation carrying its request and response types. */
|
|
5
|
+
export interface Operation<TRequest, TResponse> {
|
|
6
|
+
readonly method: 'POST';
|
|
7
|
+
readonly path: string;
|
|
8
|
+
readonly [OPERATION_TYPES]?: (request: TRequest) => TResponse;
|
|
9
|
+
}
|
|
10
|
+
/** Client credentials and transport configuration, supplied by the application. */
|
|
11
|
+
export interface AntomClientOptions {
|
|
12
|
+
gatewayUrl: string;
|
|
13
|
+
clientId: string;
|
|
14
|
+
merchantPrivateKey: string;
|
|
15
|
+
alipayPublicKey: string;
|
|
16
|
+
keyVersion?: string;
|
|
17
|
+
agentToken?: string;
|
|
18
|
+
/** Timeout in milliseconds; defaults to 30000. */
|
|
19
|
+
timeout?: number;
|
|
20
|
+
fetch?: typeof globalThis.fetch;
|
|
21
|
+
}
|
|
22
|
+
/** Per-request cancellation, deadline, and additional non-protocol headers. */
|
|
23
|
+
export interface RequestOptions {
|
|
24
|
+
signal?: AbortSignal;
|
|
25
|
+
/** Timeout in milliseconds, overriding the client's default. */
|
|
26
|
+
timeout?: number;
|
|
27
|
+
headers?: HeadersInit;
|
|
28
|
+
}
|
|
29
|
+
/** A typed JSON operation executor shared by generated business resources. */
|
|
30
|
+
export interface OperationExecutor {
|
|
31
|
+
<TRequest, TResponse>(operation: Operation<TRequest, TResponse>, params: TRequest, options?: RequestOptions): Promise<TResponse>;
|
|
32
|
+
}
|
|
33
|
+
/** The exact bytes and routing information used by the Antom signature protocol. */
|
|
34
|
+
export interface SignedMessage {
|
|
35
|
+
method: string;
|
|
36
|
+
path: string;
|
|
37
|
+
clientId: string;
|
|
38
|
+
time: string;
|
|
39
|
+
body: string;
|
|
40
|
+
}
|
|
41
|
+
/** Raw notification data; body must be captured before JSON parsing. */
|
|
42
|
+
export interface NotificationVerificationOptions {
|
|
43
|
+
path: string;
|
|
44
|
+
body: string;
|
|
45
|
+
headers: HeadersInit;
|
|
46
|
+
clientId: string;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Reject ambiguous or cross-origin paths before signing or sending credentials.
|
|
50
|
+
* @param path Absolute API path without an origin, query, or fragment.
|
|
51
|
+
* @internal
|
|
52
|
+
*/
|
|
53
|
+
export declare function assertRequestPath(path: string): void;
|
|
54
|
+
/**
|
|
55
|
+
* Bind an API path to generated request and response types.
|
|
56
|
+
* @param path Absolute API path from the OpenAPI metadata.
|
|
57
|
+
* @returns An immutable descriptor used by the client's private JSON transport.
|
|
58
|
+
*/
|
|
59
|
+
export declare function defineOperation<TRequest, TResponse>(path: string): Operation<TRequest, TResponse>;
|
|
60
|
+
export {};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SDK_USER_AGENT = void 0;
|
|
4
|
+
exports.assertRequestPath = assertRequestPath;
|
|
5
|
+
exports.defineOperation = defineOperation;
|
|
6
|
+
/** Client configuration and transport contracts shared by generated operations and the signed client. */
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
/** SDK identification shared by JSON and special transports. */
|
|
9
|
+
exports.SDK_USER_AGENT = 'antomsdk-nodejs/0.1.0';
|
|
10
|
+
/**
|
|
11
|
+
* Reject ambiguous or cross-origin paths before signing or sending credentials.
|
|
12
|
+
* @param path Absolute API path without an origin, query, or fragment.
|
|
13
|
+
* @internal
|
|
14
|
+
*/
|
|
15
|
+
function assertRequestPath(path) {
|
|
16
|
+
if (typeof path !== 'string' || !/^\/[A-Za-z0-9/_.~-]+$/.test(path)
|
|
17
|
+
|| path.startsWith('//') || new URL(path, 'https://sdk.invalid').pathname !== path) {
|
|
18
|
+
throw new errors_js_1.AlipaySdkError('INVALID_ARGUMENT', 'An unambiguous absolute API path is required.');
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Bind an API path to generated request and response types.
|
|
23
|
+
* @param path Absolute API path from the OpenAPI metadata.
|
|
24
|
+
* @returns An immutable descriptor used by the client's private JSON transport.
|
|
25
|
+
*/
|
|
26
|
+
function defineOperation(path) {
|
|
27
|
+
assertRequestPath(path);
|
|
28
|
+
return Object.freeze({ method: 'POST', path });
|
|
29
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const amountRulesJson = "{\n \"schemaVersion\": 1,\n \"dataVersion\": \"2026-09-01\",\n \"antom\": {\n \"source\": \"Antom Amount object usage rules\",\n \"sourceUrl\": \"https://docs.antom.com/ac/ref/cc\",\n \"pageUpdatedAt\": \"2026-08-03\"\n },\n \"iso4217Reference\": {\n \"effectiveDate\": \"2026-01-01\",\n \"source\": \"ISO 4217 List One\",\n \"sourceUrl\": \"https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml\",\n \"sourceSha256\": \"838dfb991648cf36df939edd5fe3811737962b75a32252847d239cedd1e291c9\"\n },\n \"currencies\": {\n \"AUD\": { \"minorUnit\": 2 },\n \"BDT\": { \"minorUnit\": 2 },\n \"BRL\": { \"minorUnit\": 2 },\n \"CAD\": { \"minorUnit\": 2 },\n \"CLP\": { \"minorUnit\": 0 },\n \"CNY\": { \"minorUnit\": 2 },\n \"EUR\": { \"minorUnit\": 2 },\n \"GBP\": { \"minorUnit\": 2 },\n \"HKD\": { \"minorUnit\": 2 },\n \"IDR\": { \"minorUnit\": 2 },\n \"JPY\": { \"minorUnit\": 0 },\n \"KRW\": { \"minorUnit\": 0 },\n \"MXN\": { \"minorUnit\": 2 },\n \"MYR\": { \"minorUnit\": 2 },\n \"NZD\": { \"minorUnit\": 2 },\n \"PEN\": { \"minorUnit\": 2 },\n \"PHP\": { \"minorUnit\": 2 },\n \"PKR\": { \"minorUnit\": 2 },\n \"PLN\": { \"minorUnit\": 2 },\n \"SGD\": { \"minorUnit\": 2 },\n \"THB\": { \"minorUnit\": 2 },\n \"TWD\": { \"minorUnit\": 2 },\n \"USD\": { \"minorUnit\": 2 },\n \"VND\": { \"minorUnit\": 0 }\n },\n \"antomConstraints\": {\n \"IDR\": { \"minorValueMultiple\": \"100\" }\n }\n}\n";
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
// Generated by ACS2 SKILL - Ant International Security
|
|
2
|
+
/** Lossless string-based amounts using the shared Antom currency rules. */
|
|
3
|
+
import { amountRulesJson } from './amount-rules-data.js';
|
|
4
|
+
/** Reports a validation category without including potentially sensitive input values. */
|
|
5
|
+
export class AmountError extends Error {
|
|
6
|
+
code;
|
|
7
|
+
/** @param code The stable validation category. */
|
|
8
|
+
constructor(code) {
|
|
9
|
+
super(code);
|
|
10
|
+
this.code = code;
|
|
11
|
+
this.name = 'AmountError';
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
let cachedRules;
|
|
15
|
+
let rulesFailure;
|
|
16
|
+
function object(value) {
|
|
17
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
18
|
+
throw new Error('Invalid rules');
|
|
19
|
+
}
|
|
20
|
+
function exactKeys(value, keys) {
|
|
21
|
+
object(value);
|
|
22
|
+
if (Object.keys(value).sort().join(',') !== [...keys].sort().join(','))
|
|
23
|
+
throw new Error('Invalid rule fields');
|
|
24
|
+
}
|
|
25
|
+
function validDate(value) {
|
|
26
|
+
return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(value) &&
|
|
27
|
+
Number.isFinite(Date.parse(value)) && new Date(value).toISOString().slice(0, 10) === value;
|
|
28
|
+
}
|
|
29
|
+
function loadRules() {
|
|
30
|
+
if (rulesFailure)
|
|
31
|
+
throw rulesFailure;
|
|
32
|
+
if (cachedRules)
|
|
33
|
+
return cachedRules;
|
|
34
|
+
try {
|
|
35
|
+
const text = amountRulesJson;
|
|
36
|
+
const data = JSON.parse(text);
|
|
37
|
+
// JSON.parse accepts duplicate keys; reject ambiguous rule files before using them.
|
|
38
|
+
const stack = [];
|
|
39
|
+
for (const match of text.matchAll(/"(?:\\.|[^"\\])*"|[{}\[\]]/g)) {
|
|
40
|
+
const token = match[0];
|
|
41
|
+
if (token === '{')
|
|
42
|
+
stack.push(new Set());
|
|
43
|
+
else if (token === '[')
|
|
44
|
+
stack.push(null);
|
|
45
|
+
else if (token === '}' || token === ']')
|
|
46
|
+
stack.pop();
|
|
47
|
+
else if (/^\s*:/.test(text.slice(match.index + token.length))) {
|
|
48
|
+
const key = JSON.parse(token);
|
|
49
|
+
const keys = stack[stack.length - 1];
|
|
50
|
+
if (!keys || keys.has(key))
|
|
51
|
+
throw new Error('Duplicate rule key');
|
|
52
|
+
keys.add(key);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
exactKeys(data, ['schemaVersion', 'dataVersion', 'antom', 'iso4217Reference', 'currencies', 'antomConstraints']);
|
|
56
|
+
if (data.schemaVersion !== 1 || !validDate(data.dataVersion))
|
|
57
|
+
throw new Error('Invalid rules version');
|
|
58
|
+
exactKeys(data.antom, ['source', 'sourceUrl', 'pageUpdatedAt']);
|
|
59
|
+
if (data.antom.source !== 'Antom Amount object usage rules' ||
|
|
60
|
+
data.antom.sourceUrl !== 'https://docs.antom.com/ac/ref/cc' || !validDate(data.antom.pageUpdatedAt)) {
|
|
61
|
+
throw new Error('Invalid source');
|
|
62
|
+
}
|
|
63
|
+
exactKeys(data.iso4217Reference, ['effectiveDate', 'source', 'sourceUrl', 'sourceSha256']);
|
|
64
|
+
const iso = data.iso4217Reference;
|
|
65
|
+
if (!validDate(iso.effectiveDate) || iso.source !== 'ISO 4217 List One' ||
|
|
66
|
+
typeof iso.sourceUrl !== 'string' || !iso.sourceUrl.startsWith('https://www.six-group.com/') ||
|
|
67
|
+
typeof iso.sourceSha256 !== 'string' || !/^[0-9a-f]{64}$/.test(iso.sourceSha256))
|
|
68
|
+
throw new Error('Invalid ISO source');
|
|
69
|
+
object(data.currencies);
|
|
70
|
+
object(data.antomConstraints);
|
|
71
|
+
if (!Object.keys(data.currencies).length)
|
|
72
|
+
throw new Error('Empty rules');
|
|
73
|
+
for (const [currency, rule] of Object.entries(data.currencies)) {
|
|
74
|
+
exactKeys(rule, ['minorUnit']);
|
|
75
|
+
if (!/^[A-Z]{3}$/.test(currency) || !Number.isInteger(rule.minorUnit) ||
|
|
76
|
+
rule.minorUnit < 0 || rule.minorUnit > 4)
|
|
77
|
+
throw new Error('Invalid currency rule');
|
|
78
|
+
}
|
|
79
|
+
for (const [currency, rule] of Object.entries(data.antomConstraints)) {
|
|
80
|
+
exactKeys(rule, ['minorValueMultiple']);
|
|
81
|
+
if (!Object.hasOwn(data.currencies, currency) || typeof rule.minorValueMultiple !== 'string' ||
|
|
82
|
+
!/^10*$/.test(rule.minorValueMultiple))
|
|
83
|
+
throw new Error('Invalid constraint');
|
|
84
|
+
}
|
|
85
|
+
cachedRules = data;
|
|
86
|
+
return cachedRules;
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
rulesFailure = new AmountError('RULE_DATA_ERROR');
|
|
90
|
+
throw rulesFailure;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
function currencyRule(currency) {
|
|
94
|
+
const rules = loadRules();
|
|
95
|
+
if (typeof currency !== 'string' || !/^[A-Z]{3}$/.test(currency))
|
|
96
|
+
throw new AmountError('INVALID_CURRENCY');
|
|
97
|
+
if (!Object.hasOwn(rules.currencies, currency))
|
|
98
|
+
throw new AmountError('UNSUPPORTED_CURRENCY');
|
|
99
|
+
return { rules, digits: rules.currencies[currency].minorUnit };
|
|
100
|
+
}
|
|
101
|
+
function normalize(value) {
|
|
102
|
+
const canonical = value.replace(/^0+(?=\d)/, '');
|
|
103
|
+
if (canonical.length > 16)
|
|
104
|
+
throw new AmountError('VALUE_TOO_LONG');
|
|
105
|
+
return canonical;
|
|
106
|
+
}
|
|
107
|
+
function valueString(value) {
|
|
108
|
+
if (typeof value !== 'string' || !/^[0-9]+$/.test(value))
|
|
109
|
+
throw new AmountError('INVALID_VALUE_FORMAT');
|
|
110
|
+
return normalize(value);
|
|
111
|
+
}
|
|
112
|
+
function checkMultiple(value, currency, rules) {
|
|
113
|
+
const multiple = rules.antomConstraints[currency]?.minorValueMultiple;
|
|
114
|
+
if (multiple && BigInt(value) % BigInt(multiple) !== 0n)
|
|
115
|
+
throw new AmountError('RULE_VIOLATION');
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* Convert a decimal amount to a smallest-unit string without rounding.
|
|
119
|
+
* @param amount Unsigned plain decimal string, including zero.
|
|
120
|
+
* @param currency Supported uppercase currency code.
|
|
121
|
+
* @returns Canonical smallest-unit string, at most sixteen digits.
|
|
122
|
+
*/
|
|
123
|
+
export function toAmount(amount, currency) {
|
|
124
|
+
const { rules, digits } = currencyRule(currency);
|
|
125
|
+
if (typeof amount !== 'string' || !/^[0-9]+(?:\.[0-9]+)?$/.test(amount))
|
|
126
|
+
throw new AmountError('INVALID_AMOUNT_FORMAT');
|
|
127
|
+
const [whole, fraction = ''] = amount.split('.');
|
|
128
|
+
if (/[1-9]/.test(fraction.slice(digits)))
|
|
129
|
+
throw new AmountError('EXCESS_PRECISION');
|
|
130
|
+
const value = normalize(whole + fraction.slice(0, digits).padEnd(digits, '0'));
|
|
131
|
+
checkMultiple(value, currency, rules);
|
|
132
|
+
return value;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Format a smallest-unit value for display without enforcing outbound multiples.
|
|
136
|
+
* @param value Unsigned integer string, including zero.
|
|
137
|
+
* @param currency Supported uppercase currency code.
|
|
138
|
+
* @returns Decimal string with the currency's configured number of fraction digits.
|
|
139
|
+
*/
|
|
140
|
+
export function fromAmount(value, currency) {
|
|
141
|
+
const { digits } = currencyRule(currency);
|
|
142
|
+
const canonical = valueString(value);
|
|
143
|
+
if (!digits)
|
|
144
|
+
return canonical;
|
|
145
|
+
const padded = canonical.padStart(digits + 1, '0');
|
|
146
|
+
return `${padded.slice(0, -digits)}.${padded.slice(-digits)}`;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Validate a smallest-unit value for sending to an API.
|
|
150
|
+
* @param value Unsigned integer string, including zero.
|
|
151
|
+
* @param currency Supported uppercase currency code.
|
|
152
|
+
*/
|
|
153
|
+
export function validateAmount(value, currency) {
|
|
154
|
+
const { rules } = currencyRule(currency);
|
|
155
|
+
checkMultiple(valueString(value), currency, rules);
|
|
156
|
+
}
|
|
157
|
+
/** Cross-language-compatible amount utility names. */
|
|
158
|
+
export const AmountUtil = Object.freeze({ toAmount, fromAmount, validate: validateAmount });
|