@ripwords/myinvois-client 0.2.14 → 0.2.16
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/api/documentSubmission.js +2 -2
- package/dist/{apiQueue-sL4mNlVz.cjs → apiQueue-CRyjAw52.cjs} +15 -2
- package/dist/apiQueue-CRyjAw52.cjs.map +1 -0
- package/dist/{apiQueue-4pQwCc0e.js → apiQueue-Csh8ru3S.js} +14 -1
- package/dist/{document-D7LLOhCD.cjs → document-CiBQaJ0c.cjs} +2 -6
- package/dist/{document-D7LLOhCD.cjs.map → document-CiBQaJ0c.cjs.map} +1 -1
- package/dist/{document-D_3z-v5k.js → document-SQQDNoI-.js} +1 -5
- package/dist/{documentSubmission-O5136E5C.js → documentSubmission-B45EflkR.js} +1 -1
- package/dist/{documentSubmission-CZvD4VVN.cjs → documentSubmission-DG5pfaBQ.cjs} +2 -2
- package/dist/{documentSubmission-CZvD4VVN.cjs.map → documentSubmission-DG5pfaBQ.cjs.map} +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.js +3 -3
- package/dist/index10.cjs +24 -4
- package/dist/index10.cjs.map +1 -0
- package/dist/index11.cjs +0 -20
- package/dist/index12.cjs +33 -2
- package/dist/{index26.cjs.map → index12.cjs.map} +1 -1
- package/dist/index13.cjs +23 -2
- package/dist/{index27.cjs.map → index13.cjs.map} +1 -1
- package/dist/index14.cjs +0 -330
- package/dist/index15.cjs +0 -193
- package/dist/index16.cjs +0 -62
- package/dist/index17.cjs +3 -531
- package/dist/index18.cjs +9 -192
- package/dist/index18.cjs.map +1 -1
- package/dist/index19.cjs +5 -0
- package/dist/index2.cjs +61 -4
- package/dist/index2.cjs.map +1 -0
- package/dist/index20.cjs +19 -24
- package/dist/index21.cjs +3 -0
- package/dist/index22.cjs +3 -0
- package/dist/index23.cjs +326 -25
- package/dist/index23.cjs.map +1 -1
- package/dist/index24.cjs +187 -19
- package/dist/index24.cjs.map +1 -1
- package/dist/index25.cjs +5 -0
- package/dist/index26.cjs +6 -33
- package/dist/index27.cjs +4 -23
- package/dist/index28.cjs +3 -0
- package/dist/index29.cjs +3 -0
- package/dist/index3.cjs +531 -6
- package/dist/index3.cjs.map +1 -0
- package/dist/index30.cjs +6 -0
- package/dist/index4.cjs +195 -4
- package/dist/index4.cjs.map +1 -0
- package/dist/index5.cjs +0 -3
- package/dist/index6.cjs +24 -2
- package/dist/index6.cjs.map +1 -0
- package/dist/index7.cjs +0 -6
- package/dist/index8.cjs +0 -4
- package/dist/index9.cjs +25 -9
- package/dist/index9.cjs.map +1 -1
- package/dist/utils/apiQueue.js +1 -1
- package/dist/utils/document.js +1 -1
- package/dist/utils/signature-diagnostics.js +1 -1
- package/package.json +1 -1
- package/dist/apiQueue-sL4mNlVz.cjs.map +0 -1
- package/dist/index14.cjs.map +0 -1
- package/dist/index15.cjs.map +0 -1
- package/dist/index16.cjs.map +0 -1
- package/dist/index17.cjs.map +0 -1
- package/dist/index20.cjs.map +0 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import "../formatIdValue-qTxJqj9o.js";
|
|
2
|
-
import "../document-
|
|
3
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-
|
|
2
|
+
import "../document-SQQDNoI-.js";
|
|
3
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "../documentSubmission-B45EflkR.js";
|
|
4
4
|
|
|
5
5
|
export { getSubmissionStatus, performDocumentAction, submitDocument };
|
|
@@ -94,7 +94,13 @@ var RateLimiter = class {
|
|
|
94
94
|
return new Promise((resolve, reject) => {
|
|
95
95
|
const execute = () => {
|
|
96
96
|
if (debug && category) console.log(`[apiQueue] ▶️ Executing request (${category}). Remaining queue: ${this.queue.length}`);
|
|
97
|
-
|
|
97
|
+
try {
|
|
98
|
+
const result = fn();
|
|
99
|
+
if (result && typeof result.then === "function") result.then(resolve).catch(reject);
|
|
100
|
+
else resolve(result);
|
|
101
|
+
} catch (err) {
|
|
102
|
+
reject(err);
|
|
103
|
+
}
|
|
98
104
|
};
|
|
99
105
|
if (debug && category) console.log(`[apiQueue] ⏳ Queued request (${category}). Queue length before push: ${this.queue.length}`);
|
|
100
106
|
this.queue.push(execute);
|
|
@@ -132,6 +138,13 @@ function categorizeRequest(path, method = "GET") {
|
|
|
132
138
|
if (cleanPath.includes("/searchtin")) return "searchTin";
|
|
133
139
|
if (cleanPath.includes("/qrcode")) return "taxpayerQr";
|
|
134
140
|
if (cleanPath.includes("/connect/token")) return "loginTaxpayer";
|
|
141
|
+
if (cleanPath.includes("/documents/search")) return "searchDocuments";
|
|
142
|
+
if (/\/documents\/[^/]+\/raw$/.test(cleanPath)) return "getDocument";
|
|
143
|
+
if (/\/documents\/[^/]+\/details$/.test(cleanPath)) return "getDocumentDetails";
|
|
144
|
+
if (cleanPath.includes("/documents/state/")) return isPost ? "cancelDocument" : "getDocument";
|
|
145
|
+
if (cleanPath.includes("/taxpayer/search/tin")) return "searchTin";
|
|
146
|
+
if (cleanPath.includes("/taxpayer/validate/")) return "searchTin";
|
|
147
|
+
if (cleanPath.includes("/taxpayer/qrcode")) return "taxpayerQr";
|
|
135
148
|
return "default";
|
|
136
149
|
}
|
|
137
150
|
|
|
@@ -148,4 +161,4 @@ Object.defineProperty(exports, 'queueRequest', {
|
|
|
148
161
|
return queueRequest;
|
|
149
162
|
}
|
|
150
163
|
});
|
|
151
|
-
//# sourceMappingURL=apiQueue-
|
|
164
|
+
//# sourceMappingURL=apiQueue-CRyjAw52.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"apiQueue-CRyjAw52.cjs","names":["RATE_LIMITS: Record<ApiCategory, RateLimitConfig>","config: RateLimitConfig","fn: () => Promise<T>","debug: boolean","category?: ApiCategory","category: ApiCategory","path: string","method: string"],"sources":["../src/utils/apiQueue.ts"],"sourcesContent":["// A very small utility that provides per-endpoint request queuing with fixed-window rate-limits.\n// The goal is to make sure that we never exceed the vendor-defined limits while also ensuring\n// that every request is eventually executed.\n//\n// NOTE: This is intentionally minimal – no external dependencies are introduced.\n// If you need more advanced features (persistence, jitter, etc.) consider a library such as `bottleneck`.\n\n/*\nRate-limit specification (per 60-second window)\n----------------------------------------------\nLogin as Taxpayer System : 12\nLogin as Intermediary System : 12\nSubmit Documents : 100\nGet Submission : 300\nCancel Document : 12\nReject Document : 12\nGet Document : 60\nGet Document Details : 125\nGet Recent Documents : 12\nSearch Documents : 12\nSearch Taxpayer's TIN : 60\nTaxpayer's QR Code : 60\n*/\n\nexport type ApiCategory =\n | 'loginTaxpayer'\n | 'loginIntermediary'\n | 'submitDocuments'\n | 'getSubmission'\n | 'cancelDocument'\n | 'rejectDocument'\n | 'getDocument'\n | 'getDocumentDetails'\n | 'getRecentDocuments'\n | 'searchDocuments'\n | 'searchTin'\n | 'taxpayerQr'\n | 'default'\n\ninterface RateLimitConfig {\n limit: number\n windowMs: number\n}\n\nconst WINDOW = 60_000 // 60 seconds\n\n// Hard-coded limits based on the specification above.\nconst RATE_LIMITS: Record<ApiCategory, RateLimitConfig> = {\n loginTaxpayer: { limit: 12, windowMs: WINDOW },\n loginIntermediary: { limit: 12, windowMs: WINDOW },\n submitDocuments: { limit: 100, windowMs: WINDOW },\n getSubmission: { limit: 300, windowMs: WINDOW },\n cancelDocument: { limit: 12, windowMs: WINDOW },\n rejectDocument: { limit: 12, windowMs: WINDOW },\n getDocument: { limit: 60, windowMs: WINDOW },\n getDocumentDetails: { limit: 125, windowMs: WINDOW },\n getRecentDocuments: { limit: 12, windowMs: WINDOW },\n searchDocuments: { limit: 12, windowMs: WINDOW },\n searchTin: { limit: 60, windowMs: WINDOW },\n taxpayerQr: { limit: 60, windowMs: WINDOW },\n default: { limit: 10_000, windowMs: WINDOW }, // effectively no limit\n}\n\n/**\n * A very small sliding-window rate-limiter with queuing.\n * Each category gets its own instance so limits are isolated.\n */\nclass RateLimiter {\n private readonly limit: number\n private readonly windowMs: number\n private queue: Array<() => void> = []\n private timestamps: number[] = []\n private timer: NodeJS.Timeout | null = null\n\n constructor(config: RateLimitConfig) {\n this.limit = config.limit\n this.windowMs = config.windowMs\n }\n\n private drainQueue() {\n if (this.queue.length === 0) {\n return\n }\n\n const now = Date.now()\n // Purge stale timestamps (older than window)\n this.timestamps = this.timestamps.filter(ts => now - ts < this.windowMs)\n\n if (this.timestamps.length >= this.limit) {\n // We are currently rate-limited – schedule a retry when the earliest call exits the window\n const earliest = this.timestamps[0]!\n const delay = this.windowMs - (now - earliest) + 1 // +1ms buffer\n if (!this.timer) {\n this.timer = setTimeout(() => {\n this.timer = null\n this.drainQueue()\n }, delay)\n }\n return\n }\n\n // We can process at least one queued request now\n const next = this.queue.shift()!\n this.timestamps.push(now)\n next()\n\n // Recursively drain (in case there is remaining capacity)\n this.drainQueue()\n }\n\n get queueSize() {\n return this.queue.length\n }\n\n schedule<T>(\n fn: () => Promise<T>,\n debug: boolean = false,\n category?: ApiCategory,\n ): Promise<T> {\n return new Promise((resolve, reject) => {\n const execute = () => {\n if (debug && category) {\n console.log(\n `[apiQueue] ▶️ Executing request (${category}). Remaining queue: ${this.queue.length}`,\n )\n }\n try {\n const result = fn()\n // Support both promise and synchronous return values\n if (result && typeof (result as any).then === 'function') {\n ;(result as Promise<T>).then(resolve).catch(reject)\n } else {\n resolve(result as T)\n }\n } catch (err) {\n reject(err)\n }\n }\n\n if (debug && category) {\n console.log(\n `[apiQueue] ⏳ Queued request (${category}). Queue length before push: ${this.queue.length}`,\n )\n }\n\n this.queue.push(execute)\n this.drainQueue()\n })\n }\n}\n\n// A shared registry of limiters keyed by category\nconst limiterRegistry = new Map<ApiCategory, RateLimiter>()\n\nfunction getLimiter(category: ApiCategory): RateLimiter {\n if (!limiterRegistry.has(category)) {\n limiterRegistry.set(category, new RateLimiter(RATE_LIMITS[category]))\n }\n // Non-null because we just set it if missing.\n return limiterRegistry.get(category) as RateLimiter\n}\n\n/**\n * Public helper to schedule a request according to the category's limits.\n */\nexport function queueRequest<T>(\n category: ApiCategory,\n fn: () => Promise<T>,\n debug: boolean = false,\n): Promise<T> {\n const limiter = getLimiter(category)\n return limiter.schedule(fn, debug, category)\n}\n\n/**\n * Very naive path-based category detection. If no matcher fits, the `default` category\n * (effectively unlimited) is returned. Adjust these heuristics as your API surface evolves.\n */\nexport function categorizeRequest(\n path: string,\n method: string = 'GET',\n): ApiCategory {\n const cleanPath = path.toLowerCase()\n const isPost = method?.toUpperCase() === 'POST'\n\n if (cleanPath.includes('/documentsubmissions')) {\n return isPost ? 'submitDocuments' : 'getSubmission'\n }\n\n if (cleanPath.includes('/documentmanagement')) {\n if (cleanPath.endsWith('/cancel')) return 'cancelDocument'\n if (cleanPath.endsWith('/reject')) return 'rejectDocument'\n if (cleanPath.endsWith('/details')) return 'getDocumentDetails'\n if (cleanPath.includes('/recent')) return 'getRecentDocuments'\n // Fallbacks inside document management\n return method === 'GET' ? 'getDocument' : 'searchDocuments'\n }\n\n if (cleanPath.includes('/searchtin')) return 'searchTin'\n if (cleanPath.includes('/qrcode')) return 'taxpayerQr'\n if (cleanPath.includes('/connect/token')) {\n // Distinguish between taxpayer & intermediary based on path hint if possible\n return 'loginTaxpayer'\n }\n\n // -----------------------------\n // New path matchers (v1.0 endpoints)\n // -----------------------------\n\n // Search Documents\n if (cleanPath.includes('/documents/search')) {\n return 'searchDocuments'\n }\n\n // Document raw content\n if (/\\/documents\\/[^/]+\\/raw$/.test(cleanPath)) {\n return 'getDocument'\n }\n\n // Document details\n if (/\\/documents\\/[^/]+\\/details$/.test(cleanPath)) {\n return 'getDocumentDetails'\n }\n\n // Document state actions (cancel/reject)\n if (cleanPath.includes('/documents/state/')) {\n return isPost ? 'cancelDocument' : 'getDocument'\n }\n\n // Taxpayer TIN search & validation share same limit bucket\n if (cleanPath.includes('/taxpayer/search/tin')) return 'searchTin'\n if (cleanPath.includes('/taxpayer/validate/')) return 'searchTin'\n\n // Taxpayer QR code info\n if (cleanPath.includes('/taxpayer/qrcode')) return 'taxpayerQr'\n\n return 'default'\n}\n"],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AAC1C,MAAI,UAAU,SAAS,UAAU,CAAE,QAAO;AAC1C,MAAI,UAAU,SAAS,WAAW,CAAE,QAAO;AAC3C,MAAI,UAAU,SAAS,UAAU,CAAE,QAAO;AAE1C,SAAO,WAAW,QAAQ,gBAAgB;CAC3C;AAED,KAAI,UAAU,SAAS,aAAa,CAAE,QAAO;AAC7C,KAAI,UAAU,SAAS,UAAU,CAAE,QAAO;AAC1C,KAAI,UAAU,SAAS,iBAAiB,CAEtC,QAAO;AAQT,KAAI,UAAU,SAAS,oBAAoB,CACzC,QAAO;AAIT,KAAI,2BAA2B,KAAK,UAAU,CAC5C,QAAO;AAIT,KAAI,+BAA+B,KAAK,UAAU,CAChD,QAAO;AAIT,KAAI,UAAU,SAAS,oBAAoB,CACzC,QAAO,SAAS,mBAAmB;AAIrC,KAAI,UAAU,SAAS,uBAAuB,CAAE,QAAO;AACvD,KAAI,UAAU,SAAS,sBAAsB,CAAE,QAAO;AAGtD,KAAI,UAAU,SAAS,mBAAmB,CAAE,QAAO;AAEnD,QAAO;AACR"}
|
|
@@ -93,7 +93,13 @@ var RateLimiter = class {
|
|
|
93
93
|
return new Promise((resolve, reject) => {
|
|
94
94
|
const execute = () => {
|
|
95
95
|
if (debug && category) console.log(`[apiQueue] ▶️ Executing request (${category}). Remaining queue: ${this.queue.length}`);
|
|
96
|
-
|
|
96
|
+
try {
|
|
97
|
+
const result = fn();
|
|
98
|
+
if (result && typeof result.then === "function") result.then(resolve).catch(reject);
|
|
99
|
+
else resolve(result);
|
|
100
|
+
} catch (err) {
|
|
101
|
+
reject(err);
|
|
102
|
+
}
|
|
97
103
|
};
|
|
98
104
|
if (debug && category) console.log(`[apiQueue] ⏳ Queued request (${category}). Queue length before push: ${this.queue.length}`);
|
|
99
105
|
this.queue.push(execute);
|
|
@@ -131,6 +137,13 @@ function categorizeRequest(path, method = "GET") {
|
|
|
131
137
|
if (cleanPath.includes("/searchtin")) return "searchTin";
|
|
132
138
|
if (cleanPath.includes("/qrcode")) return "taxpayerQr";
|
|
133
139
|
if (cleanPath.includes("/connect/token")) return "loginTaxpayer";
|
|
140
|
+
if (cleanPath.includes("/documents/search")) return "searchDocuments";
|
|
141
|
+
if (/\/documents\/[^/]+\/raw$/.test(cleanPath)) return "getDocument";
|
|
142
|
+
if (/\/documents\/[^/]+\/details$/.test(cleanPath)) return "getDocumentDetails";
|
|
143
|
+
if (cleanPath.includes("/documents/state/")) return isPost ? "cancelDocument" : "getDocument";
|
|
144
|
+
if (cleanPath.includes("/taxpayer/search/tin")) return "searchTin";
|
|
145
|
+
if (cleanPath.includes("/taxpayer/validate/")) return "searchTin";
|
|
146
|
+
if (cleanPath.includes("/taxpayer/qrcode")) return "taxpayerQr";
|
|
134
147
|
return "default";
|
|
135
148
|
}
|
|
136
149
|
|
|
@@ -335,11 +335,7 @@ const createSignedProperties = (certificateDigest, signingTime, issuerName, seri
|
|
|
335
335
|
* Based on working implementation pattern
|
|
336
336
|
*/
|
|
337
337
|
const calculateSignedPropertiesDigest = (signedProperties) => {
|
|
338
|
-
const
|
|
339
|
-
Target: "signature",
|
|
340
|
-
SignedProperties: signedProperties.SignedProperties
|
|
341
|
-
};
|
|
342
|
-
const signedPropertiesString = JSON.stringify(signedPropertiesWithTarget);
|
|
338
|
+
const signedPropertiesString = canonicalizeJSON(signedProperties);
|
|
343
339
|
const hash = crypto.default.createHash("sha256");
|
|
344
340
|
hash.update(signedPropertiesString, "utf8");
|
|
345
341
|
return hash.digest("base64");
|
|
@@ -607,4 +603,4 @@ Object.defineProperty(exports, 'sortObjectKeys', {
|
|
|
607
603
|
return sortObjectKeys;
|
|
608
604
|
}
|
|
609
605
|
});
|
|
610
|
-
//# sourceMappingURL=document-
|
|
606
|
+
//# sourceMappingURL=document-CiBQaJ0c.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"document-D7LLOhCD.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: any","certificatePem: string","X509Certificate","dn: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","docDigest: string","propsDigest: string","privateKeyPem: string","signingCredentials: SigningCredentials","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}","lineItems: InvoiceLineItem[]"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n AllDocumentsV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n UnitTypeCode,\n InvoiceLineItem,\n} from '../types'\nimport type { ClassificationCode } from '../types'\nimport type { TaxTypeCode } from '../types'\nimport { formatIdValue } from './formatIdValue'\n\n/**\n * MyInvois v1.1 Document Generation and Signing Utilities\n * Strictly follows: https://sdk.myinvois.hasil.gov.my/documents/invoice-v1-1\n * JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/\n */\n\n/**\n * Determines if a line item uses fixed rate taxation\n */\nexport const isFixedRateTax = (item: InvoiceLineItem): boolean => {\n return (\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n )\n}\n\n/**\n * Determines if a line item uses percentage taxation\n */\nexport const isPercentageTax = (item: InvoiceLineItem): boolean => {\n return item.taxRate !== undefined && !isFixedRateTax(item)\n}\n\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport const calculateExpectedTaxAmount = (item: InvoiceLineItem): number => {\n if (isFixedRateTax(item)) {\n return item.taxPerUnitAmount! * item.baseUnitMeasure!\n } else if (isPercentageTax(item)) {\n return (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n }\n return 0\n}\n\n/**\n * Extracts the line-item array from any document variant\n */\nconst getLineItems = (doc: AllDocumentsV1_1): InvoiceLineItem[] => {\n if ('invoiceLineItems' in doc) return doc.invoiceLineItems\n if ('creditNoteLineItems' in doc) return doc.creditNoteLineItems\n if ('debitNoteLineItems' in doc) return doc.debitNoteLineItems\n if ('refundNoteLineItems' in doc) return doc.refundNoteLineItems\n if ('selfBilledCreditNoteLineItems' in doc)\n return doc.selfBilledCreditNoteLineItems\n if ('selfBilledRefundNoteLineItems' in doc)\n return doc.selfBilledRefundNoteLineItems\n // Fallback (should never happen with exhaustive types)\n return []\n}\n\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport function sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys)\n }\n\n const sortedObj: Record<string, unknown> = {}\n const keys = Object.keys(obj as Record<string, unknown>).sort()\n\n for (const key of keys) {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key])\n }\n\n return sortedObj\n}\n\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport const canonicalizeJSON = (obj: unknown): string => {\n const sortedObj = sortObjectKeys(obj)\n // Use compact JSON with no extra whitespace\n return JSON.stringify(sortedObj, null, 0)\n}\n\n/**\n * Generates a clean invoice object following MyInvois v1.1 specification exactly\n * This is the base invoice structure WITHOUT signature elements (for hash calculation)\n *\n * Key requirements from working documents:\n * - All mandatory fields must be present\n * - Many optional fields must be present even if empty\n * - Specific field ordering and structure\n * - Correct listID values (e.g., \"3166-1\" not \"ISO3166-1\")\n */\nexport const generateCleanInvoiceObject = (\n invoice: AllDocumentsV1_1,\n): InvoiceSubmission => {\n const lineItems = getLineItems(invoice)\n return {\n // === MANDATORY CORE FIELDS ===\n ID: [{ _: invoice.eInvoiceCodeOrNumber }],\n IssueDate: [{ _: invoice.eInvoiceDate }],\n IssueTime: [{ _: invoice.eInvoiceTime }],\n InvoiceTypeCode: [\n {\n _: invoice.eInvoiceTypeCode,\n listVersionID: invoice.eInvoiceVersion || '1.1',\n },\n ],\n DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],\n\n // === BILLING REFERENCE (only for credit/debit/refund notes) ===\n ...('originalEInvoiceReferenceNumber' in invoice &&\n invoice.originalEInvoiceReferenceNumber\n ? {\n BillingReference: [\n {\n InvoiceDocumentReference: [\n {\n UUID: [\n {\n _: invoice.originalEInvoiceReferenceNumber,\n },\n ],\n ID: [\n {\n _: invoice.eInvoiceCodeOrNumber,\n },\n ],\n },\n ],\n },\n ],\n }\n : {}),\n\n // === SUPPLIER PARTY (AccountingSupplierParty) ===\n AccountingSupplierParty: [\n {\n Party: [\n {\n // Industry Classification - required field\n IndustryClassificationCode: [\n {\n _: invoice.supplier.industryClassificationCode,\n name: invoice.supplier.industryClassificationDescription,\n },\n ],\n\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.supplier.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.supplier.registrationNumber),\n schemeID: invoice.supplier.registrationType || 'NRIC',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.supplier.address.cityName }],\n CountrySubentityCode: [{ _: invoice.supplier.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.supplier.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.supplier.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.supplier.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.supplier.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === BUYER PARTY (AccountingCustomerParty) ===\n AccountingCustomerParty: [\n {\n Party: [\n {\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.buyer.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.buyer.registrationNumber),\n schemeID: invoice.buyer.registrationType || 'NRIC',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.sstRegistrationNumber || 'NA',\n schemeID: 'SST',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.buyer.address.cityName }],\n CountrySubentityCode: [{ _: invoice.buyer.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.buyer.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.buyer.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.buyer.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.buyer.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === TAX TOTAL ===\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n // Generate basic tax subtotal from invoice line items\n {\n TaxableAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxCategory: [\n {\n ID: [{ _: lineItems[0]?.taxType || '01' }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // === LEGAL MONETARY TOTAL ===\n LegalMonetaryTotal: [\n {\n LineExtensionAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxExclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxInclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxInclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableAmount: [\n {\n _: invoice.legalMonetaryTotal.payableAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // === INVOICE LINES ===\n InvoiceLine: lineItems.map((item, index) => ({\n ID: [{ _: (index + 1).toString() }],\n\n // Item Information\n Item: [\n {\n CommodityClassification: [\n {\n ItemClassificationCode: [\n {\n _: item.itemClassificationCode,\n listID: 'CLASS',\n },\n ],\n },\n ],\n Description: [{ _: item.itemDescription }],\n },\n ],\n\n ItemPriceExtension: [\n {\n Amount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n LineExtensionAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n\n // Price Information\n Price: [\n {\n PriceAmount: [\n {\n _: item.unitPrice,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // Tax Information for line\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n {\n TaxableAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n // Conditional tax fields based on taxation type\n ...(item.taxPerUnitAmount !== undefined &&\n item.baseUnitMeasure !== undefined\n ? {\n // Fixed Rate Taxation\n PerUnitAmount: [\n {\n _: item.taxPerUnitAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n BaseUnitMeasure: [\n {\n _: item.baseUnitMeasure,\n unitCode: item.baseUnitMeasureCode || 'C62',\n },\n ],\n }\n : item.taxRate !== undefined\n ? {\n // Percentage Taxation\n Percent: [{ _: item.taxRate }],\n }\n : {}),\n TaxCategory: [\n {\n ID: [{ _: item.taxType }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })),\n\n // === TAX EXCHANGE RATE (mandatory where applicable) ===\n TaxExchangeRate: invoice.currencyExchangeRate\n ? [\n {\n SourceCurrencyCode: [\n {\n _: invoice.invoiceCurrencyCode,\n },\n ],\n TargetCurrencyCode: [\n {\n _: 'MYR',\n },\n ],\n CalculationRate: [\n {\n _: invoice.currencyExchangeRate,\n },\n ],\n },\n ]\n : undefined,\n }\n}\n\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport const generateCleanUBLDocument = (\n invoices: AllDocumentsV1_1[],\n): UBLDocument => {\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: invoices.map(generateCleanInvoiceObject),\n }\n}\n\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport const calculateDocumentDigest = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // CRITICAL FIX: Remove UBLExtensions and Signature from each invoice before hashing\n const documentForHashing = JSON.parse(JSON.stringify(cleanDocument))\n if (documentForHashing.Invoice && Array.isArray(documentForHashing.Invoice)) {\n documentForHashing.Invoice.forEach((invoice: any) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to string for hashing (no canonicalization - use direct JSON.stringify)\n const documentString = JSON.stringify(documentForHashing)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(documentString, 'utf8')\n\n // Return as Base64 (DocDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n // Extract certificate content (Base64 without PEM headers/footers)\n const certificateContent = certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '') // Remove all whitespace\n\n // Convert Base64 to binary\n const certificateBinary = Buffer.from(certificateContent, 'base64')\n\n // Calculate SHA-256 hash of binary content\n const hash = crypto.createHash('sha256')\n hash.update(certificateBinary)\n\n // Return as Base64\n return hash.digest('base64')\n}\n\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport const extractCertificateInfo = (\n certificatePem: string,\n): {\n issuerName: string\n serialNumber: string\n subjectName: string\n} => {\n try {\n const cert = new X509Certificate(certificatePem)\n\n // Extract serial number and convert to decimal string\n const serialNumberHex = cert.serialNumber\n\n // ENHANCED: Normalize distinguished name format (DS326)\n // Ensures MyInvois portal compatibility for X509IssuerName matching\n const normalizeDistinguishedName = (dn: string): string => {\n // Convert multi-line format to comma-separated RFC2253 format\n const normalized = dn\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0)\n .join(', ')\n\n // MyInvois-specific normalization to prevent DS326 errors\n return normalized\n .replace(/\\s*=\\s*/g, '=') // Remove spaces around equals (CRITICAL for portal)\n .replace(/,\\s+/g, ', ') // Ensure single space after commas\n .replace(/\\r/g, '') // Remove any carriage returns\n .replace(/\\s{2,}/g, ' ') // Replace multiple spaces with single space\n .trim() // Remove leading/trailing whitespace\n }\n\n // Enhanced serial number formatting\n const formatSerialNumber = (serialHex: string): string => {\n // Convert hex to decimal and ensure it's a string\n const decimal = BigInt('0x' + serialHex).toString()\n return decimal\n }\n\n return {\n issuerName: normalizeDistinguishedName(cert.issuer),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: normalizeDistinguishedName(cert.subject),\n }\n } catch (error: unknown) {\n throw new Error(\n `Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Step 5: Create SignedProperties with enhanced structure\n * FIXED: Simplified structure to match MyInvois expectations (DS320)\n * Following MyInvois JSON signature specification exactly\n */\nexport const createSignedProperties = (\n certificateDigest: string,\n signingTime: string,\n issuerName: string,\n serialNumber: string,\n): SignedPropertiesObject => {\n return {\n SignedProperties: [\n {\n Id: 'id-xades-signed-props',\n SignedSignatureProperties: [\n {\n SigningTime: [{ _: signingTime }],\n SigningCertificate: [\n {\n Cert: [\n {\n CertDigest: [\n {\n DigestMethod: [\n {\n Algorithm:\n 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: certificateDigest }],\n },\n ],\n IssuerSerial: [\n {\n X509IssuerName: [{ _: issuerName }],\n X509SerialNumber: [{ _: serialNumber }],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Step 6: Calculate SignedProperties Digest\n * FIXED: Add Target wrapper and use direct JSON stringify (DS320)\n * Based on working implementation pattern\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n): string => {\n // CRITICAL FIX: Wrap with Target as per working implementation\n const signedPropertiesWithTarget = {\n Target: 'signature',\n SignedProperties: signedProperties.SignedProperties,\n }\n\n // Convert to string for hashing (no canonicalization - use direct JSON.stringify)\n const signedPropertiesString = JSON.stringify(signedPropertiesWithTarget)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(signedPropertiesString, 'utf8')\n\n // Return as Base64 (PropsDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport const createSignedInfoAndSign = (\n docDigest: string,\n propsDigest: string,\n privateKeyPem: string,\n): { signedInfo: SignedInfoObject; signatureValue: string } => {\n // Create SignedInfo structure following specification exactly\n const signedInfo = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // FIXED: Use direct JSON.stringify instead of canonicalization (DS333)\n // Based on working implementation pattern\n const signedInfoString = JSON.stringify(signedInfo)\n\n // Sign with RSA-SHA256 directly (RSA-SHA256 handles hashing internally)\n // FIXED: Removed double-hashing bug that was causing DS333 errors\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoString, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n return { signedInfo, signatureValue }\n } catch (error) {\n throw new Error(\n `Signature generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport const generateCompleteDocument = (\n invoices: AllDocumentsV1_1[],\n signingCredentials: SigningCredentials,\n): CompleteInvoice => {\n try {\n // Step 1: Generate clean document (done in calculateDocumentDigest)\n // Step 2: Calculate document digest\n const docDigest = calculateDocumentDigest(invoices)\n\n // Generate signing time in proper ISO format\n const signingTime = new Date().toISOString()\n\n // Extract certificate information (enhanced)\n const certInfo = extractCertificateInfo(signingCredentials.certificatePem)\n\n // Step 4: Calculate certificate digest\n const certificateDigest = calculateCertificateDigest(\n signingCredentials.certificatePem,\n )\n\n // Step 5: Create SignedProperties using extracted cert info\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 6: Calculate SignedProperties digest\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Step 3: Create SignedInfo and generate signature\n const { signedInfo, signatureValue } = createSignedInfoAndSign(\n docDigest,\n propsDigest,\n signingCredentials.privateKeyPem,\n )\n\n // Extract certificate content (Base64 without PEM headers)\n const certificate = signingCredentials.certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '')\n\n // Step 7: Create final signed document\n const signedInvoices = invoices.map(invoice => {\n const cleanInvoice = generateCleanInvoiceObject(invoice)\n\n return {\n ...cleanInvoice,\n\n // Add UBLExtensions with complete signature structure\n UBLExtensions: [\n {\n UBLExtension: [\n {\n ExtensionURI: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n ExtensionContent: [\n {\n UBLDocumentSignatures: [\n {\n SignatureInformation: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:1',\n },\n ],\n ReferencedSignatureID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n Signature: [\n {\n Id: 'signature',\n Object: [\n {\n QualifyingProperties: [\n {\n Target: 'signature',\n SignedProperties:\n signedProperties.SignedProperties,\n },\n ],\n },\n ],\n KeyInfo: [\n {\n X509Data: [\n {\n X509Certificate: [{ _: certificate }],\n X509SubjectName: [\n { _: certInfo.subjectName },\n ],\n X509IssuerSerial: [\n {\n X509IssuerName: [\n {\n _: certInfo.issuerName,\n },\n ],\n X509SerialNumber: [\n {\n _: certInfo.serialNumber,\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n SignatureValue: [{ _: signatureValue }],\n SignedInfo: [signedInfo],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // Add simple Signature reference\n Signature: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n SignatureMethod: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n },\n ],\n }\n })\n\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: signedInvoices,\n }\n } catch (error) {\n throw new Error(\n `Document generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport const createPercentageTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = (totalTaxableAmount * params.taxRate) / 100\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxRate: params.taxRate,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport const createFixedRateTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxPerUnitAmount: params.taxPerUnitAmount,\n baseUnitMeasure: params.baseUnitMeasure,\n baseUnitMeasureCode: params.baseUnitMeasureCode,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Calculates invoice totals from line items\n */\nexport const calculateInvoiceTotals = (\n lineItems: InvoiceLineItem[],\n): {\n legalMonetaryTotal: {\n taxExclusiveAmount: number\n taxInclusiveAmount: number\n payableAmount: number\n }\n taxTotal: {\n taxAmount: number\n }\n} => {\n const taxExclusiveAmount = lineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const totalTaxAmount = lineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount\n\n return {\n legalMonetaryTotal: {\n taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,\n taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,\n payableAmount: Math.round(taxInclusiveAmount * 100) / 100,\n },\n taxTotal: {\n taxAmount: Math.round(totalTaxAmount * 100) / 100,\n },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BAAiB,UAAU,OAC/B,CAAC,KAAK,SAAS,MAAM,KAAK,WAC1B,EACD;CACD,MAAM,qBAAqB,qBAAqB;AAEhD,QAAO;EACL,oBAAoB;GAClB,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,eAAe,KAAK,MAAM,qBAAqB,IAAI,GAAG;EACvD;EACD,UAAU,EACR,WAAW,KAAK,MAAM,iBAAiB,IAAI,GAAG,IAC/C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"document-CiBQaJ0c.cjs","names":["item: InvoiceLineItem","doc: AllDocumentsV1_1","obj: unknown","sortedObj: Record<string, unknown>","invoice: AllDocumentsV1_1","invoices: AllDocumentsV1_1[]","invoice: any","certificatePem: string","X509Certificate","dn: string","serialHex: string","error: unknown","certificateDigest: string","signingTime: string","issuerName: string","serialNumber: string","signedProperties: SignedPropertiesObject","docDigest: string","propsDigest: string","privateKeyPem: string","signingCredentials: SigningCredentials","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}","params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}","lineItems: InvoiceLineItem[]"],"sources":["../src/utils/document.ts"],"sourcesContent":["import crypto, { X509Certificate } from 'crypto'\nimport {\n InvoiceSubmission,\n AllDocumentsV1_1,\n SigningCredentials,\n SignedPropertiesObject,\n UBLDocument,\n CompleteInvoice,\n SignedInfoObject,\n UnitTypeCode,\n InvoiceLineItem,\n} from '../types'\nimport type { ClassificationCode } from '../types'\nimport type { TaxTypeCode } from '../types'\nimport { formatIdValue } from './formatIdValue'\n\n/**\n * MyInvois v1.1 Document Generation and Signing Utilities\n * Strictly follows: https://sdk.myinvois.hasil.gov.my/documents/invoice-v1-1\n * JSON Signature Guide: https://sdk.myinvois.hasil.gov.my/signature-creation-json/\n */\n\n/**\n * Determines if a line item uses fixed rate taxation\n */\nexport const isFixedRateTax = (item: InvoiceLineItem): boolean => {\n return (\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n )\n}\n\n/**\n * Determines if a line item uses percentage taxation\n */\nexport const isPercentageTax = (item: InvoiceLineItem): boolean => {\n return item.taxRate !== undefined && !isFixedRateTax(item)\n}\n\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport const calculateExpectedTaxAmount = (item: InvoiceLineItem): number => {\n if (isFixedRateTax(item)) {\n return item.taxPerUnitAmount! * item.baseUnitMeasure!\n } else if (isPercentageTax(item)) {\n return (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n }\n return 0\n}\n\n/**\n * Extracts the line-item array from any document variant\n */\nconst getLineItems = (doc: AllDocumentsV1_1): InvoiceLineItem[] => {\n if ('invoiceLineItems' in doc) return doc.invoiceLineItems\n if ('creditNoteLineItems' in doc) return doc.creditNoteLineItems\n if ('debitNoteLineItems' in doc) return doc.debitNoteLineItems\n if ('refundNoteLineItems' in doc) return doc.refundNoteLineItems\n if ('selfBilledCreditNoteLineItems' in doc)\n return doc.selfBilledCreditNoteLineItems\n if ('selfBilledRefundNoteLineItems' in doc)\n return doc.selfBilledRefundNoteLineItems\n // Fallback (should never happen with exhaustive types)\n return []\n}\n\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport function sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== 'object') {\n return obj\n }\n\n if (Array.isArray(obj)) {\n return obj.map(sortObjectKeys)\n }\n\n const sortedObj: Record<string, unknown> = {}\n const keys = Object.keys(obj as Record<string, unknown>).sort()\n\n for (const key of keys) {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key])\n }\n\n return sortedObj\n}\n\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport const canonicalizeJSON = (obj: unknown): string => {\n const sortedObj = sortObjectKeys(obj)\n // Use compact JSON with no extra whitespace\n return JSON.stringify(sortedObj, null, 0)\n}\n\n/**\n * Generates a clean invoice object following MyInvois v1.1 specification exactly\n * This is the base invoice structure WITHOUT signature elements (for hash calculation)\n *\n * Key requirements from working documents:\n * - All mandatory fields must be present\n * - Many optional fields must be present even if empty\n * - Specific field ordering and structure\n * - Correct listID values (e.g., \"3166-1\" not \"ISO3166-1\")\n */\nexport const generateCleanInvoiceObject = (\n invoice: AllDocumentsV1_1,\n): InvoiceSubmission => {\n const lineItems = getLineItems(invoice)\n return {\n // === MANDATORY CORE FIELDS ===\n ID: [{ _: invoice.eInvoiceCodeOrNumber }],\n IssueDate: [{ _: invoice.eInvoiceDate }],\n IssueTime: [{ _: invoice.eInvoiceTime }],\n InvoiceTypeCode: [\n {\n _: invoice.eInvoiceTypeCode,\n listVersionID: invoice.eInvoiceVersion || '1.1',\n },\n ],\n DocumentCurrencyCode: [{ _: invoice.invoiceCurrencyCode }],\n\n // === BILLING REFERENCE (only for credit/debit/refund notes) ===\n ...('originalEInvoiceReferenceNumber' in invoice &&\n invoice.originalEInvoiceReferenceNumber\n ? {\n BillingReference: [\n {\n InvoiceDocumentReference: [\n {\n UUID: [\n {\n _: invoice.originalEInvoiceReferenceNumber,\n },\n ],\n ID: [\n {\n _: invoice.eInvoiceCodeOrNumber,\n },\n ],\n },\n ],\n },\n ],\n }\n : {}),\n\n // === SUPPLIER PARTY (AccountingSupplierParty) ===\n AccountingSupplierParty: [\n {\n Party: [\n {\n // Industry Classification - required field\n IndustryClassificationCode: [\n {\n _: invoice.supplier.industryClassificationCode,\n name: invoice.supplier.industryClassificationDescription,\n },\n ],\n\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.supplier.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.supplier.registrationNumber),\n schemeID: invoice.supplier.registrationType || 'NRIC',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.supplier.address.cityName }],\n CountrySubentityCode: [{ _: invoice.supplier.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.supplier.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.supplier.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.supplier.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.supplier.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === BUYER PARTY (AccountingCustomerParty) ===\n AccountingCustomerParty: [\n {\n Party: [\n {\n // Party Identifications\n PartyIdentification: [\n {\n ID: [\n {\n _: invoice.buyer.tin,\n schemeID: 'TIN',\n },\n ],\n },\n {\n ID: [\n {\n _: formatIdValue(invoice.buyer.registrationNumber),\n schemeID: invoice.buyer.registrationType || 'NRIC',\n },\n ],\n },\n {\n ID: [\n {\n _: invoice.buyer.sstRegistrationNumber || 'NA',\n schemeID: 'SST',\n },\n ],\n },\n ],\n\n // Postal Address - FIXED listID format\n PostalAddress: [\n {\n CityName: [{ _: invoice.buyer.address.cityName }],\n CountrySubentityCode: [{ _: invoice.buyer.address.state }],\n AddressLine: [\n {\n Line: [{ _: invoice.buyer.address.addressLine0 }],\n },\n ],\n Country: [\n {\n IdentificationCode: [\n {\n _: invoice.buyer.address.country || 'MYS',\n listID: '3166-1', // FIXED: was \"ISO3166-1\"\n listAgencyID: 'ISO',\n },\n ],\n },\n ],\n },\n ],\n\n // Party Legal Entity\n PartyLegalEntity: [\n {\n RegistrationName: [{ _: invoice.buyer.name }],\n },\n ],\n\n // Contact Information\n Contact: [\n {\n Telephone: [{ _: invoice.buyer.contactNumber || '' }],\n },\n ],\n },\n ],\n },\n ],\n\n // === TAX TOTAL ===\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n // Generate basic tax subtotal from invoice line items\n {\n TaxableAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: invoice.taxTotal.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxCategory: [\n {\n ID: [{ _: lineItems[0]?.taxType || '01' }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // === LEGAL MONETARY TOTAL ===\n LegalMonetaryTotal: [\n {\n LineExtensionAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxExclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxExclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxInclusiveAmount: [\n {\n _: invoice.legalMonetaryTotal.taxInclusiveAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n PayableAmount: [\n {\n _: invoice.legalMonetaryTotal.payableAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // === INVOICE LINES ===\n InvoiceLine: lineItems.map((item, index) => ({\n ID: [{ _: (index + 1).toString() }],\n\n // Item Information\n Item: [\n {\n CommodityClassification: [\n {\n ItemClassificationCode: [\n {\n _: item.itemClassificationCode,\n listID: 'CLASS',\n },\n ],\n },\n ],\n Description: [{ _: item.itemDescription }],\n },\n ],\n\n ItemPriceExtension: [\n {\n Amount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n LineExtensionAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n\n // Price Information\n Price: [\n {\n PriceAmount: [\n {\n _: item.unitPrice,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n },\n ],\n\n // Tax Information for line\n TaxTotal: [\n {\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxSubtotal: [\n {\n TaxableAmount: [\n {\n _: item.totalTaxableAmountPerLine,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n TaxAmount: [\n {\n _: item.taxAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n // Conditional tax fields based on taxation type\n ...(item.taxPerUnitAmount !== undefined &&\n item.baseUnitMeasure !== undefined\n ? {\n // Fixed Rate Taxation\n PerUnitAmount: [\n {\n _: item.taxPerUnitAmount,\n currencyID: invoice.invoiceCurrencyCode,\n },\n ],\n BaseUnitMeasure: [\n {\n _: item.baseUnitMeasure,\n unitCode: item.baseUnitMeasureCode || 'C62',\n },\n ],\n }\n : item.taxRate !== undefined\n ? {\n // Percentage Taxation\n Percent: [{ _: item.taxRate }],\n }\n : {}),\n TaxCategory: [\n {\n ID: [{ _: item.taxType }],\n TaxScheme: [\n {\n ID: [\n {\n _: 'OTH',\n schemeAgencyID: '6',\n schemeID: 'UN/ECE 5153',\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n })),\n\n // === TAX EXCHANGE RATE (mandatory where applicable) ===\n TaxExchangeRate: invoice.currencyExchangeRate\n ? [\n {\n SourceCurrencyCode: [\n {\n _: invoice.invoiceCurrencyCode,\n },\n ],\n TargetCurrencyCode: [\n {\n _: 'MYR',\n },\n ],\n CalculationRate: [\n {\n _: invoice.currencyExchangeRate,\n },\n ],\n },\n ]\n : undefined,\n }\n}\n\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport const generateCleanUBLDocument = (\n invoices: AllDocumentsV1_1[],\n): UBLDocument => {\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: invoices.map(generateCleanInvoiceObject),\n }\n}\n\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport const calculateDocumentDigest = (\n invoices: AllDocumentsV1_1[],\n): string => {\n // Generate clean UBL document structure\n const cleanDocument = generateCleanUBLDocument(invoices)\n\n // CRITICAL FIX: Remove UBLExtensions and Signature from each invoice before hashing\n const documentForHashing = JSON.parse(JSON.stringify(cleanDocument))\n if (documentForHashing.Invoice && Array.isArray(documentForHashing.Invoice)) {\n documentForHashing.Invoice.forEach((invoice: any) => {\n delete invoice.UBLExtensions\n delete invoice.Signature\n })\n }\n\n // Convert to string for hashing (no canonicalization - use direct JSON.stringify)\n const documentString = JSON.stringify(documentForHashing)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(documentString, 'utf8')\n\n // Return as Base64 (DocDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n */\nexport const calculateCertificateDigest = (certificatePem: string): string => {\n // Extract certificate content (Base64 without PEM headers/footers)\n const certificateContent = certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '') // Remove all whitespace\n\n // Convert Base64 to binary\n const certificateBinary = Buffer.from(certificateContent, 'base64')\n\n // Calculate SHA-256 hash of binary content\n const hash = crypto.createHash('sha256')\n hash.update(certificateBinary)\n\n // Return as Base64\n return hash.digest('base64')\n}\n\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport const extractCertificateInfo = (\n certificatePem: string,\n): {\n issuerName: string\n serialNumber: string\n subjectName: string\n} => {\n try {\n const cert = new X509Certificate(certificatePem)\n\n // Extract serial number and convert to decimal string\n const serialNumberHex = cert.serialNumber\n\n // ENHANCED: Normalize distinguished name format (DS326)\n // Ensures MyInvois portal compatibility for X509IssuerName matching\n const normalizeDistinguishedName = (dn: string): string => {\n // Convert multi-line format to comma-separated RFC2253 format\n const normalized = dn\n .split('\\n')\n .map(line => line.trim())\n .filter(line => line.length > 0)\n .join(', ')\n\n // MyInvois-specific normalization to prevent DS326 errors\n return normalized\n .replace(/\\s*=\\s*/g, '=') // Remove spaces around equals (CRITICAL for portal)\n .replace(/,\\s+/g, ', ') // Ensure single space after commas\n .replace(/\\r/g, '') // Remove any carriage returns\n .replace(/\\s{2,}/g, ' ') // Replace multiple spaces with single space\n .trim() // Remove leading/trailing whitespace\n }\n\n // Enhanced serial number formatting\n const formatSerialNumber = (serialHex: string): string => {\n // Convert hex to decimal and ensure it's a string\n const decimal = BigInt('0x' + serialHex).toString()\n return decimal\n }\n\n return {\n issuerName: normalizeDistinguishedName(cert.issuer),\n serialNumber: formatSerialNumber(serialNumberHex),\n subjectName: normalizeDistinguishedName(cert.subject),\n }\n } catch (error: unknown) {\n throw new Error(\n `Failed to extract certificate info: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Step 5: Create SignedProperties with enhanced structure\n * FIXED: Simplified structure to match MyInvois expectations (DS320)\n * Following MyInvois JSON signature specification exactly\n */\nexport const createSignedProperties = (\n certificateDigest: string,\n signingTime: string,\n issuerName: string,\n serialNumber: string,\n): SignedPropertiesObject => {\n return {\n SignedProperties: [\n {\n Id: 'id-xades-signed-props',\n SignedSignatureProperties: [\n {\n SigningTime: [{ _: signingTime }],\n SigningCertificate: [\n {\n Cert: [\n {\n CertDigest: [\n {\n DigestMethod: [\n {\n Algorithm:\n 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: certificateDigest }],\n },\n ],\n IssuerSerial: [\n {\n X509IssuerName: [{ _: issuerName }],\n X509SerialNumber: [{ _: serialNumber }],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n }\n}\n\n/**\n * Step 6: Calculate SignedProperties Digest\n * FIXED: Add Target wrapper and use direct JSON stringify (DS320)\n * Based on working implementation pattern\n */\nexport const calculateSignedPropertiesDigest = (\n signedProperties: SignedPropertiesObject,\n): string => {\n // According to XAdES, the digest applies ONLY to the <SignedProperties> element\n // (the element whose Id equals 'id-xades-signed-props'). It must NOT include\n // the surrounding <QualifyingProperties> wrapper and its Target attribute.\n\n // Therefore, we hash the exact JSON representation that ends up inside\n // QualifyingProperties – i.e. the SignedProperties array structure itself.\n\n const signedPropertiesString = canonicalizeJSON(signedProperties)\n\n // Calculate SHA-256 hash\n const hash = crypto.createHash('sha256')\n hash.update(signedPropertiesString, 'utf8')\n\n // Return as Base64 (PropsDigest)\n return hash.digest('base64')\n}\n\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport const createSignedInfoAndSign = (\n docDigest: string,\n propsDigest: string,\n privateKeyPem: string,\n): { signedInfo: SignedInfoObject; signatureValue: string } => {\n // Create SignedInfo structure following specification exactly\n const signedInfo = {\n CanonicalizationMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2006/12/xml-c14n11',\n },\n ],\n SignatureMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmldsig-more#rsa-sha256',\n },\n ],\n Reference: [\n {\n Id: 'id-doc-signed-data',\n Type: '',\n URI: '',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: docDigest }],\n },\n {\n Id: 'id-xades-signed-props',\n Type: 'http://uri.etsi.org/01903/v1.3.2#SignedProperties',\n URI: '#id-xades-signed-props',\n DigestMethod: [\n {\n _: '',\n Algorithm: 'http://www.w3.org/2001/04/xmlenc#sha256',\n },\n ],\n DigestValue: [{ _: propsDigest }],\n },\n ],\n }\n\n // FIXED: Use direct JSON.stringify instead of canonicalization (DS333)\n // Based on working implementation pattern\n const signedInfoString = JSON.stringify(signedInfo)\n\n // Sign with RSA-SHA256 directly (RSA-SHA256 handles hashing internally)\n // FIXED: Removed double-hashing bug that was causing DS333 errors\n try {\n const signer = crypto.createSign('RSA-SHA256')\n signer.update(signedInfoString, 'utf8')\n const signatureValue = signer.sign(privateKeyPem, 'base64')\n\n return { signedInfo, signatureValue }\n } catch (error) {\n throw new Error(\n `Signature generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport const generateCompleteDocument = (\n invoices: AllDocumentsV1_1[],\n signingCredentials: SigningCredentials,\n): CompleteInvoice => {\n try {\n // Step 1: Generate clean document (done in calculateDocumentDigest)\n // Step 2: Calculate document digest\n const docDigest = calculateDocumentDigest(invoices)\n\n // Generate signing time in proper ISO format\n const signingTime = new Date().toISOString()\n\n // Extract certificate information (enhanced)\n const certInfo = extractCertificateInfo(signingCredentials.certificatePem)\n\n // Step 4: Calculate certificate digest\n const certificateDigest = calculateCertificateDigest(\n signingCredentials.certificatePem,\n )\n\n // Step 5: Create SignedProperties using extracted cert info\n const signedProperties = createSignedProperties(\n certificateDigest,\n signingTime,\n certInfo.issuerName,\n certInfo.serialNumber,\n )\n\n // Step 6: Calculate SignedProperties digest\n const propsDigest = calculateSignedPropertiesDigest(signedProperties)\n\n // Step 3: Create SignedInfo and generate signature\n const { signedInfo, signatureValue } = createSignedInfoAndSign(\n docDigest,\n propsDigest,\n signingCredentials.privateKeyPem,\n )\n\n // Extract certificate content (Base64 without PEM headers)\n const certificate = signingCredentials.certificatePem\n .replace(/-----BEGIN CERTIFICATE-----/g, '')\n .replace(/-----END CERTIFICATE-----/g, '')\n .replace(/\\s+/g, '')\n\n // Step 7: Create final signed document\n const signedInvoices = invoices.map(invoice => {\n const cleanInvoice = generateCleanInvoiceObject(invoice)\n\n return {\n ...cleanInvoice,\n\n // Add UBLExtensions with complete signature structure\n UBLExtensions: [\n {\n UBLExtension: [\n {\n ExtensionURI: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n ExtensionContent: [\n {\n UBLDocumentSignatures: [\n {\n SignatureInformation: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:1',\n },\n ],\n ReferencedSignatureID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n Signature: [\n {\n Id: 'signature',\n Object: [\n {\n QualifyingProperties: [\n {\n Target: 'signature',\n SignedProperties:\n signedProperties.SignedProperties,\n },\n ],\n },\n ],\n KeyInfo: [\n {\n X509Data: [\n {\n X509Certificate: [{ _: certificate }],\n X509SubjectName: [\n { _: certInfo.subjectName },\n ],\n X509IssuerSerial: [\n {\n X509IssuerName: [\n {\n _: certInfo.issuerName,\n },\n ],\n X509SerialNumber: [\n {\n _: certInfo.serialNumber,\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n SignatureValue: [{ _: signatureValue }],\n SignedInfo: [signedInfo],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n },\n ],\n\n // Add simple Signature reference\n Signature: [\n {\n ID: [\n {\n _: 'urn:oasis:names:specification:ubl:signature:Invoice',\n },\n ],\n SignatureMethod: [\n {\n _: 'urn:oasis:names:specification:ubl:dsig:enveloped:xades',\n },\n ],\n },\n ],\n }\n })\n\n return {\n _D: 'urn:oasis:names:specification:ubl:schema:xsd:Invoice-2',\n _A: 'urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2',\n _B: 'urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2',\n Invoice: signedInvoices,\n }\n } catch (error) {\n throw new Error(\n `Document generation failed: ${error instanceof Error ? error.message : String(error)}`,\n )\n }\n}\n\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport const createPercentageTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxRate: number\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = (totalTaxableAmount * params.taxRate) / 100\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxRate: params.taxRate,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport const createFixedRateTaxLineItem = (params: {\n itemClassificationCode: ClassificationCode\n itemDescription: string\n unitPrice: number\n quantity?: number\n taxType: TaxTypeCode\n taxPerUnitAmount: number\n baseUnitMeasure: number\n baseUnitMeasureCode: UnitTypeCode\n totalTaxableAmountPerLine?: number\n}): InvoiceLineItem => {\n const quantity = params.quantity || 1\n const totalTaxableAmount =\n params.totalTaxableAmountPerLine || params.unitPrice * quantity\n const taxAmount = params.taxPerUnitAmount * params.baseUnitMeasure\n\n return {\n itemClassificationCode: params.itemClassificationCode,\n itemDescription: params.itemDescription,\n unitPrice: params.unitPrice,\n taxType: params.taxType,\n taxPerUnitAmount: params.taxPerUnitAmount,\n baseUnitMeasure: params.baseUnitMeasure,\n baseUnitMeasureCode: params.baseUnitMeasureCode,\n taxAmount: Math.round(taxAmount * 100) / 100, // Round to 2 decimal places\n totalTaxableAmountPerLine: totalTaxableAmount,\n totalAmountPerLine: totalTaxableAmount + taxAmount,\n }\n}\n\n/**\n * Calculates invoice totals from line items\n */\nexport const calculateInvoiceTotals = (\n lineItems: InvoiceLineItem[],\n): {\n legalMonetaryTotal: {\n taxExclusiveAmount: number\n taxInclusiveAmount: number\n payableAmount: number\n }\n taxTotal: {\n taxAmount: number\n }\n} => {\n const taxExclusiveAmount = lineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const totalTaxAmount = lineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n const taxInclusiveAmount = taxExclusiveAmount + totalTaxAmount\n\n return {\n legalMonetaryTotal: {\n taxExclusiveAmount: Math.round(taxExclusiveAmount * 100) / 100,\n taxInclusiveAmount: Math.round(taxInclusiveAmount * 100) / 100,\n payableAmount: Math.round(taxInclusiveAmount * 100) / 100,\n },\n taxTotal: {\n taxAmount: Math.round(totalTaxAmount * 100) / 100,\n },\n }\n}\n"],"mappings":";;;;;;;;;;;;;AAyBA,MAAa,iBAAiB,CAACA,SAAmC;AAChE,QACE,KAAK,+BAAkC,KAAK;AAE/C;;;;AAKD,MAAa,kBAAkB,CAACA,SAAmC;AACjE,QAAO,KAAK,uBAA0B,eAAe,KAAK;AAC3D;;;;AAKD,MAAa,6BAA6B,CAACA,SAAkC;AAC3E,KAAI,eAAe,KAAK,CACtB,QAAO,KAAK,mBAAoB,KAAK;UAC5B,gBAAgB,KAAK,CAC9B,QAAQ,KAAK,4BAA4B,KAAK,UAAY;AAE5D,QAAO;AACR;;;;AAKD,MAAM,eAAe,CAACC,QAA6C;AACjE,KAAI,sBAAsB,IAAK,QAAO,IAAI;AAC1C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,wBAAwB,IAAK,QAAO,IAAI;AAC5C,KAAI,yBAAyB,IAAK,QAAO,IAAI;AAC7C,KAAI,mCAAmC,IACrC,QAAO,IAAI;AACb,KAAI,mCAAmC,IACrC,QAAO,IAAI;AAEb,QAAO,CAAE;AACV;;;;AAKD,SAAgB,eAAeC,KAAuB;AACpD,KAAI,QAAQ,eAAe,QAAQ,SACjC,QAAO;AAGT,KAA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6B,OAAO,YAAY;CACzD,MAAM,YAAY,OAAO,mBAAmB,OAAO;AAEnD,QAAO;EACL,wBAAwB,OAAO;EAC/B,iBAAiB,OAAO;EACxB,WAAW,OAAO;EAClB,SAAS,OAAO;EAChB,kBAAkB,OAAO;EACzB,iBAAiB,OAAO;EACxB,qBAAqB,OAAO;EAC5B,WAAW,KAAK,MAAM,YAAY,IAAI,GAAG;EACzC,2BAA2B;EAC3B,oBAAoB,qBAAqB;CAC1C;AACF;;;;AAKD,MAAa,yBAAyB,CACpCC,cAUG;CACH,MAAM,qBAAqB,UAAU,OACnC,CAAC,KAAK,SAAS,MAAM,KAAK,2BAC1B,EACD;CACD,MAAM,iBAAiB,UAAU,OAC/B,CAAC,KAAK,SAAS,MAAM,KAAK,WAC1B,EACD;CACD,MAAM,qBAAqB,qBAAqB;AAEhD,QAAO;EACL,oBAAoB;GAClB,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,oBAAoB,KAAK,MAAM,qBAAqB,IAAI,GAAG;GAC3D,eAAe,KAAK,MAAM,qBAAqB,IAAI,GAAG;EACvD;EACD,UAAU,EACR,WAAW,KAAK,MAAM,iBAAiB,IAAI,GAAG,IAC/C;CACF;AACF"}
|
|
@@ -334,11 +334,7 @@ const createSignedProperties = (certificateDigest, signingTime, issuerName, seri
|
|
|
334
334
|
* Based on working implementation pattern
|
|
335
335
|
*/
|
|
336
336
|
const calculateSignedPropertiesDigest = (signedProperties) => {
|
|
337
|
-
const
|
|
338
|
-
Target: "signature",
|
|
339
|
-
SignedProperties: signedProperties.SignedProperties
|
|
340
|
-
};
|
|
341
|
-
const signedPropertiesString = JSON.stringify(signedPropertiesWithTarget);
|
|
337
|
+
const signedPropertiesString = canonicalizeJSON(signedProperties);
|
|
342
338
|
const hash = crypto.createHash("sha256");
|
|
343
339
|
hash.update(signedPropertiesString, "utf8");
|
|
344
340
|
return hash.digest("base64");
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_document = require('./document-
|
|
1
|
+
const require_document = require('./document-CiBQaJ0c.cjs');
|
|
2
2
|
|
|
3
3
|
//#region src/api/documentSubmission.ts
|
|
4
4
|
async function submitDocument(context, documents) {
|
|
@@ -145,4 +145,4 @@ Object.defineProperty(exports, 'submitDocument', {
|
|
|
145
145
|
return submitDocument;
|
|
146
146
|
}
|
|
147
147
|
});
|
|
148
|
-
//# sourceMappingURL=documentSubmission-
|
|
148
|
+
//# sourceMappingURL=documentSubmission-DG5pfaBQ.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"documentSubmission-CZvD4VVN.cjs","names":["context: SubmissionContext","documents: AllDocumentsV1_1[]","context: Pick<SubmissionContext, 'fetch' | 'debug'>","submissionUid: string","pollInterval: number","maxRetries: number","documentUid: string","status: 'rejected' | 'cancelled'","reason: string"],"sources":["../src/api/documentSubmission.ts"],"sourcesContent":["import type {\n AllDocumentsV1_1,\n SubmissionResponse,\n SigningCredentials,\n SubmissionStatus,\n DocumentSummary,\n Fetch,\n StandardError,\n} from '../types'\nimport { generateCompleteDocument } from '../utils/document'\n\ninterface SubmissionContext {\n fetch: Fetch\n debug: boolean\n signingCredentials: SigningCredentials\n}\n\nexport async function submitDocument(\n context: SubmissionContext,\n documents: AllDocumentsV1_1[],\n): Promise<{\n data: SubmissionResponse\n status: number\n}> {\n const { fetch, debug, signingCredentials } = context\n\n // 🔒 Hard enforcement of platform submission limits\n if (documents.length > 100) {\n throw new Error(\n 'Submission rejected: Cannot submit more than 100 documents at once',\n )\n }\n\n if (debug) {\n console.log(`📦 Preparing to submit ${documents.length} document(s)...`)\n }\n\n // For batch submission, each document must be signed and encoded separately\n // Build the submission payload according to MyInvois API format\n const crypto = await import('crypto')\n\n const submissionPayload = {\n documents: await Promise.all(\n documents.map(async doc => {\n // 1️⃣ Sign the single document (generateCompleteDocument expects an array)\n const signedDocument = generateCompleteDocument(\n [doc],\n signingCredentials,\n )\n\n // 2️⃣ Serialize\n const docJson = JSON.stringify(signedDocument)\n\n // 3️⃣ Hash\n const docHash = crypto\n .createHash('sha256')\n .update(docJson, 'utf8')\n .digest('hex')\n\n // 4️⃣ Base64 encode\n const docBase64 = Buffer.from(docJson, 'utf8').toString('base64')\n\n // 🚨 Enforce 300 KB per-document limit\n const rawSize = Buffer.byteLength(docBase64, 'base64')\n if (rawSize > 300 * 1024) {\n throw new Error(\n `Submission rejected: Document ${doc.eInvoiceCodeOrNumber} is ${rawSize} bytes – exceeds 300KB limit`,\n )\n }\n\n if (debug) {\n console.log('—'.repeat(60))\n console.log(`📄 Prepared document: ${doc.eInvoiceCodeOrNumber}`)\n console.log(` • JSON size : ${docJson.length} bytes`)\n console.log(` • Base64 size: ${docBase64.length} bytes`)\n }\n\n return {\n format: 'JSON',\n document: docBase64,\n documentHash: docHash,\n codeNumber: doc.eInvoiceCodeOrNumber,\n }\n }),\n ),\n }\n\n const payloadSize = Buffer.byteLength(JSON.stringify(submissionPayload))\n\n if (payloadSize > 5 * 1024 * 1024) {\n throw new Error(\n `Submission rejected: Payload is ${payloadSize} bytes – exceeds 5MB limit`,\n )\n }\n\n if (debug) {\n console.log('🚀 Submission payload structure:')\n console.log('- Format: JSON')\n console.log('- Documents count:', submissionPayload.documents.length)\n console.log('- Total payload size:', payloadSize, 'bytes')\n }\n\n // Submit to MyInvois API with proper headers\n const response = await fetch('/api/v1.0/documentsubmissions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(submissionPayload),\n })\n\n const responseData = (await response.json()) as SubmissionResponse\n\n if (debug) {\n console.log(`📡 API Response status: ${response.status}`)\n\n if (responseData.rejectedDocuments?.length > 0) {\n responseData.rejectedDocuments.forEach((doc, index) => {\n console.log(` Document ${index + 1}:`, doc.invoiceCodeNumber)\n if (doc.error) {\n console.log(` Error:`, doc.error.message)\n if (doc.error.details) {\n doc.error.details.forEach((detail, detailIndex) => {\n console.log(` Detail ${detailIndex + 1}:`, detail.message)\n })\n }\n }\n })\n }\n }\n\n const data = responseData as SubmissionResponse\n\n if (debug) {\n if (response.status !== 202) {\n console.error('❌ Submission failed with status:', response.status)\n console.error('❌ Response data:', JSON.stringify(data, null, 2))\n } else {\n console.log('✅ Submission successful!')\n console.log(`📋 Submission UID: ${data.submissionUid}`)\n console.log(\n `✅ Accepted documents: ${data.acceptedDocuments?.length || 0}`,\n )\n console.log(\n `❌ Rejected documents: ${data.rejectedDocuments?.length || 0}`,\n )\n }\n }\n\n return {\n data,\n status: response.status,\n }\n}\n\nexport async function getSubmissionStatus(\n context: Pick<SubmissionContext, 'fetch' | 'debug'>,\n submissionUid: string,\n pollInterval: number = 1000,\n maxRetries: number = 10,\n): Promise<{\n status: SubmissionStatus\n documentSummary?: DocumentSummary[]\n error?: {\n code: string\n message: string | null\n target: string\n details: {\n code: string\n message: string\n target: string\n }[]\n }\n}> {\n const { fetch, debug } = context\n\n try {\n const response = await fetch(\n `/api/v1.0/documentsubmissions/${submissionUid}`,\n )\n\n const data = await response.json()\n\n if (debug) {\n console.log('Submission:', data)\n if (data.error) {\n console.log('Submission error details:', data.error.details)\n }\n }\n\n // If we have a successful response and status is completed, return success\n if (data.overallStatus === 'Valid') {\n return {\n status: data.overallStatus,\n documentSummary: data.documentSummary,\n }\n }\n if (data.overallStatus === 'Invalid') {\n return {\n status: 'Invalid',\n documentSummary: data.documentSummary,\n }\n }\n\n // If we have retries left, continue polling for any non-completed status or errors\n if (maxRetries > 0) {\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out',\n target: 'submission',\n details: [],\n },\n }\n } catch (error) {\n // Handle any request errors by retrying if we have retries left\n if (maxRetries > 0) {\n if (debug) {\n console.log('Request error, retrying...', error)\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out after request errors',\n target: 'submission',\n details: [],\n },\n }\n }\n}\n\nexport async function performDocumentAction(\n documentUid: string,\n status: 'rejected' | 'cancelled',\n reason: string,\n): Promise<{\n uuid: string\n status: string\n error: StandardError\n}> {\n const response = await fetch(\n `/api/v1.0/documents/state/${documentUid}/state`,\n {\n method: 'POST',\n body: JSON.stringify({\n status,\n reason,\n }),\n },\n )\n\n const data = (await response.json()) as {\n uuid: string\n status: string\n error: StandardError\n }\n\n return data\n}\n"],"mappings":";;;AAiBA,eAAsB,eACpBA,SACAC,WAIC;CACD,MAAM,EAAE,gBAAO,OAAO,oBAAoB,GAAG;AAG7C,KAAI,UAAU,SAAS,IACrB,OAAM,IAAI,MACR;AAIJ,KAAI,MACF,SAAQ,KAAK,yBAAyB,UAAU,OAAO,iBAAiB;CAK1E,MAAM,SAAS,MAAM,OAAO;CAE5B,MAAM,oBAAoB,EACxB,WAAW,MAAM,QAAQ,IACvB,UAAU,IAAI,OAAM,QAAO;EAEzB,MAAM,iBAAiB,0CACrB,CAAC,GAAI,GACL,mBACD;EAGD,MAAM,UAAU,KAAK,UAAU,eAAe;EAG9C,MAAM,UAAU,OACb,WAAW,SAAS,CACpB,OAAO,SAAS,OAAO,CACvB,OAAO,MAAM;EAGhB,MAAM,YAAY,OAAO,KAAK,SAAS,OAAO,CAAC,SAAS,SAAS;EAGjE,MAAM,UAAU,OAAO,WAAW,WAAW,SAAS;AACtD,MAAI,UAAU,MAAM,KAClB,OAAM,IAAI,OACP,gCAAgC,IAAI,qBAAqB,MAAM,QAAQ;AAI5E,MAAI,OAAO;AACT,WAAQ,IAAI,IAAI,OAAO,GAAG,CAAC;AAC3B,WAAQ,KAAK,wBAAwB,IAAI,qBAAqB,EAAE;AAChE,WAAQ,KAAK,mBAAmB,QAAQ,OAAO,QAAQ;AACvD,WAAQ,KAAK,oBAAoB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C;CACD,MAAM,WAAW,MAAM,OACpB,4BAA4B,YAAY,SACzC;EACE,QAAQ;EACR,MAAM,KAAK,UAAU;GACnB;GACA;EACD,EAAC;CACH,EACF;CAED,MAAM,OAAQ,MAAM,SAAS,MAAM;AAMnC,QAAO;AACR"}
|
|
1
|
+
{"version":3,"file":"documentSubmission-DG5pfaBQ.cjs","names":["context: SubmissionContext","documents: AllDocumentsV1_1[]","context: Pick<SubmissionContext, 'fetch' | 'debug'>","submissionUid: string","pollInterval: number","maxRetries: number","documentUid: string","status: 'rejected' | 'cancelled'","reason: string"],"sources":["../src/api/documentSubmission.ts"],"sourcesContent":["import type {\n AllDocumentsV1_1,\n SubmissionResponse,\n SigningCredentials,\n SubmissionStatus,\n DocumentSummary,\n Fetch,\n StandardError,\n} from '../types'\nimport { generateCompleteDocument } from '../utils/document'\n\ninterface SubmissionContext {\n fetch: Fetch\n debug: boolean\n signingCredentials: SigningCredentials\n}\n\nexport async function submitDocument(\n context: SubmissionContext,\n documents: AllDocumentsV1_1[],\n): Promise<{\n data: SubmissionResponse\n status: number\n}> {\n const { fetch, debug, signingCredentials } = context\n\n // 🔒 Hard enforcement of platform submission limits\n if (documents.length > 100) {\n throw new Error(\n 'Submission rejected: Cannot submit more than 100 documents at once',\n )\n }\n\n if (debug) {\n console.log(`📦 Preparing to submit ${documents.length} document(s)...`)\n }\n\n // For batch submission, each document must be signed and encoded separately\n // Build the submission payload according to MyInvois API format\n const crypto = await import('crypto')\n\n const submissionPayload = {\n documents: await Promise.all(\n documents.map(async doc => {\n // 1️⃣ Sign the single document (generateCompleteDocument expects an array)\n const signedDocument = generateCompleteDocument(\n [doc],\n signingCredentials,\n )\n\n // 2️⃣ Serialize\n const docJson = JSON.stringify(signedDocument)\n\n // 3️⃣ Hash\n const docHash = crypto\n .createHash('sha256')\n .update(docJson, 'utf8')\n .digest('hex')\n\n // 4️⃣ Base64 encode\n const docBase64 = Buffer.from(docJson, 'utf8').toString('base64')\n\n // 🚨 Enforce 300 KB per-document limit\n const rawSize = Buffer.byteLength(docBase64, 'base64')\n if (rawSize > 300 * 1024) {\n throw new Error(\n `Submission rejected: Document ${doc.eInvoiceCodeOrNumber} is ${rawSize} bytes – exceeds 300KB limit`,\n )\n }\n\n if (debug) {\n console.log('—'.repeat(60))\n console.log(`📄 Prepared document: ${doc.eInvoiceCodeOrNumber}`)\n console.log(` • JSON size : ${docJson.length} bytes`)\n console.log(` • Base64 size: ${docBase64.length} bytes`)\n }\n\n return {\n format: 'JSON',\n document: docBase64,\n documentHash: docHash,\n codeNumber: doc.eInvoiceCodeOrNumber,\n }\n }),\n ),\n }\n\n const payloadSize = Buffer.byteLength(JSON.stringify(submissionPayload))\n\n if (payloadSize > 5 * 1024 * 1024) {\n throw new Error(\n `Submission rejected: Payload is ${payloadSize} bytes – exceeds 5MB limit`,\n )\n }\n\n if (debug) {\n console.log('🚀 Submission payload structure:')\n console.log('- Format: JSON')\n console.log('- Documents count:', submissionPayload.documents.length)\n console.log('- Total payload size:', payloadSize, 'bytes')\n }\n\n // Submit to MyInvois API with proper headers\n const response = await fetch('/api/v1.0/documentsubmissions', {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(submissionPayload),\n })\n\n const responseData = (await response.json()) as SubmissionResponse\n\n if (debug) {\n console.log(`📡 API Response status: ${response.status}`)\n\n if (responseData.rejectedDocuments?.length > 0) {\n responseData.rejectedDocuments.forEach((doc, index) => {\n console.log(` Document ${index + 1}:`, doc.invoiceCodeNumber)\n if (doc.error) {\n console.log(` Error:`, doc.error.message)\n if (doc.error.details) {\n doc.error.details.forEach((detail, detailIndex) => {\n console.log(` Detail ${detailIndex + 1}:`, detail.message)\n })\n }\n }\n })\n }\n }\n\n const data = responseData as SubmissionResponse\n\n if (debug) {\n if (response.status !== 202) {\n console.error('❌ Submission failed with status:', response.status)\n console.error('❌ Response data:', JSON.stringify(data, null, 2))\n } else {\n console.log('✅ Submission successful!')\n console.log(`📋 Submission UID: ${data.submissionUid}`)\n console.log(\n `✅ Accepted documents: ${data.acceptedDocuments?.length || 0}`,\n )\n console.log(\n `❌ Rejected documents: ${data.rejectedDocuments?.length || 0}`,\n )\n }\n }\n\n return {\n data,\n status: response.status,\n }\n}\n\nexport async function getSubmissionStatus(\n context: Pick<SubmissionContext, 'fetch' | 'debug'>,\n submissionUid: string,\n pollInterval: number = 1000,\n maxRetries: number = 10,\n): Promise<{\n status: SubmissionStatus\n documentSummary?: DocumentSummary[]\n error?: {\n code: string\n message: string | null\n target: string\n details: {\n code: string\n message: string\n target: string\n }[]\n }\n}> {\n const { fetch, debug } = context\n\n try {\n const response = await fetch(\n `/api/v1.0/documentsubmissions/${submissionUid}`,\n )\n\n const data = await response.json()\n\n if (debug) {\n console.log('Submission:', data)\n if (data.error) {\n console.log('Submission error details:', data.error.details)\n }\n }\n\n // If we have a successful response and status is completed, return success\n if (data.overallStatus === 'Valid') {\n return {\n status: data.overallStatus,\n documentSummary: data.documentSummary,\n }\n }\n if (data.overallStatus === 'Invalid') {\n return {\n status: 'Invalid',\n documentSummary: data.documentSummary,\n }\n }\n\n // If we have retries left, continue polling for any non-completed status or errors\n if (maxRetries > 0) {\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out',\n target: 'submission',\n details: [],\n },\n }\n } catch (error) {\n // Handle any request errors by retrying if we have retries left\n if (maxRetries > 0) {\n if (debug) {\n console.log('Request error, retrying...', error)\n }\n await new Promise(resolve => setTimeout(resolve, pollInterval))\n return await getSubmissionStatus(\n context,\n submissionUid,\n pollInterval,\n maxRetries - 1,\n )\n }\n\n // No retries left - return timeout\n return {\n status: 'Invalid',\n error: {\n code: 'Timeout',\n message: 'Submission timed out after request errors',\n target: 'submission',\n details: [],\n },\n }\n }\n}\n\nexport async function performDocumentAction(\n documentUid: string,\n status: 'rejected' | 'cancelled',\n reason: string,\n): Promise<{\n uuid: string\n status: string\n error: StandardError\n}> {\n const response = await fetch(\n `/api/v1.0/documents/state/${documentUid}/state`,\n {\n method: 'POST',\n body: JSON.stringify({\n status,\n reason,\n }),\n },\n )\n\n const data = (await response.json()) as {\n uuid: string\n status: string\n error: StandardError\n }\n\n return data\n}\n"],"mappings":";;;AAiBA,eAAsB,eACpBA,SACAC,WAIC;CACD,MAAM,EAAE,gBAAO,OAAO,oBAAoB,GAAG;AAG7C,KAAI,UAAU,SAAS,IACrB,OAAM,IAAI,MACR;AAIJ,KAAI,MACF,SAAQ,KAAK,yBAAyB,UAAU,OAAO,iBAAiB;CAK1E,MAAM,SAAS,MAAM,OAAO;CAE5B,MAAM,oBAAoB,EACxB,WAAW,MAAM,QAAQ,IACvB,UAAU,IAAI,OAAM,QAAO;EAEzB,MAAM,iBAAiB,0CACrB,CAAC,GAAI,GACL,mBACD;EAGD,MAAM,UAAU,KAAK,UAAU,eAAe;EAG9C,MAAM,UAAU,OACb,WAAW,SAAS,CACpB,OAAO,SAAS,OAAO,CACvB,OAAO,MAAM;EAGhB,MAAM,YAAY,OAAO,KAAK,SAAS,OAAO,CAAC,SAAS,SAAS;EAGjE,MAAM,UAAU,OAAO,WAAW,WAAW,SAAS;AACtD,MAAI,UAAU,MAAM,KAClB,OAAM,IAAI,OACP,gCAAgC,IAAI,qBAAqB,MAAM,QAAQ;AAI5E,MAAI,OAAO;AACT,WAAQ,IAAI,IAAI,OAAO,GAAG,CAAC;AAC3B,WAAQ,KAAK,wBAAwB,IAAI,qBAAqB,EAAE;AAChE,WAAQ,KAAK,mBAAmB,QAAQ,OAAO,QAAQ;AACvD,WAAQ,KAAK,oBAAoB,UAAU,OAAO,QAAQ;EAC3D;AAED,SAAO;GACL,QAAQ;GACR,UAAU;GACV,cAAc;GACd,YAAY,IAAI;EACjB;CACF,EAAC,CACH,CACF;CAED,MAAM,cAAc,OAAO,WAAW,KAAK,UAAU,k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nC,QAAO;AACR"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
const require_documentManagement = require('./documentManagement-DQ7JEcBq.cjs');
|
|
2
2
|
require('./formatIdValue-i67o4kyD.cjs');
|
|
3
|
-
require('./document-
|
|
4
|
-
const require_documentSubmission = require('./documentSubmission-
|
|
3
|
+
require('./document-CiBQaJ0c.cjs');
|
|
4
|
+
const require_documentSubmission = require('./documentSubmission-DG5pfaBQ.cjs');
|
|
5
5
|
const require_documentTypeManagement = require('./documentTypeManagement-D_-LiQVg.cjs');
|
|
6
6
|
const require_notificationManagement = require('./notificationManagement-DLBDn77E.cjs');
|
|
7
7
|
const require_platformLogin = require('./platformLogin-Ch6hFKoU.cjs');
|
|
8
8
|
const require_taxpayerValidation = require('./taxpayerValidation-D_jGaVty.cjs');
|
|
9
9
|
const require_certificate = require('./certificate-CWmfCPdt.cjs');
|
|
10
10
|
const require_getBaseUrl = require('./getBaseUrl-D0G4GZmp.cjs');
|
|
11
|
-
const require_apiQueue = require('./apiQueue-
|
|
11
|
+
const require_apiQueue = require('./apiQueue-CRyjAw52.cjs');
|
|
12
12
|
|
|
13
13
|
//#region src/index.ts
|
|
14
14
|
var MyInvoisClient = class MyInvoisClient {
|
package/dist/index.js
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { getDocument, getDocumentDetails, searchDocuments } from "./documentManagement-CIQPkmyb.js";
|
|
2
2
|
import "./formatIdValue-qTxJqj9o.js";
|
|
3
|
-
import "./document-
|
|
4
|
-
import { getSubmissionStatus, performDocumentAction, submitDocument } from "./documentSubmission-
|
|
3
|
+
import "./document-SQQDNoI-.js";
|
|
4
|
+
import { getSubmissionStatus, performDocumentAction, submitDocument } from "./documentSubmission-B45EflkR.js";
|
|
5
5
|
import { getDocumentType, getDocumentTypeVersion, getDocumentTypes } from "./documentTypeManagement-cBtVCOY3.js";
|
|
6
6
|
import { getNotifications } from "./notificationManagement-n4Z5e-My.js";
|
|
7
7
|
import { platformLogin } from "./platformLogin-CqI9OLYP.js";
|
|
8
8
|
import { taxpayerQRCode, tinSearch, verifyTin } from "./taxpayerValidation-y6P-Es0S.js";
|
|
9
9
|
import { extractCertificateInfo, getPemFromP12, validateKeyPair } from "./certificate-COwqszxD.js";
|
|
10
10
|
import { getBaseUrl } from "./getBaseUrl-D7nUmoYb.js";
|
|
11
|
-
import { categorizeRequest, queueRequest } from "./apiQueue-
|
|
11
|
+
import { categorizeRequest, queueRequest } from "./apiQueue-Csh8ru3S.js";
|
|
12
12
|
|
|
13
13
|
//#region src/index.ts
|
|
14
14
|
var MyInvoisClient = class MyInvoisClient {
|
package/dist/index10.cjs
CHANGED
|
@@ -1,5 +1,25 @@
|
|
|
1
|
-
const require_certificate = require('./certificate-CWmfCPdt.cjs');
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
2
|
+
//#region src/types/payment-modes.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Enum representing the allowed payment mode codes with descriptive names.
|
|
5
|
+
* Provides a more readable way to reference payment modes.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const mode = PaymentModeCodeEnum.Cash;
|
|
9
|
+
* console.log(mode); // Output: "01"
|
|
10
|
+
*/
|
|
11
|
+
let PaymentModeCodeEnum = /* @__PURE__ */ function(PaymentModeCodeEnum$1) {
|
|
12
|
+
PaymentModeCodeEnum$1["Cash"] = "01";
|
|
13
|
+
PaymentModeCodeEnum$1["Cheque"] = "02";
|
|
14
|
+
PaymentModeCodeEnum$1["BankTransfer"] = "03";
|
|
15
|
+
PaymentModeCodeEnum$1["CreditCard"] = "04";
|
|
16
|
+
PaymentModeCodeEnum$1["DebitCard"] = "05";
|
|
17
|
+
PaymentModeCodeEnum$1["EWalletDigitalWallet"] = "06";
|
|
18
|
+
PaymentModeCodeEnum$1["DigitalBank"] = "07";
|
|
19
|
+
PaymentModeCodeEnum$1["Others"] = "08";
|
|
20
|
+
return PaymentModeCodeEnum$1;
|
|
21
|
+
}({});
|
|
22
|
+
|
|
23
|
+
//#endregion
|
|
24
|
+
exports.PaymentModeCodeEnum = PaymentModeCodeEnum;
|
|
25
|
+
//# sourceMappingURL=index10.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index10.cjs","names":[],"sources":["../src/types/payment-modes.d.ts"],"sourcesContent":["/**\n * Represents the allowed codes for payment modes.\n * Based on the documentation: https://sdk.myinvois.hasil.gov.my/codes/payment-methods/\n */\nexport type PaymentModeCode =\n | '01' // Cash\n | '02' // Cheque\n | '03' // Bank Transfer\n | '04' // Credit Card\n | '05' // Debit Card\n | '06' // e-Wallet / Digital Wallet\n | '07' // Digital Bank\n | '08' // Others\n\n/**\n * Enum representing the allowed payment mode codes with descriptive names.\n * Provides a more readable way to reference payment modes.\n *\n * @example\n * const mode = PaymentModeCodeEnum.Cash;\n * console.log(mode); // Output: \"01\"\n */\nexport enum PaymentModeCodeEnum {\n Cash = '01',\n Cheque = '02',\n BankTransfer = '03',\n CreditCard = '04',\n DebitCard = '05',\n EWalletDigitalWallet = '06',\n DigitalBank = '07',\n Others = '08',\n}\n\n/**\n * Interface representing a payment mode entry.\n * Contains the code and its corresponding description.\n */\nexport interface PaymentMode {\n code: PaymentModeCode\n description: string\n}\n"],"mappings":";;;;;;;;;;AAsBA,IAAY,sEAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACD"}
|
package/dist/index11.cjs
CHANGED
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
require('./formatIdValue-i67o4kyD.cjs');
|
|
2
|
-
const require_document = require('./document-D7LLOhCD.cjs');
|
|
3
|
-
|
|
4
|
-
exports.calculateCertificateDigest = require_document.calculateCertificateDigest;
|
|
5
|
-
exports.calculateDocumentDigest = require_document.calculateDocumentDigest;
|
|
6
|
-
exports.calculateExpectedTaxAmount = require_document.calculateExpectedTaxAmount;
|
|
7
|
-
exports.calculateInvoiceTotals = require_document.calculateInvoiceTotals;
|
|
8
|
-
exports.calculateSignedPropertiesDigest = require_document.calculateSignedPropertiesDigest;
|
|
9
|
-
exports.canonicalizeJSON = require_document.canonicalizeJSON;
|
|
10
|
-
exports.createFixedRateTaxLineItem = require_document.createFixedRateTaxLineItem;
|
|
11
|
-
exports.createPercentageTaxLineItem = require_document.createPercentageTaxLineItem;
|
|
12
|
-
exports.createSignedInfoAndSign = require_document.createSignedInfoAndSign;
|
|
13
|
-
exports.createSignedProperties = require_document.createSignedProperties;
|
|
14
|
-
exports.extractCertificateInfo = require_document.extractCertificateInfo;
|
|
15
|
-
exports.generateCleanInvoiceObject = require_document.generateCleanInvoiceObject;
|
|
16
|
-
exports.generateCleanUBLDocument = require_document.generateCleanUBLDocument;
|
|
17
|
-
exports.generateCompleteDocument = require_document.generateCompleteDocument;
|
|
18
|
-
exports.isFixedRateTax = require_document.isFixedRateTax;
|
|
19
|
-
exports.isPercentageTax = require_document.isPercentageTax;
|
|
20
|
-
exports.sortObjectKeys = require_document.sortObjectKeys;
|
package/dist/index12.cjs
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
const require_formatIdValue = require('./formatIdValue-i67o4kyD.cjs');
|
|
2
1
|
|
|
3
|
-
|
|
2
|
+
//#region src/types/state-codes.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Enum representing the allowed state codes with descriptive names.
|
|
5
|
+
* Provides a more readable way to reference states.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const code = StateCodeEnum.Selangor;
|
|
9
|
+
* console.log(code); // Output: "10"
|
|
10
|
+
*/
|
|
11
|
+
let StateCodeEnum = /* @__PURE__ */ function(StateCodeEnum$1) {
|
|
12
|
+
StateCodeEnum$1["Johor"] = "01";
|
|
13
|
+
StateCodeEnum$1["Kedah"] = "02";
|
|
14
|
+
StateCodeEnum$1["Kelantan"] = "03";
|
|
15
|
+
StateCodeEnum$1["Melaka"] = "04";
|
|
16
|
+
StateCodeEnum$1["NegeriSembilan"] = "05";
|
|
17
|
+
StateCodeEnum$1["Pahang"] = "06";
|
|
18
|
+
StateCodeEnum$1["PulauPinang"] = "07";
|
|
19
|
+
StateCodeEnum$1["Perak"] = "08";
|
|
20
|
+
StateCodeEnum$1["Perlis"] = "09";
|
|
21
|
+
StateCodeEnum$1["Selangor"] = "10";
|
|
22
|
+
StateCodeEnum$1["Terengganu"] = "11";
|
|
23
|
+
StateCodeEnum$1["Sabah"] = "12";
|
|
24
|
+
StateCodeEnum$1["Sarawak"] = "13";
|
|
25
|
+
StateCodeEnum$1["WPKualaLumpur"] = "14";
|
|
26
|
+
StateCodeEnum$1["WPLabuan"] = "15";
|
|
27
|
+
StateCodeEnum$1["WPPutrajaya"] = "16";
|
|
28
|
+
StateCodeEnum$1["NotApplicable"] = "17";
|
|
29
|
+
return StateCodeEnum$1;
|
|
30
|
+
}({});
|
|
31
|
+
|
|
32
|
+
//#endregion
|
|
33
|
+
exports.StateCodeEnum = StateCodeEnum;
|
|
34
|
+
//# sourceMappingURL=index12.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"
|
|
1
|
+
{"version":3,"file":"index12.cjs","names":[],"sources":["../src/types/state-codes.d.ts"],"sourcesContent":["/**\n * Represents the allowed codes for Malaysian states and federal territories.\n * Based on the documentation: https://sdk.myinvois.hasil.gov.my/codes/state-codes/\n */\nexport type StateCode =\n | '01' // Johor\n | '02' // Kedah\n | '03' // Kelantan\n | '04' // Melaka\n | '05' // Negeri Sembilan\n | '06' // Pahang\n | '07' // Pulau Pinang\n | '08' // Perak\n | '09' // Perlis\n | '10' // Selangor\n | '11' // Terengganu\n | '12' // Sabah\n | '13' // Sarawak\n | '14' // Wilayah Persekutuan Kuala Lumpur\n | '15' // Wilayah Persekutuan Labuan\n | '16' // Wilayah Persekutuan Putrajaya\n | '17' // Not Applicable\n\n/**\n * Enum representing the allowed state codes with descriptive names.\n * Provides a more readable way to reference states.\n *\n * @example\n * const code = StateCodeEnum.Selangor;\n * console.log(code); // Output: \"10\"\n */\nexport enum StateCodeEnum {\n Johor = '01',\n Kedah = '02',\n Kelantan = '03',\n Melaka = '04',\n NegeriSembilan = '05',\n Pahang = '06',\n PulauPinang = '07',\n Perak = '08',\n Perlis = '09',\n Selangor = '10',\n Terengganu = '11',\n Sabah = '12',\n Sarawak = '13',\n WPKualaLumpur = '14',\n WPLabuan = '15',\n WPPutrajaya = '16',\n NotApplicable = '17',\n}\n\n/**\n * Interface representing a state code entry.\n * Contains the code and its corresponding name.\n */\nexport interface State {\n code: StateCode\n name: string\n}\n"],"mappings":";;;;;;;;;;AA+BA,IAAY,0DAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACD"}
|
package/dist/index13.cjs
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
const require_getBaseUrl = require('./getBaseUrl-D0G4GZmp.cjs');
|
|
2
1
|
|
|
3
|
-
|
|
2
|
+
//#region src/types/tax-types.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Enum representing the allowed tax type codes with descriptive names.
|
|
5
|
+
* Provides a more readable way to reference tax types.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const code = TaxTypeCodeEnum.SalesTax;
|
|
9
|
+
* console.log(code); // Output: "01"
|
|
10
|
+
*/
|
|
11
|
+
let TaxTypeCodeEnum = /* @__PURE__ */ function(TaxTypeCodeEnum$1) {
|
|
12
|
+
TaxTypeCodeEnum$1["SalesTax"] = "01";
|
|
13
|
+
TaxTypeCodeEnum$1["ServiceTax"] = "02";
|
|
14
|
+
TaxTypeCodeEnum$1["TourismTax"] = "03";
|
|
15
|
+
TaxTypeCodeEnum$1["HighValueGoodsTax"] = "04";
|
|
16
|
+
TaxTypeCodeEnum$1["SalesTaxLowValueGoods"] = "05";
|
|
17
|
+
TaxTypeCodeEnum$1["NotApplicable"] = "06";
|
|
18
|
+
TaxTypeCodeEnum$1["TaxExemption"] = "E";
|
|
19
|
+
return TaxTypeCodeEnum$1;
|
|
20
|
+
}({});
|
|
21
|
+
|
|
22
|
+
//#endregion
|
|
23
|
+
exports.TaxTypeCodeEnum = TaxTypeCodeEnum;
|
|
24
|
+
//# sourceMappingURL=index13.cjs.map
|