@ripwords/myinvois-client 0.2.35 → 0.2.37
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/documentManagement.d.ts +2 -2
- package/dist/api/documentSubmission.d.ts +3 -3
- package/dist/api/documentSubmission.js +2 -2
- package/dist/api/documentTypeManagement.d.ts +2 -2
- package/dist/api/notificationManagement.d.ts +2 -2
- package/dist/api/platformLogin.d.ts +3 -3
- package/dist/api/platformLogin.js +1 -1
- package/dist/api/taxpayerValidation.d.ts +2 -2
- package/dist/{apiQueue-BE3-DB1A.js → apiQueue-CfneHIgD.js} +53 -19
- package/dist/{apiQueue-DDXeQJDC.cjs → apiQueue-CiZxlntc.cjs} +54 -20
- package/dist/apiQueue-CiZxlntc.cjs.map +1 -0
- package/dist/{document-DWsGewNs.cjs → document-CCza2JPL.cjs} +30 -4
- package/dist/document-CCza2JPL.cjs.map +1 -0
- package/dist/{document-DI6hw1MO.js → document-DLFdGSK1.js} +29 -3
- package/dist/{documentSubmission-YwuM4ap1.cjs → documentSubmission-M4UlirJ7.cjs} +8 -7
- package/dist/documentSubmission-M4UlirJ7.cjs.map +1 -0
- package/dist/{documentSubmission-CgW1Cm0W.js → documentSubmission-ZAgXsd3X.js} +7 -6
- package/dist/{documents-4B5YOXeb.d.cts → documents-DCZ3Ffya.d.cts} +39 -1
- package/dist/{documents-ChNlyKB2.d.ts → documents-DzZA3NHj.d.ts} +38 -0
- package/dist/index.cjs +9 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts +3 -2
- package/dist/index.js +9 -6
- package/dist/index10.cjs +195 -4
- package/dist/index10.cjs.map +1 -0
- package/dist/index11.cjs +0 -22
- package/dist/index12.cjs +24 -2
- package/dist/{index20.cjs.map → index12.cjs.map} +1 -1
- package/dist/index13.cjs +0 -3
- package/dist/index14.cjs +0 -330
- package/dist/index15.cjs +25 -189
- package/dist/index15.cjs.map +1 -1
- package/dist/index16.cjs +16 -53
- package/dist/index16.cjs.map +1 -1
- package/dist/index17.cjs +0 -532
- package/dist/index18.cjs +25 -187
- package/dist/index18.cjs.map +1 -1
- package/dist/index19.cjs +24 -0
- package/dist/{index27.cjs.map → index19.cjs.map} +1 -1
- package/dist/index20.cjs +0 -25
- package/dist/index23.cjs +3 -28
- package/dist/index24.cjs +9 -21
- package/dist/index24.cjs.map +1 -1
- package/dist/index25.cjs +5 -0
- package/dist/index26.cjs +21 -33
- package/dist/index27.cjs +2 -23
- package/dist/index28.cjs +3 -0
- package/dist/index29.cjs +330 -0
- package/dist/{index14.cjs.map → index29.cjs.map} +1 -1
- package/dist/index3.cjs +2 -2
- package/dist/index30.cjs +193 -0
- package/dist/index30.cjs.map +1 -0
- package/dist/index6.cjs +1 -1
- package/dist/index62.cts.map +1 -1
- package/dist/index65.cts.map +1 -1
- package/dist/index67.cts.map +1 -1
- package/dist/index71.cts.map +1 -1
- package/dist/index8.cjs +61 -3
- package/dist/index8.cjs.map +1 -0
- package/dist/index9.cjs +528 -9
- package/dist/index9.cjs.map +1 -1
- package/dist/{platformLogin-CqI9OLYP.js → platformLogin-B6f18bB7.js} +2 -2
- package/dist/{platformLogin-Ch6hFKoU.cjs → platformLogin-BVTUzLjd.cjs} +3 -3
- package/dist/platformLogin-BVTUzLjd.cjs.map +1 -0
- package/dist/{taxpayer-C9VMf0iv.d.ts → taxpayer-DmHW0m7o.d.ts} +1 -1
- package/dist/{taxpayer-DubRo4qZ.d.cts → taxpayer-Pm90MrPj.d.cts} +2 -2
- package/dist/types/documents.d.ts +1 -1
- package/dist/types/index.d.ts +2 -2
- package/dist/types/taxpayer.d.ts +2 -2
- package/dist/utils/apiQueue.js +1 -1
- package/dist/utils/document.d.ts +6 -2
- package/dist/utils/document.js +1 -1
- package/dist/utils/signature-diagnostics.d.ts +2 -2
- package/dist/utils/signature-diagnostics.js +1 -1
- package/dist/utils/validation.d.ts +2 -2
- package/package.json +1 -1
- package/dist/apiQueue-DDXeQJDC.cjs.map +0 -1
- package/dist/document-DWsGewNs.cjs.map +0 -1
- package/dist/documentSubmission-YwuM4ap1.cjs.map +0 -1
- package/dist/index17.cjs.map +0 -1
- package/dist/index23.cjs.map +0 -1
- package/dist/index26.cjs.map +0 -1
- package/dist/platformLogin-Ch6hFKoU.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index30.cjs","names":["tin: string","registrationType?: string","errors: ValidationError[]","contactNumber: string","amount: number","fieldName: string","item: InvoiceLineItem","index: number","invoice: InvoiceV1_1","allErrors: ValidationError[]"],"sources":["../src/utils/validation.ts"],"sourcesContent":["import type { InvoiceV1_1, InvoiceLineItem } from '../types'\n\n/**\n * MyInvois Invoice Validation Utilities\n *\n * Provides comprehensive validation for invoice data before document generation\n * and submission to ensure compliance with MyInvois business rules and format requirements.\n */\n\nexport interface ValidationResult {\n isValid: boolean\n errors: ValidationError[]\n warnings: ValidationWarning[]\n}\n\nexport interface ValidationError {\n field: string\n code: string\n message: string\n severity: 'error' | 'warning'\n}\n\nexport interface ValidationWarning extends ValidationError {\n severity: 'warning'\n}\n\n/**\n * Validates TIN format based on registration type\n */\nexport const validateTIN = (\n tin: string,\n registrationType?: string,\n): ValidationError[] => {\n const errors: ValidationError[] = []\n\n if (!tin) {\n errors.push({\n field: 'tin',\n code: 'TIN_REQUIRED',\n message: 'TIN is required',\n severity: 'error',\n })\n return errors\n }\n\n // TIN format validation based on type\n if (registrationType === 'BRN' && !tin.startsWith('C')) {\n errors.push({\n field: 'tin',\n code: 'TIN_FORMAT_INVALID',\n message: 'Company TIN should start with \"C\" for BRN registration',\n severity: 'warning',\n })\n }\n\n if (registrationType === 'NRIC' && !tin.startsWith('IG')) {\n errors.push({\n field: 'tin',\n code: 'TIN_FORMAT_INVALID',\n message: 'Individual TIN should start with \"IG\" for NRIC registration',\n severity: 'warning',\n })\n }\n\n // Length validation\n if (tin.length > 14) {\n errors.push({\n field: 'tin',\n code: 'TIN_LENGTH_INVALID',\n message: 'TIN cannot exceed 14 characters',\n severity: 'error',\n })\n }\n\n return errors\n}\n\n/**\n * Validates contact number format (E.164 standard)\n */\nexport const validateContactNumber = (\n contactNumber: string,\n): ValidationError[] => {\n const errors: ValidationError[] = []\n\n if (!contactNumber || contactNumber === 'NA') {\n return errors // Allow NA for consolidated e-invoices\n }\n\n // E.164 format validation\n const e164Regex = /^\\+[1-9]\\d{1,14}$/\n if (!e164Regex.test(contactNumber)) {\n errors.push({\n field: 'contactNumber',\n code: 'CONTACT_FORMAT_INVALID',\n message: 'Contact number must be in E.164 format (e.g., +60123456789)',\n severity: 'error',\n })\n }\n\n if (contactNumber.length < 8) {\n errors.push({\n field: 'contactNumber',\n code: 'CONTACT_LENGTH_INVALID',\n message: 'Contact number must be at least 8 characters',\n severity: 'error',\n })\n }\n\n return errors\n}\n\n/**\n * Validates monetary amounts\n */\nexport const validateMonetaryAmount = (\n amount: number,\n fieldName: string,\n maxDigits = 18,\n maxDecimals = 2,\n): ValidationError[] => {\n const errors: ValidationError[] = []\n\n if (amount < 0) {\n errors.push({\n field: fieldName,\n code: 'AMOUNT_NEGATIVE',\n message: `${fieldName} cannot be negative`,\n severity: 'error',\n })\n }\n\n // Check total digits\n const amountStr = amount.toString()\n const [integerPart, decimalPart] = amountStr.split('.')\n\n if (integerPart && integerPart.length > maxDigits - maxDecimals) {\n errors.push({\n field: fieldName,\n code: 'AMOUNT_DIGITS_EXCEEDED',\n message: `${fieldName} exceeds maximum ${maxDigits} digits`,\n severity: 'error',\n })\n }\n\n if (decimalPart && decimalPart.length > maxDecimals) {\n errors.push({\n field: fieldName,\n code: 'AMOUNT_DECIMALS_EXCEEDED',\n message: `${fieldName} exceeds maximum ${maxDecimals} decimal places`,\n severity: 'error',\n })\n }\n\n return errors\n}\n\n/**\n * Validates line item tax calculation consistency for both fixed rate and percentage taxation\n */\nexport const validateLineItemTax = (\n item: InvoiceLineItem,\n index: number,\n): ValidationError[] => {\n const errors: ValidationError[] = []\n const tolerance = 0.01\n\n // Check if tax calculation method is specified\n const hasFixedRate =\n item.taxPerUnitAmount !== undefined && item.baseUnitMeasure !== undefined\n const hasPercentageRate = item.taxRate !== undefined\n\n if (!hasFixedRate && !hasPercentageRate) {\n errors.push({\n field: `lineItem[${index}]`,\n code: 'TAX_METHOD_MISSING',\n message: `Line item ${index + 1} must specify either taxRate (for percentage) or taxPerUnitAmount + baseUnitMeasure (for fixed rate)`,\n severity: 'error',\n })\n return errors\n }\n\n if (hasFixedRate && hasPercentageRate) {\n errors.push({\n field: `lineItem[${index}]`,\n code: 'TAX_METHOD_CONFLICT',\n message: `Line item ${index + 1} cannot have both percentage and fixed rate tax methods`,\n severity: 'error',\n })\n }\n\n // Validate fixed rate tax calculation\n if (hasFixedRate) {\n if (item.baseUnitMeasureCode === undefined) {\n errors.push({\n field: `lineItem[${index}].baseUnitMeasureCode`,\n code: 'UNIT_CODE_MISSING',\n message: `Line item ${index + 1} with fixed rate tax must specify baseUnitMeasureCode`,\n severity: 'error',\n })\n }\n\n const expectedTaxAmount = item.taxPerUnitAmount! * item.baseUnitMeasure!\n if (Math.abs(item.taxAmount - expectedTaxAmount) > tolerance) {\n errors.push({\n field: `lineItem[${index}].taxAmount`,\n code: 'FIXED_TAX_CALCULATION_MISMATCH',\n message: `Line item ${index + 1} tax amount (${item.taxAmount}) doesn't match fixed rate calculation (${item.taxPerUnitAmount} × ${item.baseUnitMeasure} = ${expectedTaxAmount})`,\n severity: 'error',\n })\n }\n }\n\n // Validate percentage tax calculation\n if (hasPercentageRate && !hasFixedRate) {\n const expectedTaxAmount =\n (item.totalTaxableAmountPerLine * item.taxRate!) / 100\n if (Math.abs(item.taxAmount - expectedTaxAmount) > tolerance) {\n errors.push({\n field: `lineItem[${index}].taxAmount`,\n code: 'PERCENTAGE_TAX_CALCULATION_MISMATCH',\n message: `Line item ${index + 1} tax amount (${item.taxAmount}) doesn't match percentage calculation (${item.totalTaxableAmountPerLine} × ${item.taxRate}% = ${expectedTaxAmount})`,\n severity: 'error',\n })\n }\n }\n\n return errors\n}\n\n/**\n * Validates tax calculation consistency\n */\nexport const validateTaxCalculations = (\n invoice: InvoiceV1_1,\n): ValidationError[] => {\n const errors: ValidationError[] = []\n\n // Validate individual line item tax calculations\n invoice.invoiceLineItems.forEach((item, index) => {\n errors.push(...validateLineItemTax(item, index))\n })\n\n // Calculate expected totals from line items\n const expectedTaxExclusive = invoice.invoiceLineItems.reduce(\n (sum, item) => sum + item.totalTaxableAmountPerLine,\n 0,\n )\n const expectedTaxAmount = invoice.invoiceLineItems.reduce(\n (sum, item) => sum + item.taxAmount,\n 0,\n )\n\n // Allow small rounding differences (0.01)\n const tolerance = 0.01\n\n if (\n Math.abs(\n invoice.legalMonetaryTotal.taxExclusiveAmount - expectedTaxExclusive,\n ) > tolerance\n ) {\n errors.push({\n field: 'legalMonetaryTotal.taxExclusiveAmount',\n code: 'TAX_EXCLUSIVE_MISMATCH',\n message: `Tax exclusive amount (${invoice.legalMonetaryTotal.taxExclusiveAmount}) doesn't match sum of line items (${expectedTaxExclusive})`,\n severity: 'error',\n })\n }\n\n if (Math.abs(invoice.taxTotal.taxAmount - expectedTaxAmount) > tolerance) {\n errors.push({\n field: 'taxTotal.taxAmount',\n code: 'TAX_AMOUNT_MISMATCH',\n message: `Tax amount (${invoice.taxTotal.taxAmount}) doesn't match sum of line item taxes (${expectedTaxAmount})`,\n severity: 'error',\n })\n }\n\n return errors\n}\n\n/**\n * Main validation function for complete invoice\n */\nexport const validateInvoice = (invoice: InvoiceV1_1): ValidationResult => {\n const allErrors: ValidationError[] = []\n\n // Core field validations\n allErrors.push(\n ...validateTIN(invoice.supplier.tin, invoice.supplier.registrationType),\n )\n allErrors.push(\n ...validateTIN(invoice.buyer.tin, invoice.buyer.registrationType),\n )\n\n allErrors.push(...validateContactNumber(invoice.supplier.contactNumber))\n allErrors.push(...validateContactNumber(invoice.buyer.contactNumber))\n\n // Monetary validations\n allErrors.push(\n ...validateMonetaryAmount(\n invoice.legalMonetaryTotal.taxExclusiveAmount,\n 'taxExclusiveAmount',\n ),\n )\n allErrors.push(\n ...validateMonetaryAmount(\n invoice.legalMonetaryTotal.payableAmount,\n 'payableAmount',\n ),\n )\n allErrors.push(\n ...validateMonetaryAmount(invoice.taxTotal.taxAmount, 'taxAmount'),\n )\n\n // Line item validations\n invoice.invoiceLineItems.forEach((item, index) => {\n allErrors.push(\n ...validateMonetaryAmount(item.unitPrice, `lineItem[${index}].unitPrice`),\n )\n allErrors.push(\n ...validateMonetaryAmount(item.taxAmount, `lineItem[${index}].taxAmount`),\n )\n allErrors.push(\n ...validateMonetaryAmount(\n item.totalTaxableAmountPerLine,\n `lineItem[${index}].totalTaxableAmountPerLine`,\n ),\n )\n })\n\n // Business rule validations\n allErrors.push(...validateTaxCalculations(invoice))\n\n // Separate errors and warnings\n const errors = allErrors.filter(e => e.severity === 'error')\n const warnings = allErrors.filter(\n e => e.severity === 'warning',\n ) as ValidationWarning[]\n\n return {\n isValid: errors.length === 0,\n errors,\n warnings,\n }\n}\n"],"mappings":";;;;;AA6BA,MAAa,cAAc,CACzBA,KACAC,qBACsB;CACtB,MAAMC,SAA4B,CAAE;AAEpC,MAAK,KAAK;AACR,SAAO,KAAK;GACV,OAAO;GACP,MAAM;GACN,SAAS;GACT,UAAU;EACX,EAAC;AACF,SAAO;CACR;AAGD,KAAI,qBAAqB,UAAU,IAAI,WAAW,IAAI,CACpD,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,UAAU;CACX,EAAC;AAGJ,KAAI,qBAAqB,WAAW,IAAI,WAAW,KAAK,CACtD,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,UAAU;CACX,EAAC;AAIJ,KAAI,IAAI,SAAS,GACf,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,UAAU;CACX,EAAC;AAGJ,QAAO;AACR;;;;AAKD,MAAa,wBAAwB,CACnCC,kBACsB;CACtB,MAAMD,SAA4B,CAAE;AAEpC,MAAK,iBAAiB,kBAAkB,KACtC,QAAO;CAIT,MAAM,YAAY;AAClB,MAAK,UAAU,KAAK,cAAc,CAChC,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,UAAU;CACX,EAAC;AAGJ,KAAI,cAAc,SAAS,EACzB,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,SAAS;EACT,UAAU;CACX,EAAC;AAGJ,QAAO;AACR;;;;AAKD,MAAa,yBAAyB,CACpCE,QACAC,WACA,YAAY,IACZ,cAAc,MACQ;CACtB,MAAMH,SAA4B,CAAE;AAEpC,KAAI,SAAS,EACX,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,UAAU,EAAE,UAAU;EACtB,UAAU;CACX,EAAC;CAIJ,MAAM,YAAY,OAAO,UAAU;CACnC,MAAM,CAAC,aAAa,YAAY,GAAG,UAAU,MAAM,IAAI;AAEvD,KAAI,eAAe,YAAY,SAAS,YAAY,YAClD,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,UAAU,EAAE,UAAU,mBAAmB,UAAU;EACnD,UAAU;CACX,EAAC;AAGJ,KAAI,eAAe,YAAY,SAAS,YACtC,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,UAAU,EAAE,UAAU,mBAAmB,YAAY;EACrD,UAAU;CACX,EAAC;AAGJ,QAAO;AACR;;;;AAKD,MAAa,sBAAsB,CACjCI,MACAC,UACsB;CACtB,MAAML,SAA4B,CAAE;CACpC,MAAM,YAAY;CAGlB,MAAM,eACJ,KAAK,+BAAkC,KAAK;CAC9C,MAAM,oBAAoB,KAAK;AAE/B,MAAK,iBAAiB,mBAAmB;AACvC,SAAO,KAAK;GACV,QAAQ,WAAW,MAAM;GACzB,MAAM;GACN,UAAU,YAAY,QAAQ,EAAE;GAChC,UAAU;EACX,EAAC;AACF,SAAO;CACR;AAED,KAAI,gBAAgB,kBAClB,QAAO,KAAK;EACV,QAAQ,WAAW,MAAM;EACzB,MAAM;EACN,UAAU,YAAY,QAAQ,EAAE;EAChC,UAAU;CACX,EAAC;AAIJ,KAAI,cAAc;AAChB,MAAI,KAAK,+BACP,QAAO,KAAK;GACV,QAAQ,WAAW,MAAM;GACzB,MAAM;GACN,UAAU,YAAY,QAAQ,EAAE;GAChC,UAAU;EACX,EAAC;EAGJ,MAAM,oBAAoB,KAAK,mBAAoB,KAAK;AACxD,MAAI,KAAK,IAAI,KAAK,YAAY,kBAAkB,GAAG,UACjD,QAAO,KAAK;GACV,QAAQ,WAAW,MAAM;GACzB,MAAM;GACN,UAAU,YAAY,QAAQ,EAAE,eAAe,KAAK,UAAU,0CAA0C,KAAK,iBAAiB,KAAK,KAAK,gBAAgB,KAAK,kBAAkB;GAC/K,UAAU;EACX,EAAC;CAEL;AAGD,KAAI,sBAAsB,cAAc;EACtC,MAAM,oBACH,KAAK,4BAA4B,KAAK,UAAY;AACrD,MAAI,KAAK,IAAI,KAAK,YAAY,kBAAkB,GAAG,UACjD,QAAO,KAAK;GACV,QAAQ,WAAW,MAAM;GACzB,MAAM;GACN,UAAU,YAAY,QAAQ,EAAE,eAAe,KAAK,UAAU,0CAA0C,KAAK,0BAA0B,KAAK,KAAK,QAAQ,MAAM,kBAAkB;GACjL,UAAU;EACX,EAAC;CAEL;AAED,QAAO;AACR;;;;AAKD,MAAa,0BAA0B,CACrCM,YACsB;CACtB,MAAMN,SAA4B,CAAE;AAGpC,SAAQ,iBAAiB,QAAQ,CAAC,MAAM,UAAU;AAChD,SAAO,KAAK,GAAG,oBAAoB,MAAM,MAAM,CAAC;CACjD,EAAC;CAGF,MAAM,uBAAuB,QAAQ,iBAAiB,OACpD,CAAC,KAAK,SAAS,MAAM,KAAK,2BAC1B,EACD;CACD,MAAM,oBAAoB,QAAQ,iBAAiB,OACjD,CAAC,KAAK,SAAS,MAAM,KAAK,WAC1B,EACD;CAGD,MAAM,YAAY;AAElB,KACE,KAAK,IACH,QAAQ,mBAAmB,qBAAqB,qBACjD,GAAG,UAEJ,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,UAAU,wBAAwB,QAAQ,mBAAmB,mBAAmB,qCAAqC,qBAAqB;EAC1I,UAAU;CACX,EAAC;AAGJ,KAAI,KAAK,IAAI,QAAQ,SAAS,YAAY,kBAAkB,GAAG,UAC7D,QAAO,KAAK;EACV,OAAO;EACP,MAAM;EACN,UAAU,cAAc,QAAQ,SAAS,UAAU,0CAA0C,kBAAkB;EAC/G,UAAU;CACX,EAAC;AAGJ,QAAO;AACR;;;;AAKD,MAAa,kBAAkB,CAACM,YAA2C;CACzE,MAAMC,YAA+B,CAAE;AAGvC,WAAU,KACR,GAAG,YAAY,QAAQ,SAAS,KAAK,QAAQ,SAAS,iBAAiB,CACxE;AACD,WAAU,KACR,GAAG,YAAY,QAAQ,MAAM,KAAK,QAAQ,MAAM,iBAAiB,CAClE;AAED,WAAU,KAAK,GAAG,sBAAsB,QAAQ,SAAS,cAAc,CAAC;AACxE,WAAU,KAAK,GAAG,sBAAsB,QAAQ,MAAM,cAAc,CAAC;AAGrE,WAAU,KACR,GAAG,uBACD,QAAQ,mBAAmB,oBAC3B,qBACD,CACF;AACD,WAAU,KACR,GAAG,uBACD,QAAQ,mBAAmB,eAC3B,gBACD,CACF;AACD,WAAU,KACR,GAAG,uBAAuB,QAAQ,SAAS,WAAW,YAAY,CACnE;AAGD,SAAQ,iBAAiB,QAAQ,CAAC,MAAM,UAAU;AAChD,YAAU,KACR,GAAG,uBAAuB,KAAK,YAAY,WAAW,MAAM,aAAa,CAC1E;AACD,YAAU,KACR,GAAG,uBAAuB,KAAK,YAAY,WAAW,MAAM,aAAa,CAC1E;AACD,YAAU,KACR,GAAG,uBACD,KAAK,4BACJ,WAAW,MAAM,6BACnB,CACF;CACF,EAAC;AAGF,WAAU,KAAK,GAAG,wBAAwB,QAAQ,CAAC;CAGnD,MAAM,SAAS,UAAU,OAAO,OAAK,EAAE,aAAa,QAAQ;CAC5D,MAAM,WAAW,UAAU,OACzB,OAAK,EAAE,aAAa,UACrB;AAED,QAAO;EACL,SAAS,OAAO,WAAW;EAC3B;EACA;CACD;AACF"}
|
package/dist/index6.cjs
CHANGED
package/dist/index62.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index62.cts","names":[],"sources":["../src/api/documentSubmission.d.ts"],"sourcesContent":["import type { AllDocumentsV1_1, SubmissionResponse, SigningCredentials, SubmissionStatus, DocumentSummary, Fetch, StandardError } from '../types';\ninterface SubmissionContext {\n fetch: Fetch;\n debug: boolean;\n signingCredentials: SigningCredentials;\n}\nexport declare function submitDocument(context: SubmissionContext, documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n}>;\nexport declare function getSubmissionStatus(context: Pick<SubmissionContext, 'fetch' | 'debug'>, submissionUid: string, pollInterval?: number, maxRetries?: number, pageNo?: number, pageSize?: number): 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}>;\nexport declare function performDocumentAction(documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n}>;\nexport {};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAI,oBAAoB;CAAC;CAAG,MAAA;CAAA,MAAA;AAAA;AAC5B,IAAW,iBAAK;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AAChB,IAAW,sBAAO;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AAClB,IAAW,wBAAwB;CAAC;CAAK,MAAC;CAAA,MAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"index62.cts","names":[],"sources":["../src/api/documentSubmission.d.ts"],"sourcesContent":["import type { AllDocumentsV1_1, SubmissionResponse, SigningCredentials, SubmissionStatus, DocumentSummary, Fetch, StandardError } from '../types';\ninterface SubmissionContext {\n fetch: Fetch;\n debug: boolean;\n signingCredentials: SigningCredentials;\n}\nexport declare function submitDocument(context: SubmissionContext, documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n}>;\nexport declare function getSubmissionStatus(context: Pick<SubmissionContext, 'fetch' | 'debug'>, submissionUid: string, pollInterval?: number, maxRetries?: number, pageNo?: number, pageSize?: number): 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}>;\nexport declare function performDocumentAction(context: Pick<SubmissionContext, 'fetch'>, documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n}>;\nexport {};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAI,oBAAoB;CAAC;CAAG,MAAA;CAAA,MAAA;AAAA;AAC5B,IAAW,iBAAK;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AAChB,IAAW,sBAAO;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AAClB,IAAW,wBAAwB;CAAC;CAAK,MAAC;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA"}
|
package/dist/index65.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index65.cts","names":[],"sources":["../src/api/platformLogin.d.ts"],"sourcesContent":["import type { ClientCredentials } from '../types';\nexport declare const platformLogin: (client: ClientCredentials) => Promise<{\n token: string;\n tokenExpiration: Date;\n}>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAW,gBAAgB;CAAC;CAAK,MAAM;CAAmB,MAAM;CAAM,
|
|
1
|
+
{"version":3,"file":"index65.cts","names":[],"sources":["../src/api/platformLogin.d.ts"],"sourcesContent":["import type { ClientCredentials } from '../types';\nexport declare const platformLogin: (client: ClientCredentials, fetchFn?: (url: string, options?: RequestInit) => Promise<Response>) => Promise<{\n token: string;\n tokenExpiration: Date;\n}>;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA,IAAW,gBAAgB;CAAC;CAAK,MAAM;CAAmB,MAAM;CAAa,MAAM;CAAU,MAAM;CAAS,MAAM;CAAM,MAAM;AAAQ"}
|
package/dist/index67.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index67.cts","names":[],"sources":["../src/index.d.ts"],"sourcesContent":["import { DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypesResponse, DocumentTypeVersionResponse, DocumentValidationResult, DocumentValidationStepResult, EInvoiceTypeCode, NotificationResponse, NotificationSearchParams, RegistrationType, StandardError, SubmissionResponse, SubmissionStatus, TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse, AllDocumentsV1_1 } from './types';\nexport type * from './types/index.d.ts';\nexport declare class MyInvoisClient {\n private readonly baseUrl;\n private readonly clientId;\n private readonly clientSecret;\n private readonly environment;\n private onBehalfOf?;\n private readonly signingCredentials;\n private readonly debug;\n private token;\n private tokenExpiration;\n constructor(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', certificatePem: string, privateKeyPem: string, onBehalfOf?: string, debug?: boolean);\n updateOnBehalfOf(onBehalfOf: string): Promise<void>;\n private refreshToken;\n private getToken;\n private fetch;\n /**\n * Validates a TIN against a NRIC/ARMY/PASSPORT/BRN (Business Registration Number)\n *\n * This method verifies if a given Tax Identification Number (TIN) is valid by checking it against\n * the provided identification type and value through the MyInvois platform's validation service.\n *\n * @param tin - The TIN to validate\n * @param idType - The type of ID to validate against ('NRIC', 'ARMY', 'PASSPORT', or 'BRN')\n * @param idValue - The value of the ID to validate against\n * @returns Promise resolving to true if the TIN is valid, false otherwise\n *\n * @example\n * ```typescript\n * // Validate TIN against NRIC\n * const isValid = await client.verifyTin('C12345678901234', 'NRIC', '123456789012');\n * if (isValid) {\n * console.log('TIN is valid');\n * }\n *\n * // Validate TIN against Business Registration Number\n * const isValidBusiness = await client.verifyTin('C98765432109876', 'BRN', '123456-K');\n * ```\n *\n * @remarks\n * - Returns false if validation fails due to network errors or invalid credentials\n * - Debug mode provides error logging for troubleshooting validation failures\n * - This is a non-blocking validation that won't throw exceptions on failure\n */\n verifyTin(tin: string, idType: RegistrationType, idValue: string): Promise<boolean>;\n /**\n * Searches for a Tax Identification Number (TIN) using taxpayer information.\n *\n * This method allows searching for a TIN using either a taxpayer name or a combination\n * of identification type and value. The search is flexible and supports multiple\n * identification types including NRIC, ARMY, PASSPORT, and BRN.\n *\n * @param params - Search parameters object\n * @param params.taxpayerName - Optional name of the taxpayer to search for\n * @param params.idType - Optional type of ID to search with (NRIC, ARMY, PASSPORT, BRN)\n * @param params.idValue - Optional value of the ID to search with\n * @returns Promise resolving to TIN search response or standard error\n *\n * @example\n * ```typescript\n * // Search by taxpayer name\n * const result = await client.searchTin({ taxpayerName: 'John Doe' });\n * if ('tin' in result) {\n * console.log('Found TIN:', result.tin);\n * }\n *\n * // Search by ID type and value\n * const result = await client.searchTin({\n * idType: 'NRIC',\n * idValue: '123456789012'\n * });\n * ```\n *\n * @remarks\n * - Either taxpayerName or both idType and idValue must be provided\n * - Returns StandardError object if search criteria are invalid or inconclusive\n * - Debug mode provides detailed error logging for troubleshooting\n * - Search results are not guaranteed to be unique\n */\n searchTin(params: TinSearchParams): Promise<TinSearchResponse>;\n /**\n * Retrieves taxpayer information from a QR code.\n *\n * This method decodes a QR code containing taxpayer information and returns\n * detailed taxpayer data including TIN, name, contact details, and business information.\n *\n * @param qrCodeText - The QR code text to decode\n * @returns Promise resolving to taxpayer QR code response or standard error\n *\n * @example\n * ```typescript\n * // Get taxpayer info from QR code\n * const taxpayerInfo = await client.getTaxpayerQRCode('QR_CODE_TEXT');\n * if ('tin' in taxpayerInfo) {\n * console.log('Taxpayer TIN:', taxpayerInfo.tin);\n * console.log('Business Name:', taxpayerInfo.name);\n * console.log('Address:', taxpayerInfo.addressLine1);\n * }\n * ```\n *\n * @remarks\n * - QR code must be in the correct format specified by MyInvois\n * - Returns StandardError if QR code is invalid or cannot be decoded\n * - Debug mode provides detailed error logging\n */\n getTaxpayerQRCode(qrCodeText: string): Promise<TaxpayerQRCodeResponse>;\n /**\n * Performs an action on a document such as rejection or cancellation.\n *\n * This method allows updating the status of a document to either rejected or cancelled,\n * along with providing a reason for the action. Useful for managing document workflow\n * and maintaining audit trails.\n *\n * @param documentUid - The unique identifier of the document\n * @param status - The new status to set ('rejected' or 'cancelled')\n * @param reason - The reason for the status change\n * @returns Promise resolving to document action response containing UUID, status, and any errors\n *\n * @example\n * ```typescript\n * // Reject a document with reason\n * const result = await client.performDocumentAction(\n * 'doc-123',\n * 'rejected',\n * 'Invalid tax calculation'\n * );\n *\n * // Cancel a document\n * const result = await client.performDocumentAction(\n * 'doc-456',\n * 'cancelled',\n * 'Duplicate submission'\n * );\n * ```\n *\n * @remarks\n * - Only valid for documents in appropriate states\n * - Reason is required and should be descriptive\n * - Action is irreversible once completed\n * - Returns error if document cannot be found or action is invalid\n */\n performDocumentAction(documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n }>;\n /**\n * Submits one or more e-invoice documents to the MyInvois platform for processing.\n *\n * This method digitally signs each document using the provided certificate and private key,\n * generates document hashes, encodes them for submission, and sends them to the platform.\n * The method includes comprehensive validation warnings for document size and count limits.\n *\n * @param documents - Array of InvoiceV1_1 documents to be submitted\n * @returns Promise resolving to submission response containing the submission data and HTTP status\n * @throws {Error} If PRIVATE_KEY or CERTIFICATE environment variables are missing\n * @throws {Error} If document signing, encoding, or API submission fails\n *\n * @example\n * ```typescript\n * // Submit a single invoice\n * const result = await client.submitDocument([invoiceData]);\n * console.log(result.data.submissionUid); // Track submission with this UID\n *\n * // Submit multiple invoices\n * const result = await client.submitDocument([invoice1, invoice2, invoice3]);\n * if (result.status === 202) {\n * console.log('Documents submitted successfully');\n * }\n * ```\n *\n * @remarks\n * - Requires PRIVATE_KEY and CERTIFICATE environment variables for document signing\n * - Each document is digitally signed with XML-DSIG before submission\n * - Documents are base64-encoded for transmission\n * - API limits: Max 100 documents per submission, 5MB total payload, 300KB per document\n * - Debug mode provides detailed logging of payload sizes and validation warnings\n * - Returns HTTP 202 for successful submissions that require processing\n */\n submitDocument(documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n }>;\n /**\n * Polls the MyInvois platform to get the current status of a document submission.\n *\n * This method continuously checks the submission status until it receives a final result\n * (Valid or Invalid) or reaches the maximum retry limit. It's designed to handle the\n * asynchronous nature of document processing on the MyInvois platform.\n *\n * @param submissionUid - The unique identifier of the submission to check\n * @param pollInterval - Time in milliseconds between status checks (default: 1000ms)\n * @param maxRetries - Maximum number of retry attempts (default: 10)\n * @returns Promise resolving to submission status object with document summary and any errors\n *\n * @example\n * ```typescript\n * // Check submission status with default polling\n * const result = await client.getSubmissionStatus('submission-uid-123');\n * if (result.status === 'Valid') {\n * console.log('All documents processed successfully');\n * console.log('Document summaries:', result.documentSummary);\n * }\n *\n * // Custom polling interval and retry count\n * const result = await client.getSubmissionStatus(\n * 'submission-uid-123',\n * 2000, // Poll every 2 seconds\n * 20 // Try up to 20 times\n * );\n * ```\n *\n * @remarks\n * - Automatically retries on network errors until maxRetries is reached\n * - Returns 'Invalid' status with timeout error if submission processing takes too long\n * - Debug mode provides detailed logging of polling attempts and responses\n * - Use reasonable poll intervals to avoid overwhelming the API\n */\n getSubmissionStatus(submissionUid: string, pollInterval?: number, maxRetries?: number, pageNo?: number, pageSize?: number): 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 /**\n * Retrieves a document by its unique identifier with the raw document content.\n *\n * @param documentUid - The unique identifier of the document to retrieve\n * @returns Promise resolving to document summary with raw document content as a string\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const document = await client.getDocument('doc-uuid-123');\n * console.log(document.document); // Raw XML/JSON content\n * console.log(document.uuid); // Document UUID\n * ```\n */\n getDocument(documentUid: string): Promise<DocumentSummary & {\n document: string;\n }>;\n /**\n * Retrieves detailed information about a document including validation results.\n *\n * @param documentUid - The unique identifier of the document to get details for\n * @returns Promise resolving to document summary with detailed validation results\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const details = await client.getDocumentDetails('doc-uuid-123');\n * console.log(details.validationResults.status); // 'Valid' | 'Invalid' | 'Processing'\n * console.log(details.validationResults.validationSteps); // Array of validation step results\n * ```\n */\n getDocumentDetails(documentUid: string): Promise<DocumentSummary & {\n validationResults: {\n status: DocumentValidationResult;\n validationSteps: DocumentValidationStepResult[];\n };\n }>;\n /**\n * Searches for documents based on various filter criteria.\n *\n * @param params - Search parameters object\n * @param params.uuid - Optional specific document UUID to search for\n * @param params.submissionDateFrom - Required start date for submission date range (ISO date string)\n * @param params.submissionDateTo - Optional end date for submission date range (ISO date string)\n * @param params.pageSize - Optional number of results per page (default handled by API)\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.issueDateFrom - Optional start date for issue date range (ISO date string)\n * @param params.issueDateTo - Optional end date for issue date range (ISO date string)\n * @param params.invoiceDirection - Optional filter by invoice direction ('Sent' or 'Received')\n * @param params.status - Optional filter by document status\n * @param params.documentType - Optional filter by e-invoice type code\n * @param params.searchQuery - Optional text search across uuid, buyerTIN, supplierTIN, buyerName, supplierName, internalID, total\n * @returns Promise resolving to array of document summaries matching the search criteria\n * @throws {Error} If the search request fails\n *\n * @example\n * ```typescript\n * // Search for documents submitted in the last 30 days\n * const documents = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * submissionDateTo: '2024-01-31',\n * status: 'Valid',\n * pageSize: 10\n * });\n *\n * // Search by supplier name\n * const supplierDocs = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * searchQuery: 'ACME Corp',\n * invoiceDirection: 'Received'\n * });\n * ```\n */\n searchDocuments({ uuid, submissionDateFrom, submissionDateTo, pageSize, pageNo, issueDateFrom, issueDateTo, invoiceDirection, status, documentType, searchQuery, }: {\n uuid?: string;\n submissionDateFrom: string;\n submissionDateTo?: string;\n pageSize?: number;\n pageNo?: number;\n issueDateFrom?: string;\n issueDateTo?: string;\n invoiceDirection?: 'Sent' | 'Received';\n status?: DocumentStatus;\n documentType?: EInvoiceTypeCode;\n searchQuery?: string;\n }): Promise<DocumentSummary[]>;\n /**\n * Retrieves notifications from the MyInvois platform based on specified search criteria.\n *\n * This method allows you to search for system notifications, alerts, and messages\n * sent by the MyInvois platform regarding document processing, system updates,\n * or account-related information.\n *\n * @param params - Search parameters object for filtering notifications\n * @param params.dateFrom - Optional start date for notification date range (ISO date string)\n * @param params.dateTo - Optional end date for notification date range (ISO date string)\n * @param params.type - Optional notification type filter\n * @param params.language - Optional language preference for notifications\n * @param params.status - Optional notification status filter\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.pageSize - Optional number of results per page\n * @returns Promise resolving to notification response object or standard error\n *\n * @example\n * ```typescript\n * // Get all notifications from the last 7 days\n * const notifications = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * dateTo: '2024-01-07',\n * pageSize: 20\n * });\n *\n * // Get unread notifications only\n * const unreadNotifications = await client.getNotifications({\n * status: 0, // Assuming 0 = unread\n * language: 'en'\n * });\n *\n * // Paginated notification retrieval\n * const firstPage = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * pageNo: 0,\n * pageSize: 10\n * });\n * ```\n *\n * @remarks\n * - All parameters are optional, allowing flexible filtering\n * - Returns paginated results when pageNo and pageSize are specified\n * - Date parameters should be in ISO format (YYYY-MM-DD)\n * - May return StandardError object if the request fails\n */\n getNotifications({ dateFrom, dateTo, type, language, status, pageNo, pageSize, }: NotificationSearchParams): Promise<NotificationResponse>;\n getDocumentTypes(): Promise<DocumentTypesResponse>;\n /**\n * Retrieves detailed information about a specific document type from the MyInvois platform.\n *\n * This method fetches metadata and configuration details for a specific document type,\n * including supported versions, validation rules, and structural requirements.\n * Useful for understanding document format requirements before submission.\n *\n * @param id - The unique identifier of the document type to retrieve\n * @returns Promise resolving to document type response object or standard error\n *\n * @example\n * ```typescript\n * // Get details for e-invoice document type\n * const invoiceType = await client.getDocumentType(1);\n * if ('id' in invoiceType) {\n * console.log('Document type name:', invoiceType.name);\n * console.log('Available versions:', invoiceType.versionNumber);\n * console.log('Description:', invoiceType.description);\n * }\n *\n * // Handle potential errors\n * const documentType = await client.getDocumentType(999);\n * if ('error' in documentType) {\n * console.error('Failed to retrieve document type:', documentType.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if the document type ID doesn't exist\n * - Document type information includes validation schemas and business rules\n * - Use this method to discover supported document formats and versions\n * - Essential for understanding submission requirements for different document types\n */\n getDocumentType(id: number): Promise<DocumentTypeResponse>;\n /**\n * Generates a shareable QR code URL for a specific document.\n *\n * This method retrieves the document details using its unique identifier,\n * then constructs a URL that can be used to access or share the document\n * via the MyInvois platform. The URL format differs between sandbox and\n * production environments.\n *\n * @param documentUid - The unique identifier of the document\n * @returns Promise resolving to a string containing the QR code URL\n *\n * @example\n * ```typescript\n * const qrCodeUrl = await client.getDocumentQrCode('abc123');\n * console.log('Shareable QR code URL:', qrCodeUrl);\n * // Output (sandbox): https://preprod.myinvois.hasil.gov.my/abc123/share/longId\n * // Output (production): https://myinvois.hasil.gov.my/abc123/share/longId\n * ```\n *\n * @remarks\n * - The returned URL can be embedded in a QR code for document sharing.\n * - The method fetches the document to obtain its longId, which is required for the URL.\n * - Ensure the documentUid is valid and accessible by the current client.\n */\n getDocumentQrCode(documentUid: string, longId?: string): Promise<string | null>;\n /**\n * Retrieves detailed information about a specific version of a document type.\n *\n * This method fetches version-specific metadata, schema definitions, and validation rules\n * for a particular document type version. Essential for understanding the exact format\n * and requirements for document submission in a specific version.\n *\n * @param id - The unique identifier of the document type\n * @param versionId - The unique identifier of the specific version to retrieve\n * @returns Promise resolving to document type version response object or standard error\n *\n * @example\n * ```typescript\n * // Get specific version details for e-invoice\n * const invoiceV1_1 = await client.getDocumentTypeVersion(1, 1);\n * if ('id' in invoiceV1_1) {\n * console.log('Version number:', invoiceV1_1.versionNumber);\n * console.log('Schema:', invoiceV1_1.jsonSchema);\n * console.log('Status:', invoiceV1_1.status);\n * }\n *\n * // Compare different versions\n * const [v1_0, v1_1] = await Promise.all([\n * client.getDocumentTypeVersion(1, 0),\n * client.getDocumentTypeVersion(1, 1)\n * ]);\n *\n * // Handle version not found\n * const result = await client.getDocumentTypeVersion(1, 999);\n * if ('error' in result) {\n * console.error('Version not found:', result.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if document type ID or version ID doesn't exist\n * - Version information includes JSON schema for validation\n * - Different versions may have different validation rules and field requirements\n * - Use this to ensure your documents conform to the specific version requirements\n * - Version status indicates if the version is active, deprecated, or under development\n */\n getDocumentTypeVersion(id: number, versionId: number): Promise<DocumentTypeVersionResponse>;\n static fromP12(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', p12Input: Buffer | string, passphrase: string, onBehalfOf?: string, debug?: boolean): MyInvoisClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAW,iBAAiB;CAAC;CAAK,MAAE;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA"}
|
|
1
|
+
{"version":3,"file":"index67.cts","names":[],"sources":["../src/index.d.ts"],"sourcesContent":["import { DocumentStatus, DocumentSummary, DocumentTypeResponse, DocumentTypesResponse, DocumentTypeVersionResponse, DocumentValidationResult, DocumentValidationStepResult, EInvoiceTypeCode, NotificationResponse, NotificationSearchParams, RegistrationType, StandardError, SubmissionResponse, SubmissionStatus, TaxpayerQRCodeResponse, TinSearchParams, TinSearchResponse, AllDocumentsV1_1 } from './types';\nexport type * from './types/index.d.ts';\nexport declare class MyInvoisClient {\n private readonly baseUrl;\n private readonly clientId;\n private readonly clientSecret;\n private readonly environment;\n private onBehalfOf?;\n private readonly signingCredentials;\n private readonly debug;\n private token;\n private tokenExpiration;\n private requestCount;\n constructor(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', certificatePem: string, privateKeyPem: string, onBehalfOf?: string, debug?: boolean);\n updateOnBehalfOf(onBehalfOf: string): Promise<void>;\n private refreshToken;\n private getToken;\n private fetch;\n /**\n * Validates a TIN against a NRIC/ARMY/PASSPORT/BRN (Business Registration Number)\n *\n * This method verifies if a given Tax Identification Number (TIN) is valid by checking it against\n * the provided identification type and value through the MyInvois platform's validation service.\n *\n * @param tin - The TIN to validate\n * @param idType - The type of ID to validate against ('NRIC', 'ARMY', 'PASSPORT', or 'BRN')\n * @param idValue - The value of the ID to validate against\n * @returns Promise resolving to true if the TIN is valid, false otherwise\n *\n * @example\n * ```typescript\n * // Validate TIN against NRIC\n * const isValid = await client.verifyTin('C12345678901234', 'NRIC', '123456789012');\n * if (isValid) {\n * console.log('TIN is valid');\n * }\n *\n * // Validate TIN against Business Registration Number\n * const isValidBusiness = await client.verifyTin('C98765432109876', 'BRN', '123456-K');\n * ```\n *\n * @remarks\n * - Returns false if validation fails due to network errors or invalid credentials\n * - Debug mode provides error logging for troubleshooting validation failures\n * - This is a non-blocking validation that won't throw exceptions on failure\n */\n verifyTin(tin: string, idType: RegistrationType, idValue: string): Promise<boolean>;\n /**\n * Searches for a Tax Identification Number (TIN) using taxpayer information.\n *\n * This method allows searching for a TIN using either a taxpayer name or a combination\n * of identification type and value. The search is flexible and supports multiple\n * identification types including NRIC, ARMY, PASSPORT, and BRN.\n *\n * @param params - Search parameters object\n * @param params.taxpayerName - Optional name of the taxpayer to search for\n * @param params.idType - Optional type of ID to search with (NRIC, ARMY, PASSPORT, BRN)\n * @param params.idValue - Optional value of the ID to search with\n * @returns Promise resolving to TIN search response or standard error\n *\n * @example\n * ```typescript\n * // Search by taxpayer name\n * const result = await client.searchTin({ taxpayerName: 'John Doe' });\n * if ('tin' in result) {\n * console.log('Found TIN:', result.tin);\n * }\n *\n * // Search by ID type and value\n * const result = await client.searchTin({\n * idType: 'NRIC',\n * idValue: '123456789012'\n * });\n * ```\n *\n * @remarks\n * - Either taxpayerName or both idType and idValue must be provided\n * - Returns StandardError object if search criteria are invalid or inconclusive\n * - Debug mode provides detailed error logging for troubleshooting\n * - Search results are not guaranteed to be unique\n */\n searchTin(params: TinSearchParams): Promise<TinSearchResponse>;\n /**\n * Retrieves taxpayer information from a QR code.\n *\n * This method decodes a QR code containing taxpayer information and returns\n * detailed taxpayer data including TIN, name, contact details, and business information.\n *\n * @param qrCodeText - The QR code text to decode\n * @returns Promise resolving to taxpayer QR code response or standard error\n *\n * @example\n * ```typescript\n * // Get taxpayer info from QR code\n * const taxpayerInfo = await client.getTaxpayerQRCode('QR_CODE_TEXT');\n * if ('tin' in taxpayerInfo) {\n * console.log('Taxpayer TIN:', taxpayerInfo.tin);\n * console.log('Business Name:', taxpayerInfo.name);\n * console.log('Address:', taxpayerInfo.addressLine1);\n * }\n * ```\n *\n * @remarks\n * - QR code must be in the correct format specified by MyInvois\n * - Returns StandardError if QR code is invalid or cannot be decoded\n * - Debug mode provides detailed error logging\n */\n getTaxpayerQRCode(qrCodeText: string): Promise<TaxpayerQRCodeResponse>;\n /**\n * Performs an action on a document such as rejection or cancellation.\n *\n * This method allows updating the status of a document to either rejected or cancelled,\n * along with providing a reason for the action. Useful for managing document workflow\n * and maintaining audit trails.\n *\n * @param documentUid - The unique identifier of the document\n * @param status - The new status to set ('rejected' or 'cancelled')\n * @param reason - The reason for the status change\n * @returns Promise resolving to document action response containing UUID, status, and any errors\n *\n * @example\n * ```typescript\n * // Reject a document with reason\n * const result = await client.performDocumentAction(\n * 'doc-123',\n * 'rejected',\n * 'Invalid tax calculation'\n * );\n *\n * // Cancel a document\n * const result = await client.performDocumentAction(\n * 'doc-456',\n * 'cancelled',\n * 'Duplicate submission'\n * );\n * ```\n *\n * @remarks\n * - Only valid for documents in appropriate states\n * - Reason is required and should be descriptive\n * - Action is irreversible once completed\n * - Returns error if document cannot be found or action is invalid\n */\n performDocumentAction(documentUid: string, status: 'rejected' | 'cancelled', reason: string): Promise<{\n uuid: string;\n status: string;\n error: StandardError;\n }>;\n /**\n * Submits one or more e-invoice documents to the MyInvois platform for processing.\n *\n * This method digitally signs each document using the provided certificate and private key,\n * generates document hashes, encodes them for submission, and sends them to the platform.\n * The method includes comprehensive validation warnings for document size and count limits.\n *\n * @param documents - Array of InvoiceV1_1 documents to be submitted\n * @returns Promise resolving to submission response containing the submission data and HTTP status\n * @throws {Error} If PRIVATE_KEY or CERTIFICATE environment variables are missing\n * @throws {Error} If document signing, encoding, or API submission fails\n *\n * @example\n * ```typescript\n * // Submit a single invoice\n * const result = await client.submitDocument([invoiceData]);\n * console.log(result.data.submissionUid); // Track submission with this UID\n *\n * // Submit multiple invoices\n * const result = await client.submitDocument([invoice1, invoice2, invoice3]);\n * if (result.status === 202) {\n * console.log('Documents submitted successfully');\n * }\n * ```\n *\n * @remarks\n * - Requires PRIVATE_KEY and CERTIFICATE environment variables for document signing\n * - Each document is digitally signed with XML-DSIG before submission\n * - Documents are base64-encoded for transmission\n * - API limits: Max 100 documents per submission, 5MB total payload, 300KB per document\n * - Debug mode provides detailed logging of payload sizes and validation warnings\n * - Returns HTTP 202 for successful submissions that require processing\n */\n submitDocument(documents: AllDocumentsV1_1[]): Promise<{\n data: SubmissionResponse;\n status: number;\n }>;\n /**\n * Polls the MyInvois platform to get the current status of a document submission.\n *\n * This method continuously checks the submission status until it receives a final result\n * (Valid or Invalid) or reaches the maximum retry limit. It's designed to handle the\n * asynchronous nature of document processing on the MyInvois platform.\n *\n * @param submissionUid - The unique identifier of the submission to check\n * @param pollInterval - Time in milliseconds between status checks (default: 1000ms)\n * @param maxRetries - Maximum number of retry attempts (default: 10)\n * @returns Promise resolving to submission status object with document summary and any errors\n *\n * @example\n * ```typescript\n * // Check submission status with default polling\n * const result = await client.getSubmissionStatus('submission-uid-123');\n * if (result.status === 'Valid') {\n * console.log('All documents processed successfully');\n * console.log('Document summaries:', result.documentSummary);\n * }\n *\n * // Custom polling interval and retry count\n * const result = await client.getSubmissionStatus(\n * 'submission-uid-123',\n * 2000, // Poll every 2 seconds\n * 20 // Try up to 20 times\n * );\n * ```\n *\n * @remarks\n * - Automatically retries on network errors until maxRetries is reached\n * - Returns 'Invalid' status with timeout error if submission processing takes too long\n * - Debug mode provides detailed logging of polling attempts and responses\n * - Use reasonable poll intervals to avoid overwhelming the API\n */\n getSubmissionStatus(submissionUid: string, pollInterval?: number, maxRetries?: number, pageNo?: number, pageSize?: number): 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 /**\n * Retrieves a document by its unique identifier with the raw document content.\n *\n * @param documentUid - The unique identifier of the document to retrieve\n * @returns Promise resolving to document summary with raw document content as a string\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const document = await client.getDocument('doc-uuid-123');\n * console.log(document.document); // Raw XML/JSON content\n * console.log(document.uuid); // Document UUID\n * ```\n */\n getDocument(documentUid: string): Promise<DocumentSummary & {\n document: string;\n }>;\n /**\n * Retrieves detailed information about a document including validation results.\n *\n * @param documentUid - The unique identifier of the document to get details for\n * @returns Promise resolving to document summary with detailed validation results\n * @throws {Error} If the document is not found or request fails\n *\n * @example\n * ```typescript\n * const details = await client.getDocumentDetails('doc-uuid-123');\n * console.log(details.validationResults.status); // 'Valid' | 'Invalid' | 'Processing'\n * console.log(details.validationResults.validationSteps); // Array of validation step results\n * ```\n */\n getDocumentDetails(documentUid: string): Promise<DocumentSummary & {\n validationResults: {\n status: DocumentValidationResult;\n validationSteps: DocumentValidationStepResult[];\n };\n }>;\n /**\n * Searches for documents based on various filter criteria.\n *\n * @param params - Search parameters object\n * @param params.uuid - Optional specific document UUID to search for\n * @param params.submissionDateFrom - Required start date for submission date range (ISO date string)\n * @param params.submissionDateTo - Optional end date for submission date range (ISO date string)\n * @param params.pageSize - Optional number of results per page (default handled by API)\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.issueDateFrom - Optional start date for issue date range (ISO date string)\n * @param params.issueDateTo - Optional end date for issue date range (ISO date string)\n * @param params.invoiceDirection - Optional filter by invoice direction ('Sent' or 'Received')\n * @param params.status - Optional filter by document status\n * @param params.documentType - Optional filter by e-invoice type code\n * @param params.searchQuery - Optional text search across uuid, buyerTIN, supplierTIN, buyerName, supplierName, internalID, total\n * @returns Promise resolving to array of document summaries matching the search criteria\n * @throws {Error} If the search request fails\n *\n * @example\n * ```typescript\n * // Search for documents submitted in the last 30 days\n * const documents = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * submissionDateTo: '2024-01-31',\n * status: 'Valid',\n * pageSize: 10\n * });\n *\n * // Search by supplier name\n * const supplierDocs = await client.searchDocuments({\n * submissionDateFrom: '2024-01-01',\n * searchQuery: 'ACME Corp',\n * invoiceDirection: 'Received'\n * });\n * ```\n */\n searchDocuments({ uuid, submissionDateFrom, submissionDateTo, pageSize, pageNo, issueDateFrom, issueDateTo, invoiceDirection, status, documentType, searchQuery, }: {\n uuid?: string;\n submissionDateFrom: string;\n submissionDateTo?: string;\n pageSize?: number;\n pageNo?: number;\n issueDateFrom?: string;\n issueDateTo?: string;\n invoiceDirection?: 'Sent' | 'Received';\n status?: DocumentStatus;\n documentType?: EInvoiceTypeCode;\n searchQuery?: string;\n }): Promise<DocumentSummary[]>;\n /**\n * Retrieves notifications from the MyInvois platform based on specified search criteria.\n *\n * This method allows you to search for system notifications, alerts, and messages\n * sent by the MyInvois platform regarding document processing, system updates,\n * or account-related information.\n *\n * @param params - Search parameters object for filtering notifications\n * @param params.dateFrom - Optional start date for notification date range (ISO date string)\n * @param params.dateTo - Optional end date for notification date range (ISO date string)\n * @param params.type - Optional notification type filter\n * @param params.language - Optional language preference for notifications\n * @param params.status - Optional notification status filter\n * @param params.pageNo - Optional page number for pagination (0-based)\n * @param params.pageSize - Optional number of results per page\n * @returns Promise resolving to notification response object or standard error\n *\n * @example\n * ```typescript\n * // Get all notifications from the last 7 days\n * const notifications = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * dateTo: '2024-01-07',\n * pageSize: 20\n * });\n *\n * // Get unread notifications only\n * const unreadNotifications = await client.getNotifications({\n * status: 0, // Assuming 0 = unread\n * language: 'en'\n * });\n *\n * // Paginated notification retrieval\n * const firstPage = await client.getNotifications({\n * dateFrom: '2024-01-01',\n * pageNo: 0,\n * pageSize: 10\n * });\n * ```\n *\n * @remarks\n * - All parameters are optional, allowing flexible filtering\n * - Returns paginated results when pageNo and pageSize are specified\n * - Date parameters should be in ISO format (YYYY-MM-DD)\n * - May return StandardError object if the request fails\n */\n getNotifications({ dateFrom, dateTo, type, language, status, pageNo, pageSize, }: NotificationSearchParams): Promise<NotificationResponse>;\n getDocumentTypes(): Promise<DocumentTypesResponse>;\n /**\n * Retrieves detailed information about a specific document type from the MyInvois platform.\n *\n * This method fetches metadata and configuration details for a specific document type,\n * including supported versions, validation rules, and structural requirements.\n * Useful for understanding document format requirements before submission.\n *\n * @param id - The unique identifier of the document type to retrieve\n * @returns Promise resolving to document type response object or standard error\n *\n * @example\n * ```typescript\n * // Get details for e-invoice document type\n * const invoiceType = await client.getDocumentType(1);\n * if ('id' in invoiceType) {\n * console.log('Document type name:', invoiceType.name);\n * console.log('Available versions:', invoiceType.versionNumber);\n * console.log('Description:', invoiceType.description);\n * }\n *\n * // Handle potential errors\n * const documentType = await client.getDocumentType(999);\n * if ('error' in documentType) {\n * console.error('Failed to retrieve document type:', documentType.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if the document type ID doesn't exist\n * - Document type information includes validation schemas and business rules\n * - Use this method to discover supported document formats and versions\n * - Essential for understanding submission requirements for different document types\n */\n getDocumentType(id: number): Promise<DocumentTypeResponse>;\n /**\n * Generates a shareable QR code URL for a specific document.\n *\n * This method retrieves the document details using its unique identifier,\n * then constructs a URL that can be used to access or share the document\n * via the MyInvois platform. The URL format differs between sandbox and\n * production environments.\n *\n * @param documentUid - The unique identifier of the document\n * @returns Promise resolving to a string containing the QR code URL\n *\n * @example\n * ```typescript\n * const qrCodeUrl = await client.getDocumentQrCode('abc123');\n * console.log('Shareable QR code URL:', qrCodeUrl);\n * // Output (sandbox): https://preprod.myinvois.hasil.gov.my/abc123/share/longId\n * // Output (production): https://myinvois.hasil.gov.my/abc123/share/longId\n * ```\n *\n * @remarks\n * - The returned URL can be embedded in a QR code for document sharing.\n * - The method fetches the document to obtain its longId, which is required for the URL.\n * - Ensure the documentUid is valid and accessible by the current client.\n */\n getDocumentQrCode(documentUid: string, longId?: string): Promise<string | null>;\n /**\n * Retrieves detailed information about a specific version of a document type.\n *\n * This method fetches version-specific metadata, schema definitions, and validation rules\n * for a particular document type version. Essential for understanding the exact format\n * and requirements for document submission in a specific version.\n *\n * @param id - The unique identifier of the document type\n * @param versionId - The unique identifier of the specific version to retrieve\n * @returns Promise resolving to document type version response object or standard error\n *\n * @example\n * ```typescript\n * // Get specific version details for e-invoice\n * const invoiceV1_1 = await client.getDocumentTypeVersion(1, 1);\n * if ('id' in invoiceV1_1) {\n * console.log('Version number:', invoiceV1_1.versionNumber);\n * console.log('Schema:', invoiceV1_1.jsonSchema);\n * console.log('Status:', invoiceV1_1.status);\n * }\n *\n * // Compare different versions\n * const [v1_0, v1_1] = await Promise.all([\n * client.getDocumentTypeVersion(1, 0),\n * client.getDocumentTypeVersion(1, 1)\n * ]);\n *\n * // Handle version not found\n * const result = await client.getDocumentTypeVersion(1, 999);\n * if ('error' in result) {\n * console.error('Version not found:', result.error.message);\n * }\n * ```\n *\n * @remarks\n * - Returns StandardError object if document type ID or version ID doesn't exist\n * - Version information includes JSON schema for validation\n * - Different versions may have different validation rules and field requirements\n * - Use this to ensure your documents conform to the specific version requirements\n * - Version status indicates if the version is active, deprecated, or under development\n */\n getDocumentTypeVersion(id: number, versionId: number): Promise<DocumentTypeVersionResponse>;\n static fromP12(clientId: string, clientSecret: string, environment: 'sandbox' | 'production', p12Input: Buffer | string, passphrase: string, onBehalfOf?: string, debug?: boolean): MyInvoisClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,IAAW,iBAAiB;CAAC;CAAK,MAAE;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA"}
|
package/dist/index71.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index71.cts","names":[],"sources":["../src/utils/document.d.ts"],"sourcesContent":["import { InvoiceSubmission, AllDocumentsV1_1, SigningCredentials, SignedPropertiesObject, UBLDocument, CompleteInvoice, SignedInfoObject, UnitTypeCode, InvoiceLineItem } from '../types';\nimport type { ClassificationCode } from '../types';\nimport type { TaxTypeCode } from '../types';\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 * Determines if a line item uses fixed rate taxation\n */\nexport declare const isFixedRateTax: (item: InvoiceLineItem) => boolean;\n/**\n * Determines if a line item uses percentage taxation\n */\nexport declare const isPercentageTax: (item: InvoiceLineItem) => boolean;\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport declare const calculateExpectedTaxAmount: (item: InvoiceLineItem) => number;\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport declare function sortObjectKeys(obj: unknown): unknown;\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport declare const canonicalizeJSON: (obj: unknown) => string;\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 declare const generateCleanInvoiceObject: (invoice: AllDocumentsV1_1) => InvoiceSubmission;\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport declare const generateCleanUBLDocument: (invoices: AllDocumentsV1_1[]) => UBLDocument;\n/**\n * Step 1: Transform the document for hashing or transmission\n * Removes UBLExtensions and Signature, and minifies the JSON\n * Returns the minified, cleaned JSON string\n *\n * FIXED: Use regex-based minification to match PowerShell script exactly\n */\nexport declare const transformDocumentForHashing: (invoices: AllDocumentsV1_1[]) => string;\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport declare const calculateDocumentDigest: (invoices: AllDocumentsV1_1[]) => string;\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n * FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData\n */\nexport declare const calculateCertificateDigest: (certificatePem: string) => string;\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport declare const extractCertificateInfo: (certificatePem: string) => {\n issuerName: string;\n serialNumber: string;\n subjectName: string;\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 declare const createSignedProperties: (certificateDigest: string, signingTime: string, issuerName: string, serialNumber: string) => SignedPropertiesObject;\n/**\n * Step 6: Calculate SignedProperties Digest\n * Calculates the digest over the correct structure for validator compliance.\n * FIXED: Calculate digest from SignedProperties only (without Target wrapper)\n */\nexport declare const calculateSignedPropertiesDigest: (signedProperties: SignedPropertiesObject, useTargetWrapper?: boolean) => string;\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport declare const createSignedInfoAndSign: (docDigest: string, propsDigest: string, privateKeyPem: string) => {\n signedInfo: SignedInfoObject;\n signatureValue: string;\n};\n/**\n * Signs the minified document string using the provided private key PEM\n * Returns the signature as a base64 string\n * FIXED: Match PowerShell script exactly - first compute hash, then sign the hash\n */\nexport declare const signDocumentString: (documentString: string, privateKeyPem: string) => string;\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport declare const generateCompleteDocument: (invoices: AllDocumentsV1_1[], signingCredentials: SigningCredentials) => CompleteInvoice;\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport declare 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/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport declare 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/**\n * Calculates invoice totals from line items\n */\nexport declare const calculateInvoiceTotals: (lineItems: InvoiceLineItem[]) => {\n legalMonetaryTotal: {\n taxExclusiveAmount: number;\n taxInclusiveAmount: number;\n payableAmount: number;\n };\n taxTotal: {\n taxAmount: number;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAE,iBAAA,CAAA,KAAA,MAAA,eAAA;AACF,IAAW,kBAAkB,CAAC,KAAK,MAAM,eAAgB;AACzD,IAAW,6BAA6B,CAAC,KAAK,MAAM,eAAgB;AACpE,IAAW,iBAAiB,CAAC,GAAI;AACjC,IAAE,mBAAA,CAAA,GAAA;AACF,IAAE,6BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,2BAA2B;CAAC;CAAK,MAAM;CAAE,MAAA;AAAA;AACpD,IAAE,8BAAA,CAAA,KAAA,MAAA,gBAAA;AACF,IAAW,0BAA0B,CAAC,KAAK,MAAM,gBAAiB;AAClE,IAAE,6BAAA,CAAA,GAAA;AACF,IAAW,yBAAyB,CAAC,GAAI;AACzC,IAAE,yBAAA,CAAA,KAAA,MAAA,sBAAA;AACF,IAAW,kCAAkC,CAAC,KAAK,MAAM,sBAAe;AACxE,IAAE,0BAAA,CAAA,KAAA,MAAA,gBAAA;AACF,IAAW,qBAAqB,CAAC,GAAI;AACrC,IAAE,2BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,8BAA8B;CAAC;CAAK,MAAM;CAAoB,MAAM;CAAG,MAAA;AAAA;AAClF,IAAE,6BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,yBAAyB,CAAC,KAAK,MAAM,eAAgB"}
|
|
1
|
+
{"version":3,"file":"index71.cts","names":[],"sources":["../src/utils/document.d.ts"],"sourcesContent":["import { InvoiceSubmission, AllDocumentsV1_1, SigningCredentials, SignedPropertiesObject, UBLDocument, CompleteInvoice, SignedInfoObject, UnitTypeCode, InvoiceLineItem } from '../types';\nimport type { ClassificationCode } from '../types';\nimport type { TaxTypeCode } from '../types';\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 * Determines if a line item uses fixed rate taxation\n */\nexport declare const isFixedRateTax: (item: InvoiceLineItem) => boolean;\n/**\n * Determines if a line item uses percentage taxation\n */\nexport declare const isPercentageTax: (item: InvoiceLineItem) => boolean;\n/**\n * Calculates expected tax amount for a line item based on its tax type\n */\nexport declare const calculateExpectedTaxAmount: (item: InvoiceLineItem) => number;\n/**\n * Helper function to recursively sort object keys for JSON canonicalization\n */\nexport declare function sortObjectKeys(obj: unknown): unknown;\n/**\n * Enhanced canonicalization following MyInvois specification exactly\n * Key changes: ensure consistent ordering and formatting\n */\nexport declare const canonicalizeJSON: (obj: unknown) => string;\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 declare const generateCleanInvoiceObject: (invoice: AllDocumentsV1_1) => InvoiceSubmission;\n/**\n * Generates the complete UBL document structure with namespace declarations\n */\nexport declare const generateCleanUBLDocument: (invoices: AllDocumentsV1_1[]) => UBLDocument;\n/**\n * Step 1: Transform the document for hashing or transmission\n * Removes UBLExtensions and Signature, and minifies the JSON\n * Returns the minified, cleaned JSON string\n *\n * FIXED: Use regex-based minification to match PowerShell script exactly\n */\nexport declare const transformDocumentForHashing: (invoices: AllDocumentsV1_1[]) => string;\n/**\n * Step 2: Calculate Document Digest\n * FIXED: Remove UBLExtensions and Signature before hashing (DS322)\n * Based on working implementation pattern\n */\nexport declare const calculateDocumentDigest: (invoices: AllDocumentsV1_1[]) => string;\n/**\n * Step 4: Calculate Certificate Digest\n * Enhanced to handle certificate content properly\n * FIXED: Match PowerShell script exactly - use raw certificate data like $cert.RawData\n */\nexport declare const calculateCertificateDigest: (certificatePem: string) => string;\n/**\n * Enhanced certificate info extraction with better error handling\n * FIXED: Normalize issuer name format to match MyInvois expectations (DS326)\n */\nexport declare const extractCertificateInfo: (certificatePem: string) => {\n issuerName: string;\n serialNumber: string;\n subjectName: string;\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 declare const createSignedProperties: (certificateDigest: string, signingTime: string, issuerName: string, serialNumber: string) => SignedPropertiesObject;\n/**\n * Step 6: Calculate SignedProperties Digest\n * Calculates the digest over the correct structure for validator compliance.\n * FIXED: Calculate digest from SignedProperties only (without Target wrapper)\n */\nexport declare const calculateSignedPropertiesDigest: (signedProperties: SignedPropertiesObject, useTargetWrapper?: boolean) => string;\n/**\n * Step 3: Create SignedInfo and calculate signature\n * Enhanced with better structure and signature generation\n */\nexport declare const createSignedInfoAndSign: (docDigest: string, propsDigest: string, privateKeyPem: string) => {\n signedInfo: SignedInfoObject;\n signatureValue: string;\n};\n/**\n * Signs the minified document string using the provided private key PEM\n * Returns the signature as a base64 string\n * FIXED: Match PowerShell script exactly - first compute hash, then sign the hash\n */\nexport declare const signDocumentString: (documentString: string, privateKeyPem: string) => string;\n/**\n * Complete document generation with signatures\n * Follows the complete MyInvois JSON signature creation process (Steps 1-7)\n */\nexport declare const generateCompleteDocument: (invoices: AllDocumentsV1_1[], signingCredentials: SigningCredentials) => CompleteInvoice;\n/**\n * Creates a line item with percentage-based taxation (e.g., SST, GST)\n */\nexport declare 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 discountAmount?: number;\n discountRate?: number;\n}) => InvoiceLineItem;\n/**\n * Creates a line item with fixed rate taxation (e.g., Tourism Tax)\n */\nexport declare 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 discountAmount?: number;\n discountRate?: number;\n}) => InvoiceLineItem;\n/**\n * Calculates invoice totals from line items\n */\nexport declare const calculateInvoiceTotals: (lineItems: InvoiceLineItem[]) => {\n legalMonetaryTotal: {\n taxExclusiveAmount: number;\n taxInclusiveAmount: number;\n payableAmount: number;\n };\n taxTotal: {\n taxAmount: number;\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,IAAE,iBAAA,CAAA,KAAA,MAAA,eAAA;AACF,IAAW,kBAAkB,CAAC,KAAK,MAAM,eAAgB;AACzD,IAAW,6BAA6B,CAAC,KAAK,MAAM,eAAgB;AACpE,IAAW,iBAAiB,CAAC,GAAI;AACjC,IAAE,mBAAA,CAAA,GAAA;AACF,IAAE,6BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,2BAA2B;CAAC;CAAK,MAAM;CAAE,MAAA;AAAA;AACpD,IAAE,8BAAA,CAAA,KAAA,MAAA,gBAAA;AACF,IAAW,0BAA0B,CAAC,KAAK,MAAM,gBAAiB;AAClE,IAAE,6BAAA,CAAA,GAAA;AACF,IAAW,yBAAyB,CAAC,GAAI;AACzC,IAAE,yBAAA,CAAA,KAAA,MAAA,sBAAA;AACF,IAAW,kCAAkC,CAAC,KAAK,MAAM,sBAAe;AACxE,IAAE,0BAAA,CAAA,KAAA,MAAA,gBAAA;AACF,IAAW,qBAAqB,CAAC,GAAI;AACrC,IAAE,2BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,8BAA8B;CAAC;CAAK,MAAM;CAAoB,MAAM;CAAG,MAAA;AAAA;AAClF,IAAE,6BAAA;CAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;AACF,IAAW,yBAAyB,CAAC,KAAK,MAAM,eAAgB"}
|
package/dist/index8.cjs
CHANGED
|
@@ -1,4 +1,62 @@
|
|
|
1
|
-
const require_apiQueue = require('./apiQueue-DDXeQJDC.cjs');
|
|
2
1
|
|
|
3
|
-
|
|
4
|
-
|
|
2
|
+
//#region src/types/classification-codes.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Enum representing the allowed classification codes with descriptive names.
|
|
5
|
+
* Provides a more readable way to reference classification codes.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const code = ClassificationCodeEnum.ComputerSmartphoneOrTablet;
|
|
9
|
+
* console.log(code); // Output: "003"
|
|
10
|
+
*/
|
|
11
|
+
let ClassificationCodeEnum = /* @__PURE__ */ function(ClassificationCodeEnum$1) {
|
|
12
|
+
ClassificationCodeEnum$1["BreastfeedingEquipment"] = "001";
|
|
13
|
+
ClassificationCodeEnum$1["ChildCareCentresAndKindergartensFees"] = "002";
|
|
14
|
+
ClassificationCodeEnum$1["ComputerSmartphoneOrTablet"] = "003";
|
|
15
|
+
ClassificationCodeEnum$1["ConsolidatedEInvoice"] = "004";
|
|
16
|
+
ClassificationCodeEnum$1["ConstructionMaterials"] = "005";
|
|
17
|
+
ClassificationCodeEnum$1["Disbursement"] = "006";
|
|
18
|
+
ClassificationCodeEnum$1["Donation"] = "007";
|
|
19
|
+
ClassificationCodeEnum$1["ECommerceEInvoiceToBuyer"] = "008";
|
|
20
|
+
ClassificationCodeEnum$1["ECommerceSelfBilledToSellerLogistics"] = "009";
|
|
21
|
+
ClassificationCodeEnum$1["EducationFees"] = "010";
|
|
22
|
+
ClassificationCodeEnum$1["GoodsOnConsignmentConsignor"] = "011";
|
|
23
|
+
ClassificationCodeEnum$1["GoodsOnConsignmentConsignee"] = "012";
|
|
24
|
+
ClassificationCodeEnum$1["GymMembership"] = "013";
|
|
25
|
+
ClassificationCodeEnum$1["InsuranceEducationMedicalBenefits"] = "014";
|
|
26
|
+
ClassificationCodeEnum$1["InsuranceTakafulLife"] = "015";
|
|
27
|
+
ClassificationCodeEnum$1["InterestFinancingExpenses"] = "016";
|
|
28
|
+
ClassificationCodeEnum$1["InternetSubscription"] = "017";
|
|
29
|
+
ClassificationCodeEnum$1["LandAndBuilding"] = "018";
|
|
30
|
+
ClassificationCodeEnum$1["MedicalExamLearningDisabilities"] = "019";
|
|
31
|
+
ClassificationCodeEnum$1["MedicalExamVaccination"] = "020";
|
|
32
|
+
ClassificationCodeEnum$1["MedicalExpensesSeriousDiseases"] = "021";
|
|
33
|
+
ClassificationCodeEnum$1["Others"] = "022";
|
|
34
|
+
ClassificationCodeEnum$1["PetroleumOperations"] = "023";
|
|
35
|
+
ClassificationCodeEnum$1["PrivateRetirementSchemeDeferredAnnuity"] = "024";
|
|
36
|
+
ClassificationCodeEnum$1["MotorVehicle"] = "025";
|
|
37
|
+
ClassificationCodeEnum$1["SubscriptionBooksJournalsEtc"] = "026";
|
|
38
|
+
ClassificationCodeEnum$1["Reimbursement"] = "027";
|
|
39
|
+
ClassificationCodeEnum$1["RentalOfMotorVehicle"] = "028";
|
|
40
|
+
ClassificationCodeEnum$1["EVChargingFacilities"] = "029";
|
|
41
|
+
ClassificationCodeEnum$1["RepairAndMaintenance"] = "030";
|
|
42
|
+
ClassificationCodeEnum$1["ResearchAndDevelopment"] = "031";
|
|
43
|
+
ClassificationCodeEnum$1["ForeignIncome"] = "032";
|
|
44
|
+
ClassificationCodeEnum$1["SelfBilledBettingGaming"] = "033";
|
|
45
|
+
ClassificationCodeEnum$1["SelfBilledImportationGoods"] = "034";
|
|
46
|
+
ClassificationCodeEnum$1["SelfBilledImportationServices"] = "035";
|
|
47
|
+
ClassificationCodeEnum$1["SelfBilledOthers"] = "036";
|
|
48
|
+
ClassificationCodeEnum$1["SelfBilledMonetaryPaymentToAgents"] = "037";
|
|
49
|
+
ClassificationCodeEnum$1["SportsEquipmentRentalFeesEtc"] = "038";
|
|
50
|
+
ClassificationCodeEnum$1["SupportingEquipmentDisabledPerson"] = "039";
|
|
51
|
+
ClassificationCodeEnum$1["VoluntaryContributionProvidentFund"] = "040";
|
|
52
|
+
ClassificationCodeEnum$1["DentalExamTreatment"] = "041";
|
|
53
|
+
ClassificationCodeEnum$1["FertilityTreatment"] = "042";
|
|
54
|
+
ClassificationCodeEnum$1["TreatmentHomeCareNursingEtc"] = "043";
|
|
55
|
+
ClassificationCodeEnum$1["VouchersGiftCardsLoyaltyPoints"] = "044";
|
|
56
|
+
ClassificationCodeEnum$1["SelfBilledNonMonetaryPaymentToAgents"] = "045";
|
|
57
|
+
return ClassificationCodeEnum$1;
|
|
58
|
+
}({});
|
|
59
|
+
|
|
60
|
+
//#endregion
|
|
61
|
+
exports.ClassificationCodeEnum = ClassificationCodeEnum;
|
|
62
|
+
//# sourceMappingURL=index8.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index8.cjs","names":[],"sources":["../src/types/classification-codes.d.ts"],"sourcesContent":["/**\n * Represents the allowed classification codes for e-Invoice items.\n * Based on the documentation: https://sdk.myinvois.hasil.gov.my/codes/classification-codes/\n */\nexport type ClassificationCode =\n | '001' // Breastfeeding equipment\n | '002' // Child care centres and kindergartens fees\n | '003' // Computer, smartphone or tablet\n | '004' // Consolidated e-Invoice\n | '005' // Construction materials (as specified under Fourth Schedule of the Lembaga Pembangunan Industri Pembinaan Malaysia Act 1994)\n | '006' // Disbursement\n | '007' // Donation\n | '008' // e-Commerce - e-Invoice to buyer / purchaser\n | '009' // e-Commerce - Self-billed e-Invoice to seller, logistics, etc.\n | '010' // Education fees\n | '011' // Goods on consignment (Consignor)\n | '012' // Goods on consignment (Consignee)\n | '013' // Gym membership\n | '014' // Insurance - Education and medical benefits\n | '015' // Insurance - Takaful or life insurance\n | '016' // Interest and financing expenses\n | '017' // Internet subscription\n | '018' // Land and building\n | '019' // Medical examination for learning disabilities and early intervention or rehabilitation treatments of learning disabilities\n | '020' // Medical examination or vaccination expenses\n | '021' // Medical expenses for serious diseases\n | '022' // Others\n | '023' // Petroleum operations (as defined in Petroleum (Income Tax) Act 1967)\n | '024' // Private retirement scheme or deferred annuity scheme\n | '025' // Motor vehicle\n | '026' // Subscription of books / journals / magazines / newspapers / other similar publications\n | '027' // Reimbursement\n | '028' // Rental of motor vehicle\n | '029' // EV charging facilities (Installation, rental, sale / purchase or subscription fees)\n | '030' // Repair and maintenance\n | '031' // Research and development\n | '032' // Foreign income\n | '033' // Self-billed - Betting and gaming\n | '034' // Self-billed - Importation of goods\n | '035' // Self-billed - Importation of services\n | '036' // Self-billed - Others\n | '037' // Self-billed - Monetary payment to agents, dealers or distributors\n | '038' // Sports equipment, rental / entry fees for sports facilities, registration in sports competition or sports training fees imposed by associations / sports clubs / companies registered with the Sports Commissioner or Companies Commission of Malaysia and carrying out sports activities as listed under the Sports Development Act 1997\n | '039' // Supporting equipment for disabled person\n | '040' // Voluntary contribution to approved provident fund\n | '041' // Dental examination or treatment\n | '042' // Fertility treatment\n | '043' // Treatment and home care nursing, daycare centres and residential care centers\n | '044' // Vouchers, gift cards, loyalty points, etc\n | '045' // Self-billed - Non-monetary payment to agents, dealers or distributors\n\n/**\n * Enum representing the allowed classification codes with descriptive names.\n * Provides a more readable way to reference classification codes.\n *\n * @example\n * const code = ClassificationCodeEnum.ComputerSmartphoneOrTablet;\n * console.log(code); // Output: \"003\"\n */\nexport enum ClassificationCodeEnum {\n BreastfeedingEquipment = '001',\n ChildCareCentresAndKindergartensFees = '002',\n ComputerSmartphoneOrTablet = '003',\n ConsolidatedEInvoice = '004',\n ConstructionMaterials = '005',\n Disbursement = '006',\n Donation = '007',\n ECommerceEInvoiceToBuyer = '008',\n ECommerceSelfBilledToSellerLogistics = '009',\n EducationFees = '010',\n GoodsOnConsignmentConsignor = '011',\n GoodsOnConsignmentConsignee = '012',\n GymMembership = '013',\n InsuranceEducationMedicalBenefits = '014',\n InsuranceTakafulLife = '015',\n InterestFinancingExpenses = '016',\n InternetSubscription = '017',\n LandAndBuilding = '018',\n MedicalExamLearningDisabilities = '019',\n MedicalExamVaccination = '020',\n MedicalExpensesSeriousDiseases = '021',\n Others = '022',\n PetroleumOperations = '023',\n PrivateRetirementSchemeDeferredAnnuity = '024',\n MotorVehicle = '025',\n SubscriptionBooksJournalsEtc = '026',\n Reimbursement = '027',\n RentalOfMotorVehicle = '028',\n EVChargingFacilities = '029',\n RepairAndMaintenance = '030',\n ResearchAndDevelopment = '031',\n ForeignIncome = '032',\n SelfBilledBettingGaming = '033',\n SelfBilledImportationGoods = '034',\n SelfBilledImportationServices = '035',\n SelfBilledOthers = '036',\n SelfBilledMonetaryPaymentToAgents = '037',\n SportsEquipmentRentalFeesEtc = '038',\n SupportingEquipmentDisabledPerson = '039',\n VoluntaryContributionProvidentFund = '040',\n DentalExamTreatment = '041',\n FertilityTreatment = '042',\n TreatmentHomeCareNursingEtc = '043',\n VouchersGiftCardsLoyaltyPoints = '044',\n SelfBilledNonMonetaryPaymentToAgents = '045',\n}\n\n/**\n * Interface representing a classification code entry.\n * Contains the code and its corresponding description.\n */\nexport interface Classification {\n code: ClassificationCode\n description: string\n}\n"],"mappings":";;;;;;;;;;AA2DA,IAAY,4EAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AACD"}
|