<commit_before>"use strict";

var https = require('https');
// var http = require('http');
var querystring = require('querystring');

module.exports = function (apiKey, options) {
    options = options || {};

    var responseToResource = function(response) {
        if (response === null) {
            return false;
        }

        var types = {
            Address: 'Address',
            CustomsItem: 'CustomsItem',
            CustomsInfo: 'CustomsInfo',
            Parcel: 'Parcel',
            Shipment: 'Shipment',
            Rate: 'Rate',
            Refund: 'Refund',
            Batch: 'Batch',
            ScanForm: 'ScanForm',
            Tracker: 'Tracker',
            PostageLabel: 'PostageLabel',
            Event: 'Event'
        };

        var prefixes = {
            adr: 'Address',
            sf: 'ScanForm',
            cstitem: 'CustomsItem',
            cstinfo: 'CustomsInfo',
            prcl: 'Parcel',
            shp: 'Shipment',
            rate: 'Rate',
            refund: 'Refund',
            batch: 'Batch',
            trk: 'Tracker',
            postagelabel: 'PostageLabel',
            evt: 'Event'
        };

        if (Object.prototype.toString.call(response) === '[object Array]') {
            for (var i = 0; i < response.length; i++) {
                response[i] = responseToResource(response[i]);
            }
        } else if (typeof response === 'object') {
            var cls = 'Resource';
            if (response.object !== undefined && response.object !== null) {
                if (types[response.object] !== undefined && types[response.object] !== null) {
                    cls = types[response.object];
                }
            } else if (response.id !== undefined && response.id !== null) {
                var prefix = response.id.substr(0, response.id.indexOf('_'));
                if(prefixes[prefix] !== undefined && prefixes[prefix] !== null) {
                    cls = prefixes[prefix];
                }
            }

            var obj = new easypost[cls];
            obj.createFromResponse(response);
            return obj;
        }

        return response;
    }

    var Requestor = function(myApiKey) {
        this.apiKey = myApiKey || apiKey;
        this.queryParams = {};

    }
    Requestor.prototype.request = function(method, path, params, callback) {
        delete params.apiKey;
        this.encodeParams(params);
        var requestData = querystring.stringify(this.queryParams);

        path = '/v2' + path;

        // console.log(method, "request for", path);
        // console.log("http request", requestData);

        var auth = 'Basic ' + new Buffer(apiKey + ":").toString('base64');

        var request_options = {
            host: 'api.easypost.com',
            port: '443',
            // host: 'localhost',
            // port: '5000',
            path: path,
            method: method,
            headers: {
                'Authorization': auth,
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': requestData.length
            }
        };

        var req = https.request(request_options);
        // var req = http.request(request_options);
        this.responseListener(req, callback);
        req.write(requestData);
        req.end();
    }
    Requestor.prototype.encodeParams = function(params, prefix) {
        if(typeof params !== 'object') {
            return params;
        }

        var newParams = [];

        Object.keys(params).forEach(function(key) {
            if(params[key] === null) {
                return;
            }

            var newKey = key;
            if(prefix && key) {
                var newKey = prefix + '[' + key + ']';
            }

            if(params[key] instanceof easypost.Resource) {
                params[key] = {id: params[key].id};
            }

            if(typeof params[key] === 'object') {
                newParams.push(this.encodeParams(params[key], newKey));
            } else {
                this.queryParams[newKey] = params[key];
            }

        }, this);

        return newParams;
    }
    Requestor.prototype.responseListener = function(req, cb) {
        if(typeof cb !== 'function') {
            throw new easypost.Error("Requestor requires a callback to handle response.");
        }

        req.on('response', function(res) {
            var response = '';
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                response += chunk;
            });
            res.on('end', function() {
                var err = null;
                try {
                    response = JSON.parse(response);
                    if(response.error !== undefined && response.error !== null) {
                        err = new easypost.Error(response.error.message);
                        err.param = response.error.param;
                        response = null;
                    }<commit_msg>Fixed logging of error messages. (response.error.message does not exist)<commit_after>"use strict";

var https = require('https');
// var http = require('http');
var querystring = require('querystring');

module.exports = function (apiKey, options) {
    options = options || {};

    var responseToResource = function(response) {
        if (response === null) {
            return false;
        }

        var types = {
            Address: 'Address',
            CustomsItem: 'CustomsItem',
            CustomsInfo: 'CustomsInfo',
            Parcel: 'Parcel',
            Shipment: 'Shipment',
            Rate: 'Rate',
            Refund: 'Refund',
            Batch: 'Batch',
            ScanForm: 'ScanForm',
            Tracker: 'Tracker',
            PostageLabel: 'PostageLabel',
            Event: 'Event'
        };

        var prefixes = {
            adr: 'Address',
            sf: 'ScanForm',
            cstitem: 'CustomsItem',
            cstinfo: 'CustomsInfo',
            prcl: 'Parcel',
            shp: 'Shipment',
            rate: 'Rate',
            refund: 'Refund',
            batch: 'Batch',
            trk: 'Tracker',
            postagelabel: 'PostageLabel',
            evt: 'Event'
        };

        if (Object.prototype.toString.call(response) === '[object Array]') {
            for (var i = 0; i < response.length; i++) {
                response[i] = responseToResource(response[i]);
            }
        } else if (typeof response === 'object') {
            var cls = 'Resource';
            if (response.object !== undefined && response.object !== null) {
                if (types[response.object] !== undefined && types[response.object] !== null) {
                    cls = types[response.object];
                }
            } else if (response.id !== undefined && response.id !== null) {
                var prefix = response.id.substr(0, response.id.indexOf('_'));
                if(prefixes[prefix] !== undefined && prefixes[prefix] !== null) {
                    cls = prefixes[prefix];
                }
            }

            var obj = new easypost[cls];
            obj.createFromResponse(response);
            return obj;
        }

        return response;
    }

    var Requestor = function(myApiKey) {
        this.apiKey = myApiKey || apiKey;
        this.queryParams = {};

    }
    Requestor.prototype.request = function(method, path, params, callback) {
        delete params.apiKey;
        this.encodeParams(params);
        var requestData = querystring.stringify(this.queryParams);

        path = '/v2' + path;

        // console.log(method, "request for", path);
        // console.log("http request", requestData);

        var auth = 'Basic ' + new Buffer(apiKey + ":").toString('base64');

        var request_options = {
            host: 'api.easypost.com',
            port: '443',
            // host: 'localhost',
            // port: '5000',
            path: path,
            method: method,
            headers: {
                'Authorization': auth,
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded',
                'Content-Length': requestData.length
            }
        };

        var req = https.request(request_options);
        // var req = http.request(request_options);
        this.responseListener(req, callback);
        req.write(requestData);
        req.end();
    }
    Requestor.prototype.encodeParams = function(params, prefix) {
        if(typeof params !== 'object') {
            return params;
        }

        var newParams = [];

        Object.keys(params).forEach(function(key) {
            if(params[key] === null) {
                return;
            }

            var newKey = key;
            if(prefix && key) {
                var newKey = prefix + '[' + key + ']';
            }

            if(params[key] instanceof easypost.Resource) {
                params[key] = {id: params[key].id};
            }

            if(typeof params[key] === 'object') {
                newParams.push(this.encodeParams(params[key], newKey));
            } else {
                this.queryParams[newKey] = params[key];
            }

        }, this);

        return newParams;
    }
    Requestor.prototype.responseListener = function(req, cb) {
        if(typeof cb !== 'function') {
            throw new easypost.Error("Requestor requires a callback to handle response.");
        }

        req.on('response', function(res) {
            var response = '';
            res.setEncoding('utf8');
            res.on('data', function(chunk) {
                response += chunk;
            });
            res.on('end', function() {
                var err = null;
                try {
                    response = JSON.parse(response);
                    if(response.error !== undefined && response.error !== null) {
                        err = new easypost.Error(response.error);
                        err.param = response.error.param;
                        response = null;
                    }
{'fraction_non_alphanumeric': 0.13203271258252045, 'fraction_numerical': 0.002561828751601143, 'mean_word_length': 1.5080306399802323, 'pattern_counts': {'":': 2, '<': 5, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6144830', 'n_tokens_mistral': 2716, 'n_tokens_neox': 2605, 'n_words': 578}