UNPKG

usezap-cli

Version:

Zap CLI - Command-line interface for Zap API client

59 lines (53 loc) 2.06 kB
const iconv = require('iconv-lite'); const lpad = (str, width) => { let paddedStr = str; while (paddedStr.length < width) { paddedStr = ' ' + paddedStr; } return paddedStr; }; const rpad = (str, width) => { let paddedStr = str; while (paddedStr.length < width) { paddedStr = paddedStr + ' '; } return paddedStr; }; const parseDataFromResponse = (response, disableParsingResponseJson = false) => { // Parse the charset from content type: https://stackoverflow.com/a/33192813 const charsetMatch = /charset=([^()<>@,;:"/[\]?.=\s]*)/i.exec(response.headers['content-type'] || ''); // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec#using_exec_with_regexp_literals const charsetValue = charsetMatch?.[1]; const dataBuffer = Buffer.from(response.data); // Overwrite the original data for backwards compatibility let data; if (iconv.encodingExists(charsetValue)) { data = iconv.decode(dataBuffer, charsetValue); } else { data = iconv.decode(dataBuffer, 'utf-8'); } // Try to parse response to JSON, this can quietly fail try { // Filter out ZWNBSP character // https://gist.github.com/antic183/619f42b559b78028d1fe9e7ae8a1352d data = data.replace(/^\uFEFF/, ''); if (!disableParsingResponseJson) { // Add debug logging to help identify JSON parsing issues if (process.env.ZAP_DEBUG) { console.log('[DEBUG] Attempting to parse JSON response data:', data.substring(0, 200) + (data.length > 200 ? '...' : '')); } data = JSON.parse(data); } } catch (error) { // Add better error logging for debugging if (process.env.ZAP_DEBUG) { console.log('[DEBUG] JSON parsing failed in parseDataFromResponse:', error.message); console.log('[DEBUG] Raw data that failed to parse:', data.substring(0, 500) + (data.length > 500 ? '...' : '')); } } return { data, dataBuffer }; }; module.exports = { lpad, rpad, parseDataFromResponse };