### Serve Static Files using npx serve Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Starts a static file server in the 'examples' directory using the `serve` package. This is a solution for browser-related issues where examples might not work due to improper serving of static assets. It requires `npx` and the `serve` package to be installed. ```bash # Solution: Use a static file server npx serve examples/ ``` -------------------------------- ### Install Project Dependencies using npm Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Installs all the necessary project dependencies listed in the `package.json` file. This is a common troubleshooting step when encountering 'Module not found' errors. It requires `npm` to be installed and accessible in the environment. ```bash # Solution: Install dependencies npm install ``` -------------------------------- ### Install vietqr-ts Package Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Provides commands for installing the 'vietqr-ts' package using npm or yarn, addressing 'Cannot find module 'vietqr-ts' errors due to missing installation. ```bash # Install package npm install vietqr-ts # Or using yarn yarn add vietqr-ts ``` -------------------------------- ### Install vietqr-ts with pnpm Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Instructions for installing the vietqr-ts library using the pnpm package manager. This is the primary method for adding the library to your project. ```bash pnpm add vietqr-ts ``` -------------------------------- ### Install tsx Package using npm Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Installs the `tsx` package as a development dependency. This is typically required for running TypeScript files directly during development or testing, and resolves 'Cannot find module 'tsx'' errors. It requires `npm` to be installed. ```bash # Solution: Install tsx npm install -D tsx ``` -------------------------------- ### Install Dependencies and Build Project Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/CONTRIBUTING.md Installs project dependencies using npm and then builds the project. These are essential steps after cloning the repository. ```bash npm install npm run build ``` -------------------------------- ### Minimal Reproduction for Bug Reports (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md This code snippet provides an example of creating a minimal reproduction case for bug reports. It defines a sample configuration for QR generation and logs the output. It also lists essential environment details like Node.js and package versions, which are crucial for debugging. ```typescript // Good bug report example const config = { bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: 50000 }; const qrData = generateVietQR(config); console.log(qrData); // Share exact output // Include: // - Node.js version: node --version // - Package version: npm list vietqr-ts // - Operating system // - Error messages (full stack trace) ``` -------------------------------- ### Install VietQR TypeScript Library Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Demonstrates how to install the VietQR TypeScript library using different package managers (npm, yarn, pnpm). This is the first step to integrate VietQR into your project. ```bash npm install vietqr-ts ``` ```bash yarn add vietqr-ts ``` ```bash pnpm add vietqr-ts ``` -------------------------------- ### Provide Clear Payment Instructions in TypeScript Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Logs clear payment instructions to the console, including the amount, currency, recipient account number, and bank name. This function is intended for user-facing output to guide the payment process. It requires `amount`, `accountNumber`, and `bankName` to be defined. ```typescript console.log(`Scan QR to pay ${amount} VND`); console.log(`To: ${accountNumber} (${bankName})`); ``` -------------------------------- ### Create Output Directory using mkdir Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Creates a directory named 'output' inside the 'examples' directory, including any necessary parent directories. This command is used to ensure that an output directory exists for saving generated image files, resolving issues where images are not saved. It requires shell access and the `mkdir` command. ```bash # Solution: Create output directory mkdir -p examples/output ``` -------------------------------- ### Type Checking with VietQRConfig Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Illustrates how to use the `VietQRConfig` type from vietqr-ts to ensure type safety during configuration. This example shows proper type assertion and leverages TypeScript's autocompletion and type checking capabilities. ```typescript // Check types are working import { VietQRConfig } from 'vietqr-ts'; const config: VietQRConfig = { bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }; // TypeScript should provide autocomplete and type checking ``` -------------------------------- ### Unit Test Example in TypeScript Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/CONTRIBUTING.md An example of how to write unit tests using Vitest for a TypeScript function. It demonstrates testing for correct output and error handling. ```typescript import { describe, it, expect } from 'vitest'; import { yourFunction } from '../path/to/module'; describe('YourFeature', () => { it('should handle valid input correctly', () => { const result = yourFunction(validInput); expect(result).toEqual(expectedOutput); }); it('should throw error for invalid input', () => { expect(() => yourFunction(invalidInput)).toThrow('Expected error message'); }); }); ``` -------------------------------- ### Install VietQR TypeScript Library Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/README.md Installs the vietqr-ts package using npm. This is the first step to integrate VietQR functionality into your TypeScript project. ```bash npm install vietqr-ts ``` -------------------------------- ### Compress and Resize Images for VietQR Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Offers TypeScript functions using the 'sharp' library to compress and resize images, helping to overcome the 'Image size exceeds 2MB limit' error. It includes usage examples for checking and applying these transformations. ```typescript // Solution 1: Compress image before processing async function compressImage(buffer: Buffer, maxSizeBytes: number): Promise { // Using sharp library (install: npm install sharp) const sharp = require('sharp'); let quality = 90; let compressed = buffer; while (compressed.length > maxSizeBytes && quality > 10) { compressed = await sharp(buffer) .jpeg({ quality }) .toBuffer(); quality -= 10; } return compressed; } // Solution 2: Resize image async function resizeImage(buffer: Buffer, maxDimension: number): Promise { const sharp = require('sharp'); return await sharp(buffer) .resize(maxDimension, maxDimension, { fit: 'inside', withoutEnlargement: true }) .toBuffer(); } // Usage const originalBuffer = await fs.readFile('large-qr.png'); // Check size first if (!isValidImageSize(originalBuffer)) { const resized = await resizeImage(originalBuffer, 1000); const result = decode(resized); } else { const result = decode(originalBuffer); } ``` -------------------------------- ### Correct vs. Incorrect Code Usage Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Illustrates the convention for presenting code examples, distinguishing between incorrect (❌) and correct (✅) usage patterns. This pattern is used throughout the documentation to provide clear, actionable code snippets. ```typescript // ❌ Wrong - shows incorrect usage const badExample = incorrectCode(); // ✅ Correct - shows proper usage const goodExample = correctCode(); // Usage context and explanation // Expected output or behavior ``` -------------------------------- ### TypeScript Unit Test Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/architecture.md Example unit tests for the VietQR generation and validation logic. It includes tests for generating static QR codes and validating input parameters like bank BIN. ```typescript describe('VietQR Generation', () => { describe('Static QR', () => { it('should generate valid static QR', () => { const result = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); expect(result.qrType).toBe('static'); expect(result.amount).toBeUndefined(); }); }); describe('Validation', () => { it('should reject invalid bank BIN', () => { expect(() => { generateVietQR({ bankBin: '123', // Too short accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); }).toThrow(ValidationError); }); }); }); ``` -------------------------------- ### TypeScript Benchmarking Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/architecture.md A simple benchmark for measuring the performance of the `generateVietQR` function. It uses `performance.now()` to calculate the duration and asserts it against a threshold. ```typescript // Simple benchmarks in tests const start = performance.now(); const result = generateVietQR(config); const duration = performance.now() - start; expect(duration).toBeLessThan(10); // 10ms threshold ``` -------------------------------- ### Donation/Tipping QR Generation (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates a static QR code for donations or tipping, where the amount is not fixed. Outputs an SVG image. ```typescript // Static QR for donations (no fixed amount) const donationQR = generateQRImage({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', message: 'Support our cause' }, { format: 'svg', width: 500 }); ``` -------------------------------- ### Optimize QR Generation: Parallel Processing Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Compares sequential QR generation with parallel processing using `Promise.all` to improve performance for large batches. Demonstrates how to efficiently generate multiple QR codes concurrently. ```typescript // Problem: Sequential processing async function slowBatchGeneration(configs: VietQRConfig[]) { const results = []; for (const config of configs) { const qr = await generateQRImage(generateVietQR(config).rawData); results.push(qr); } return results; } // Solution: Parallel processing async function fastBatchGeneration(configs: VietQRConfig[]) { return await Promise.all( configs.map(async (config) => { const qrData = generateVietQR(config); return await generateQRImage(qrData.rawData); }) ); } // With rate limiting for very large batches async function rateLimitedBatchGeneration( configs: VietQRConfig[], concurrency: number = 10 ) { const results = []; for (let i = 0; i < configs.length; i += concurrency) { const batch = configs.slice(i, i + concurrency); const batchResults = await Promise.all( batch.map(async (config) => { const qrData = generateVietQR(config); return await generateQRImage(qrData.rawData); }) ); results.push(...batchResults); } return results; } ``` -------------------------------- ### Payment Terminal QR Generation (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates a QR code for point-of-sale payment terminals, specifying merchant category and outputting in SVG format for scalability. ```typescript // Generate QR for point-of-sale const terminalQR = generateQRImage({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: saleAmount, merchantCategory: '5812' // Restaurant }, { format: 'svg', // SVG for terminal display width: 300 }); ``` -------------------------------- ### Generate QR Code Image (Browser CDN) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates a QR code image for display in a web browser using a CDN link for the vietqr-ts library. Supports various payment details and image formatting options. ```html ``` -------------------------------- ### Generate VietQR with Correct Bank BIN Format Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md This example illustrates the correct format for the 'bankBin' parameter when generating a VietQR code using the vietqr-ts library. The bank BIN must be exactly 6 digits. Incorrect formats will lead to errors. Ensure the 'generateVietQR' function is available and the library is imported. ```typescript // ❌ Wrong - not 6 digits generateVietQR({ bankBin: '9704', // Too short accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); // ❌ Wrong - contains non-digits generateVietQR({ bankBin: 'MB9704', // Has letters accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); // ✅ Correct - exactly 6 digits generateVietQR({ bankBin: '970422', // MB Bank accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); ``` -------------------------------- ### Verify Payment Amount (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Implements a security check to verify that the parsed QR code amount matches the expected amount to prevent fraudulent transactions. ```typescript if (parsedData.amount !== expectedAmount) { throw new Error('Amount mismatch'); } ``` -------------------------------- ### Example Conventional Commit Messages Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/CONTRIBUTING.md Illustrates the format and types of commit messages used in the VietQR project, adhering to the Conventional Commits specification. ```bash feat(parser): add support for additional data field 62 fix(validator): correct CRC checksum validation logic docs(readme): update API examples with error handling test(generator): add tests for edge cases in amount formatting ``` -------------------------------- ### Using HTTPS for Secure QR Code Image Transmission Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/common-patterns.md Illustrates the importance of using HTTPS for serving QR code images to ensure secure transmission. It shows a 'good' example using an HTTPS URL for the `` tag and a 'bad' example using HTTP. ```html // Good - secure transmission // Bad - insecure transmission ``` -------------------------------- ### Generate VietQR Data (Node.js/TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates raw VietQR data for payment transactions using the vietqr-ts library. Requires bank details, account number, service code, and optionally an amount. ```typescript import { generateVietQR, parse, validate } from 'vietqr-ts'; const qr = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: '50000' }); console.log(qr.rawData); ``` ```javascript import { generateVietQR } from 'vietqr-ts'; const qr = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); ``` ```javascript const { generateVietQR } = require('vietqr-ts'); const qr = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }); ``` -------------------------------- ### E-commerce Checkout QR Generation (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates a QR code for e-commerce checkout, including order details like amount, message, and bill number. Outputs a PNG image suitable for display. ```typescript // Generate QR for order payment const orderQR = generateQRImage({ bankBin: merchantBank, accountNumber: merchantAccount, serviceCode: 'QRIBFTTA', amount: orderTotal.toString(), message: `Order #${orderId}`, billNumber: orderId }, { format: 'png', width: 400 }); // Display QR to customer displayQRCode(orderQR.dataUrl); ``` -------------------------------- ### VietQR Combined Options Example (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/parsing.md Provides an example of using multiple options simultaneously with `parseWithOptions`. This snippet shows how to combine `strictMode`, `maxLength`, and `extractPartialOnError` to create a tailored parsing behavior according to specific application requirements. ```typescript import { parseWithOptions } from 'vietqr-ts'; const result = parseWithOptions(qrString, { strictMode: true, maxLength: 2048, extractPartialOnError: false }); ``` -------------------------------- ### Add Troubleshooting Entry (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md This markdown structure is for adding troubleshooting entries to the documentation. It details the error message, cause, and provides code examples for incorrect and correct solutions using TypeScript. ```markdown ### Error: "[Error Message]" **Cause**: [Why this error occurs] **Solutions:** ```typescript // ❌ Wrong incorrectCode(); // ✅ Correct correctCode(); ``` **Prevention:** - How to avoid this error ``` -------------------------------- ### Error Handling Convention Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Details the convention for documenting errors, including the error type, a descriptive message, and suggested solutions. This pattern aids developers in diagnosing and resolving issues encountered while using the library. ```typescript // Error type DecodingErrorType.NO_QR_CODE_FOUND // Error message "No QR code found in image" // Solution // 1. Check image quality // 2. Ensure QR code is visible // 3. Verify image format (PNG/JPEG) ``` -------------------------------- ### Invoice Payment QR Generation (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Generates a VietQR string suitable for embedding in PDF invoices, including invoice-specific details like description and number. ```typescript // Generate QR for invoice const invoiceQR = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: invoiceAmount, message: invoiceDescription, billNumber: invoiceNumber, purpose: 'PAYMENT' }); // Embed in PDF invoice embedInPDF(invoiceQR.rawData); ``` -------------------------------- ### Configure TypeScript for vietqr-ts Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Provides a `tsconfig.json` configuration to resolve 'Could not find a declaration file' errors when using vietqr-ts. Ensures TypeScript can correctly recognize the library's types. ```json // tsconfig.json { "compilerOptions": { "moduleResolution": "node", "esModuleInterop": true, "skipLibCheck": false } } ``` -------------------------------- ### TypeScript Type Definition Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Shows inline TypeScript type definitions for functions and interfaces, as used in the documentation. This includes function signatures with parameter types and return types, as well as interface definitions with their properties. ```typescript function generateVietQR(config: VietQRConfig): VietQRResult interface VietQRConfig { bankBin: string; // Required: 6-digit bank code accountNumber: string; // Required: Account or card number // ... more fields } ``` -------------------------------- ### Generate Static VietQR Code (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Example of generating a static VietQR code. Static QR codes do not have a predefined amount, allowing the user to enter it upon scanning. This is suitable for donations or variable payment scenarios. ```typescript const staticQR = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' // No amount = static QR }); ``` -------------------------------- ### Boundary Test Cases for Limit Conditions (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/security-review.md Example security test cases for boundary conditions, focusing on testing limit values for inputs. This includes maximum and minimum lengths, off-by-one scenarios, and integer boundaries to ensure robustness. ```typescript // Test limit conditions - Maximum length inputs - Zero-length inputs - Off-by-one boundaries - Integer boundary values ``` -------------------------------- ### Import Styles for vietqr-ts Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/api-reference.md Demonstrates how to import functions from the vietqr-ts library in different module formats: ESM, CommonJS, and for browser environments using a bundler. Ensures proper setup for various project types. ```typescript // ESM (recommended) import { generateVietQR, generateQRImage } from 'vietqr-ts'; // CommonJS const { generateVietQR, generateQRImage } = require('vietqr-ts'); // Browser (via bundler) import { generateVietQR } from 'vietqr-ts'; ``` -------------------------------- ### Browser: Handle Data URL for QR Images Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Provides solutions for ensuring QR images display correctly in browsers, focusing on proper handling of data URLs generated by `generateQRImage`. Includes checks and explicit formatting for base64 encoded images. ```typescript // Problem: Not handling data URL correctly const qrImage = await generateQRImage(qrData); img.src = qrImage; // Should work // If not working, check: console.log(qrImage.substring(0, 50)); // Should start with "data:image/" // Solution: Explicit data URL handling const qrImage = await generateQRImage(qrData, { format: 'png' }); if (qrImage.startsWith('data:image/png;base64,')) { img.src = qrImage; } else { console.error('Invalid image data URL'); } ``` -------------------------------- ### Generate Dynamic VietQR Code (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Example of generating a dynamic VietQR code. Dynamic QR codes include a fixed amount, making them ideal for specific invoices or orders where the payment amount is predetermined. This is generally recommended for single-use payments. ```typescript const dynamicQR = generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: '50000' // With amount = dynamic QR }); ``` -------------------------------- ### Build QR String Manually (vietqr-ts) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/utilities.md Demonstrates how to manually construct a VietQR string using helper functions like `encodeField` and `calculateCRC`, along with constants like `NAPAS_GUID`. This example shows the step-by-step process of adding fields and finalizing the QR code string. ```typescript import { encodeField, calculateCRC, NAPAS_GUID } from 'vietqr-ts'; // Build QR string step by step const fields = [ encodeField('00', '01'), // Payload format indicator encodeField('01', '11'), // Initiation method (static) // Field 38: Consumer account information `3854${ encodeField('00', NAPAS_GUID) + // GUID encodeField('01', '0006970403') + // BIN + Service code encodeField('02', '01234567') // Account number }`, encodeField('52', '0000'), // Merchant category encodeField('53', '704'), // Currency encodeField('58', 'VN') // Country ]; const partialQR = fields.join('') + '6304'; const crc = calculateCRC(partialQR); const completeQR = partialQR + crc; console.log('Complete QR:', completeQR); ``` -------------------------------- ### Clone VietQR Repository Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/CONTRIBUTING.md Clones the VietQR repository from GitHub to your local machine. This is the first step in setting up the project for development. ```bash git clone https://github.com/YOUR-USERNAME/vietqr-ts.git cd vietqr-ts ``` -------------------------------- ### Validate VietQR Code with CRC, Parse, and Verify Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md This snippet demonstrates how to validate a QR code string using the vietqr-ts library. It includes steps for checking the Cyclic Redundancy Check (CRC), parsing the QR code data, and performing a full validation. Ensure the 'vietqr-ts' library is installed. ```typescript import { parse, validate, verifyCRC } from 'vietqr-ts'; const qrString = "your-qr-string-here"; // Step 1: Check CRC console.log('CRC valid:', verifyCRC(qrString)); // Step 2: Try parsing const parseResult = parse(qrString); console.log('Parse result:', parseResult); // Step 3: Validate if parsed successfully if (parseResult.success) { const validation = validate(parseResult.data, qrString); console.log('Validation:', validation); } ``` -------------------------------- ### Configure VS Code for Documentation Indexing Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Shows how to configure VS Code settings to enable TypeScript path suggestions and to include local documentation files for indexing and search. This helps in better IDE integration with project documentation. ```json { "typescript.suggest.paths": true, "docs.sources": [ "docs/context7/**/*.md" ] } ``` -------------------------------- ### Manage VietQR Message Length for NAPAS Compliance Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md This example addresses the 'Message exceeds maximum length (25 characters)' error in vietqr-ts by showing how to truncate messages or use the 'billNumber' field. It ensures compliance with NAPAS specifications. The helper function 'sanitizeMessage' provides a way to truncate messages with an ellipsis. ```typescript // ❌ Wrong - message too long generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', message: 'Payment for invoice number INV-2024-0001' // 42 characters }); // ✅ Solution 1: Truncate message generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', message: 'Payment for order #1234'.substring(0, 25) // 25 characters }); // ✅ Solution 2: Use billNumber for tracking generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', message: 'Invoice payment', billNumber: 'INV-2024-0001' // Use billNumber for tracking }); // ✅ Solution 3: Helper function function sanitizeMessage(message: string): string { if (message.length <= 25) return message; return message.substring(0, 22) + '...'; // Truncate with ellipsis } ``` -------------------------------- ### Basic Bash Commands for Documentation Access Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Provides fundamental Bash commands for interacting with documentation files within the project. This includes reading markdown files, searching for specific content using grep, and opening files in a browser. ```bash # Read API reference cat docs/context7/api-reference.md # Search for specific topic grep -r "generateVietQR" docs/context7/ # View in browser open docs/context7/api-reference.md ``` -------------------------------- ### Generate QR Code with Mock Implementation (JavaScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/browser-example.html This JavaScript snippet demonstrates a mock implementation for generating a QR code. It captures form data, simulates QR code generation, and displays a placeholder image. It includes basic input validation for bank BIN and account number. Error handling is also included. ```javascript const form = document.getElementById('qrForm'); const result = document.getElementById('result'); const errorDiv = document.getElementById('error'); const qrImage = document.getElementById('qrImage'); const downloadBtn = document.getElementById('downloadBtn'); form.addEventListener('submit', async (e) => { e.preventDefault(); try { errorDiv.style.display = 'none'; result.classList.remove('show'); const bankBin = document.getElementById('bankBin').value; const accountNumber = document.getElementById('accountNumber').value; const amount = document.getElementById('amount').value; const message = document.getElementById('message').value; const qrSize = parseInt(document.getElementById('qrSize').value); // Validate inputs if (!bankBin || !accountNumber) { throw new Error('Please fill in all required fields'); } // Mock implementation for demonstration console.log('Generating QR with:', { bankBin, accountNumber, amount, message }); // Display result document.getElementById('qrType').textContent = amount ? 'Dynamic' : 'Static'; document.getElementById('qrBank').textContent = bankBin; document.getElementById('qrAccount').textContent = accountNumber; document.getElementById('qrAmount').textContent = amount || 'User to enter'; // Show placeholder QR qrImage.src = `https://via.placeholder.com/${qrSize}/667eea/FFFFFF?text=QR+Code`; result.classList.add('show'); // Setup download button downloadBtn.onclick = () => { const link = document.createElement('a'); link.download = `vietqr-${accountNumber}-${Date.now()}.png`; link.href = qrImage.src; link.click(); }; } catch (error) { errorDiv.textContent = `Error: ${error.message}`; errorDiv.style.display = 'block'; console.error('QR generation error:', error); } }); ``` -------------------------------- ### NAPAS GUID Constant (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/api-reference.md Defines the globally unique identifier (GUID) for NAPAS in the context of VietQR. This constant is used in constructing or parsing VietQR data. It is a string value. ```typescript const NAPAS_GUID = 'A000000727'; ``` -------------------------------- ### Run Tests and Lint Project Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/CONTRIBUTING.md Executes the test suite, generates test coverage reports, and runs the linter to check for code style issues. These commands are used for verifying code quality. ```bash npm test npm run test:coverage npm run lint npm run type-check ``` -------------------------------- ### Handle Account Number Length Error Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md This snippet shows the length limitation for account numbers in VietQR codes. It provides examples of account numbers that exceed the 19-character limit and a correct example within the limit. ```typescript // ❌ Wrong accountNumber: '012345678901234567890' // 21 chars // ✅ Correct accountNumber: '0123456789' // Within limit ``` -------------------------------- ### Complete QR Generation Workflow (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/README.md Demonstrates a complete workflow for generating a QR code using the vietqr-ts library. It includes validating configuration, generating the raw QR data, and then creating a QR image in PNG format with a specified size. ```typescript import { generateVietQR, generateQRImage, validateVietQRConfig } from 'vietqr-ts'; // 1. Validate configuration const config = { bankBin: '970403', accountNumber: '01234567', serviceCode: 'QRIBFTTA' as const, initiationMethod: '11' as const, amount: '50000' }; validateVietQRConfig(config); // 2. Generate QR data const qrData = generateVietQR(config); // 3. Generate QR image const qrImage = await generateQRImage({ data: qrData.rawData, format: 'png', size: 300 }); console.log('QR Image Data URI:', qrImage.dataURI); ``` -------------------------------- ### Handle Invalid Bank BIN Error Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md This example illustrates incorrect and correct formats for the 'bankBin' parameter when generating a VietQR code. It highlights that the bank BIN must be exactly 6 numeric digits, showing examples of invalid and valid inputs. ```typescript // ❌ Wrong bankBin: '123' // Too short bankBin: '12345678' // Too long bankBin: 'ABC123' // Non-numeric // ✅ Correct bankBin: '970422' // Exactly 6 digits ``` -------------------------------- ### Generate VietQR Code Configuration (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Shows the basic TypeScript configuration to generate a VietQR code. It requires essential details like bank BIN, account number, and service code. The output is a string representation of the QR code data. ```typescript import { generateVietQR, type VietQRConfig } from 'vietqr-ts'; const config: VietQRConfig = { bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' }; const result = generateVietQR(config); ``` -------------------------------- ### Query QR Generation Patterns with Context7 Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/README.md Demonstrates how to query for QR generation patterns using the Context7 library for the VietQR-TS project. This involves specifying the library, the topic of interest, and the desired depth of detail. ```typescript const docs = await context7.query({ library: '/binhnguyenduc/vietqr-ts', topic: 'QR generation', depth: 'detailed' }); ``` -------------------------------- ### Validate QR Data (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/README.md Validates parsed QR code data to ensure its integrity and security before processing payments. Checks for validity and corruption. ```typescript const result = parse(qrString); if (result.success) { const validation = validate(result.data, qrString); if (validation.isValid && !validation.isCorrupted) { // Safe to process } } ``` -------------------------------- ### Generate VietQR Data and QR Image Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/README.md Demonstrates how to generate VietQR payment data and then create a QR code image. It uses the `generateVietQR` function to create the raw data and `generateQRImage` to render it as a PNG image. Assumes the 'vietqr-ts' library is installed and imported. ```typescript import { generateVietQR, generateQRImage } from 'vietqr-ts'; // Generate VietQR data const qrData = generateVietQR({ bankBin: '970403', accountNumber: '01234567', serviceCode: 'QRIBFTTA', initiationMethod: '11', amount: '50000' }); // Generate QR code image const qrImage = await generateQRImage({ data: qrData.rawData, format: 'png', size: 300 }); console.log('QR Image:', qrImage.dataURI); ``` -------------------------------- ### Parallel vs Sequential QR Image Generation Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/common-patterns.md Demonstrates performance optimization by generating multiple QR codes in parallel using `Promise.all` compared to sequential generation. This is beneficial when multiple QR codes need to be created simultaneously, reducing overall processing time. Assumes the existence of a `generateQRImage` function. ```typescript // Good - parallel const [qr1, qr2, qr3] = await Promise.all([ generateQRImage(data1), generateQRImage(data2), generateQRImage(data3) ]); // Bad - sequential const qr1 = await generateQRImage(data1); const qr2 = await generateQRImage(data2); const qr3 = await generateQRImage(data3); ``` -------------------------------- ### Run VietQR-TS Tests with npm Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/README.md Provides common npm commands for running the test suite of the VietQR-TS project. These commands allow developers to execute all tests, run tests with code coverage analysis, or run tests in watch mode for continuous feedback during development. ```bash # Run all tests npm test # Run tests with coverage npm run test:coverage # Run tests in watch mode npm run test:watch ``` -------------------------------- ### TypeScript Pure Function Example Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/architecture.md Demonstrates the principle of immutability in TypeScript functions, ensuring they do not modify input parameters and always return new data. This promotes predictable behavior and easier debugging. ```typescript // ✅ Pure function - always returns new data function generateVietQR(config: VietQRConfig): VietQRResult { return { ...computedData }; } // ❌ Avoided - no mutation of inputs function generateVietQR(config: VietQRConfig): void { config.crc = calculateCRC(config); // Mutates input } ``` -------------------------------- ### Tree-shakeable Imports with vietqr-ts Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Demonstrates how to optimize bundle size when using vietqr-ts by importing only necessary functions. Importing specific functions (tree-shakeable) results in a smaller bundle compared to importing the entire module with a wildcard. ```typescript // ✅ Better - tree-shakeable import { generateVietQR } from 'vietqr-ts'; // ❌ Larger bundle - imports everything import * as VietQR from 'vietqr-ts'; ``` -------------------------------- ### NAPAS GUID Constant (vietqr-ts) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/api/utilities.md Defines the `NAPAS_GUID` constant, which is the globally unique identifier for VietQR within the NAPAS system. This constant is a string and is essential for constructing the '38' field in a VietQR code. ```typescript const NAPAS_GUID = "A000000727"; ``` ```typescript import { NAPAS_GUID } from 'vietqr-ts'; console.log('NAPAS GUID:', NAPAS_GUID); // "A000000727" // Used in Field 38 (GUID) const field38 = `3810${NAPAS_GUID}`; ``` -------------------------------- ### Integrate VietQR Library for QR Generation (JavaScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/examples/browser-example.html This JavaScript snippet shows how to use the actual VietQR library to generate QR code images. It requires importing the `generateQRImage` function. The function takes transaction details and configuration options for format, size, and error correction. The output is a data URL for the QR code image. ```javascript // In production, import from your built bundle or CDN // import { generateQRImage } from 'https://unpkg.com/vietqr-ts'; // ... inside the event listener ... /* const qrResult = await generateQRImage({ bankBin, accountNumber, serviceCode: 'QRIBFTTA', ...(amount && { amount }), ...(message && { message }) }, { format: 'png', width: qrSize, errorCorrectionLevel: 'M' }); qrImage.src = qrResult.dataUrl; */ ``` -------------------------------- ### Correct Async/Await Usage for QR Image Generation (vietqr-ts) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Ensures QR images are correctly generated in a browser environment by using 'async/await' with the 'generateQRImage' function. Missing 'await' can lead to images not being generated properly. ```typescript // ✅ Correct const qr = await generateQRImage(config); // ❌ Wrong - missing await const qr = generateQRImage(config); ``` -------------------------------- ### Generate VietQR with Valid Amount Values Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Demonstrates correct and incorrect usage of the `generateVietQR` function with respect to the 'amount' parameter, highlighting the need for positive numerical values. Includes a validation helper function. ```typescript // ❌ Wrong amounts generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: -1000 // Negative }); generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: 0 // Zero (use undefined for static QR) }); generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: NaN // Not a number }); // ✅ Correct amounts generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA', amount: 50000 // Positive number }); generateVietQR({ bankBin: '970422', accountNumber: '0123456789', serviceCode: 'QRIBFTTA' // amount: undefined - Static QR (omit amount) }); // ✅ Amount validation helper function validateAmount(amount: number | undefined): number | undefined { if (amount === undefined) return undefined; if (isNaN(amount) || amount <= 0) { throw new Error('Amount must be a positive number'); } return Math.floor(amount); // Ensure integer } ``` -------------------------------- ### Prevent Manual QR String Modification Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Illustrates the correct way to generate QR strings using the library to ensure the CRC is automatically calculated and advises against manual modification, which can lead to CRC errors. ```typescript // Always use library-generated QR strings const qrData = generateVietQR(config); const qrString = qrData.rawData; // CRC automatically calculated // Don't manually modify QR strings // ❌ const modified = qrString.replace('...', '...'); // Breaks CRC ``` -------------------------------- ### Correct Import Path for vietqr-ts Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/faq.md Illustrates the correct way to import functions from the 'vietqr-ts' library. Avoid importing from sub-paths like '/dist/index' to prevent 'Module not found' errors and ensure proper package utilization. ```typescript // ✅ Correct import { generateVietQR } from 'vietqr-ts'; // ❌ Wrong import { generateVietQR } from 'vietqr-ts/dist/index'; ``` -------------------------------- ### Import vietqr-ts in TypeScript (ESM/CommonJS) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Demonstrates correct import statements for the vietqr-ts library in TypeScript projects, supporting both ECMAScript Modules (ESM) and CommonJS module systems. Highlights common import errors to avoid. ```typescript // ✅ Correct imports // ESM import { generateVietQR } from 'vietqr-ts'; // CommonJS const { generateVietQR } = require('vietqr-ts'); // ❌ Wrong imports import vietqr from 'vietqr-ts'; // Default import not supported import { generateVietQR } from 'vietqr'; // Wrong package name ``` -------------------------------- ### Safe Regex Patterns: Simple Optional Groups (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/security-review.md An example of a regular expression with a simple optional group. While potentially optimizable for performance, this pattern is not vulnerable to ReDoS due to its non-nested optional structure. ```typescript /^\d+(\.\d+)?$/ // Number with optional decimal // Note: Could be optimized but not vulnerable ``` -------------------------------- ### Safe Regex Patterns: Fixed-Length (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/security-review.md Examples of regular expressions with fixed-length quantifiers. These patterns are considered safe from ReDoS vulnerabilities because they do not involve backtracking. They enforce an exact number of characters, such as digits or letters. ```typescript /^\d{2}$/ // Exactly 2 digits /^\d{3}$/ // Exactly 3 digits /^\d{4}$/ // Exactly 4 digits /^\d{6}$/ // Exactly 6 digits /^[A-Za-z]{2}$/ // Exactly 2 letters ``` -------------------------------- ### Detect and Convert Image Formats for VietQR Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md Provides a TypeScript function to detect image formats using `vietqr-ts` and convert unsupported formats (like non-PNG/JPEG) to PNG using canvas. This addresses the 'Image format not supported' error. ```typescript import { detectImageFormat } from 'vietqr-ts'; async function convertToSupportedFormat(file: File): Promise { const format = detectImageFormat(await file.arrayBuffer()); if (format === 'png' || format === 'jpeg') { return Buffer.from(await file.arrayBuffer()); } // Convert to PNG using canvas (browser) const img = new Image(); img.src = URL.createObjectURL(file); await new Promise((resolve) => { img.onload = resolve; }); const canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; const ctx = canvas.getContext('2d'); ctx?.drawImage(img, 0, 0); const blob = await new Promise((resolve) => { canvas.toBlob((blob) => resolve(blob!), 'image/png'); }); return Buffer.from(await blob.arrayBuffer()); } ``` -------------------------------- ### Enable Verbose Logging for QR Generation (TypeScript) Source: https://github.com/binhnguyenduc/vietqr-ts/blob/main/docs/context7/troubleshooting.md This function demonstrates how to enable verbose logging during the QR code generation process. It logs input configuration, generated QR data, CRC validation, and parsing results. It utilizes functions like `generateVietQR`, `verifyCRC`, `parse`, and `validate` from the vietqr-ts library. ```typescript function debugQRGeneration(config: VietQRConfig) { console.log('Input config:', JSON.stringify(config, null, 2)); const qrData = generateVietQR(config); console.log('Generated QR string:', qrData.rawData); console.log('QR length:', qrData.rawData.length); console.log('Is dynamic:', qrData.isDynamic); const crcValid = verifyCRC(qrData.rawData); console.log('CRC valid:', crcValid); const parseResult = parse(qrData.rawData); console.log('Parse result:', JSON.stringify(parseResult, null, 2)); if (parseResult.success) { const validation = validate(parseResult.data, qrData.rawData); console.log('Validation:', JSON.stringify(validation, null, 2)); } return qrData; } ```