text
stringlengths
9
39.2M
dir
stringlengths
26
295
lang
stringclasses
185 values
created_date
timestamp[us]
updated_date
timestamp[us]
repo_name
stringlengths
1
97
repo_full_name
stringlengths
7
106
star
int64
1k
183k
len_tokens
int64
1
13.8M
```javascript var ip = exports; var { Buffer } = require('buffer'); var os = require('os'); ip.toBuffer = function (ip, buff, offset) { offset = ~~offset; var result; if (this.isV4Format(ip)) { result = buff || new Buffer(offset + 4); ip.split(/\./g).map((byte) => { result[offset++] = parseInt(byte, 10) & 0xff; }); } else if (this.isV6Format(ip)) { var sections = ip.split(':', 8); var i; for (i = 0; i < sections.length; i++) { var isv4 = this.isV4Format(sections[i]); var v4Buffer; if (isv4) { v4Buffer = this.toBuffer(sections[i]); sections[i] = v4Buffer.slice(0, 2).toString('hex'); } if (v4Buffer && ++i < 8) { sections.splice(i, 0, v4Buffer.slice(2, 4).toString('hex')); } } if (sections[0] === '') { while (sections.length < 8) sections.unshift('0'); } else if (sections[sections.length - 1] === '') { while (sections.length < 8) sections.push('0'); } else if (sections.length < 8) { for (i = 0; i < sections.length && sections[i] !== ''; i++); var argv = [i, 1]; for (i = 9 - sections.length; i > 0; i--) { argv.push('0'); } sections.splice.apply(sections, argv); } result = buff || new Buffer(offset + 16); for (i = 0; i < sections.length; i++) { var word = parseInt(sections[i], 16); result[offset++] = (word >> 8) & 0xff; result[offset++] = word & 0xff; } } if (!result) { throw Error(`Invalid ip address: ${ip}`); } return result; }; ip.toString = function (buff, offset, length) { offset = ~~offset; length = length || (buff.length - offset); var result = []; var i; if (length === 4) { // IPv4 for (i = 0; i < length; i++) { result.push(buff[offset + i]); } result = result.join('.'); } else if (length === 16) { // IPv6 for (i = 0; i < length; i += 2) { result.push(buff.readUInt16BE(offset + i).toString(16)); } result = result.join(':'); result = result.replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3'); result = result.replace(/:{3,4}/, '::'); } return result; }; var ipv4Regex = /^(\d{1,3}\.){3,3}\d{1,3}$/; var ipv6Regex = /^(::)?(((\d{1,3}\.){3}(\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i; ip.isV4Format = function (ip) { return ipv4Regex.test(ip); }; ip.isV6Format = function (ip) { return ipv6Regex.test(ip); }; function _normalizeFamily(family) { if (family === 4) { return 'ipv4'; } if (family === 6) { return 'ipv6'; } return family ? family.toLowerCase() : 'ipv4'; } ip.fromPrefixLen = function (prefixlen, family) { if (prefixlen > 32) { family = 'ipv6'; } else { family = _normalizeFamily(family); } var len = 4; if (family === 'ipv6') { len = 16; } var buff = new Buffer(len); for (var i = 0, n = buff.length; i < n; ++i) { var bits = 8; if (prefixlen < 8) { bits = prefixlen; } prefixlen -= bits; buff[i] = ~(0xff >> bits) & 0xff; } return ip.toString(buff); }; ip.mask = function (addr, mask) { addr = ip.toBuffer(addr); mask = ip.toBuffer(mask); var result = new Buffer(Math.max(addr.length, mask.length)); // Same protocol - do bitwise and var i; if (addr.length === mask.length) { for (i = 0; i < addr.length; i++) { result[i] = addr[i] & mask[i]; } } else if (mask.length === 4) { // IPv6 address and IPv4 mask // (Mask low bits) for (i = 0; i < mask.length; i++) { result[i] = addr[addr.length - 4 + i] & mask[i]; } } else { // IPv6 mask and IPv4 addr for (i = 0; i < result.length - 6; i++) { result[i] = 0; } // ::ffff:ipv4 result[10] = 0xff; result[11] = 0xff; for (i = 0; i < addr.length; i++) { result[i + 12] = addr[i] & mask[i + 12]; } i += 12; } for (; i < result.length; i++) { result[i] = 0; } return ip.toString(result); }; ip.cidr = function (cidrString) { var cidrParts = cidrString.split('/'); var addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.mask(addr, mask); }; ip.subnet = function (addr, mask) { var networkAddress = ip.toLong(ip.mask(addr, mask)); // Calculate the mask's length. var maskBuffer = ip.toBuffer(mask); var maskLength = 0; for (var i = 0; i < maskBuffer.length; i++) { if (maskBuffer[i] === 0xff) { maskLength += 8; } else { var octet = maskBuffer[i] & 0xff; while (octet) { octet = (octet << 1) & 0xff; maskLength++; } } } var numberOfAddresses = Math.pow(2, 32 - maskLength); return { networkAddress: ip.fromLong(networkAddress), firstAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress) : ip.fromLong(networkAddress + 1), lastAddress: numberOfAddresses <= 2 ? ip.fromLong(networkAddress + numberOfAddresses - 1) : ip.fromLong(networkAddress + numberOfAddresses - 2), broadcastAddress: ip.fromLong(networkAddress + numberOfAddresses - 1), subnetMask: mask, subnetMaskLength: maskLength, numHosts: numberOfAddresses <= 2 ? numberOfAddresses : numberOfAddresses - 2, length: numberOfAddresses, contains(other) { return networkAddress === ip.toLong(ip.mask(other, mask)); }, }; }; ip.cidrSubnet = function (cidrString) { var cidrParts = cidrString.split('/'); var addr = cidrParts[0]; if (cidrParts.length !== 2) { throw new Error(`invalid CIDR subnet: ${addr}`); } var mask = ip.fromPrefixLen(parseInt(cidrParts[1], 10)); return ip.subnet(addr, mask); }; ip.not = function (addr) { var buff = ip.toBuffer(addr); for (var i = 0; i < buff.length; i++) { buff[i] = 0xff ^ buff[i]; } return ip.toString(buff); }; ip.or = function (a, b) { var i; a = ip.toBuffer(a); b = ip.toBuffer(b); // same protocol if (a.length === b.length) { for (i = 0; i < a.length; ++i) { a[i] |= b[i]; } return ip.toString(a); // mixed protocols } var buff = a; var other = b; if (b.length > a.length) { buff = b; other = a; } var offset = buff.length - other.length; for (i = offset; i < buff.length; ++i) { buff[i] |= other[i - offset]; } return ip.toString(buff); }; ip.isEqual = function (a, b) { var i; a = ip.toBuffer(a); b = ip.toBuffer(b); // Same protocol if (a.length === b.length) { for (i = 0; i < a.length; i++) { if (a[i] !== b[i]) return false; } return true; } // Swap if (b.length === 4) { var t = b; b = a; a = t; } // a - IPv4, b - IPv6 for (i = 0; i < 10; i++) { if (b[i] !== 0) return false; } var word = b.readUInt16BE(10); if (word !== 0 && word !== 0xffff) return false; for (i = 0; i < 4; i++) { if (a[i] !== b[i + 12]) return false; } return true; }; ip.isPrivate = function (addr) { return /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i .test(addr) || /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(addr) || /^f[cd][0-9a-f]{2}:/i.test(addr) || /^fe80:/i.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.isPublic = function (addr) { return !ip.isPrivate(addr); }; ip.isLoopback = function (addr) { return /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/ .test(addr) || /^fe80::1$/.test(addr) || /^::1$/.test(addr) || /^::$/.test(addr); }; ip.loopback = function (family) { // // Default to `ipv4` // family = _normalizeFamily(family); if (family !== 'ipv4' && family !== 'ipv6') { throw new Error('family must be ipv4 or ipv6'); } return family === 'ipv4' ? '127.0.0.1' : 'fe80::1'; }; // // ### function address (name, family) // #### @name {string|'public'|'private'} **Optional** Name or security // of the network interface. // #### @family {ipv4|ipv6} **Optional** IP family of the address (defaults // to ipv4). // // Returns the address for the network interface on the current system with // the specified `name`: // * String: First `family` address of the interface. // If not found see `undefined`. // * 'public': the first public ip address of family. // * 'private': the first private ip address of family. // * undefined: First address with `ipv4` or loopback address `127.0.0.1`. // ip.address = function (name, family) { var interfaces = os.networkInterfaces(); // // Default to `ipv4` // family = _normalizeFamily(family); // // If a specific network interface has been named, // return the address. // if (name && name !== 'private' && name !== 'public') { var res = interfaces[name].filter((details) => { var itemFamily = _normalizeFamily(details.family); return itemFamily === family; }); if (res.length === 0) { return undefined; } return res[0].address; } var all = Object.keys(interfaces).map((nic) => { // // Note: name will only be `public` or `private` // when this is called. // var addresses = interfaces[nic].filter((details) => { details.family = _normalizeFamily(details.family); if (details.family !== family || ip.isLoopback(details.address)) { return false; } if (!name) { return true; } return name === 'public' ? ip.isPrivate(details.address) : ip.isPublic(details.address); }); return addresses.length ? addresses[0].address : undefined; }).filter(Boolean); return !all.length ? ip.loopback(family) : all[0]; }; ip.toLong = function (ip) { var ipl = 0; ip.split('.').forEach((octet) => { ipl <<= 8; ipl += parseInt(octet); }); return (ipl >>> 0); }; ip.fromLong = function (ipl) { return (`${ipl >>> 24}.${ ipl >> 16 & 255}.${ ipl >> 8 & 255}.${ ipl & 255}`); }; ```
/content/code_sandbox/node_modules/ip/lib/ip.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,273
```javascript /* Module dependencies */ var ElementType = require('domelementtype'); var entities = require('entities'); var unencodedElements = { __proto__: null, style: true, script: true, xmp: true, iframe: true, noembed: true, noframes: true, plaintext: true, noscript: true }; /* Format attributes */ function formatAttrs(attributes, opts) { if (!attributes) return; var output = '', value; // Loop through the attributes for (var key in attributes) { value = attributes[key]; if (output) { output += ' '; } output += key; if ((value !== null && value !== '') || opts.xmlMode) { output += '="' + (opts.decodeEntities ? entities.encodeXML(value) : value) + '"'; } } return output; } /* Self-enclosing tags (stolen from node-htmlparser) */ var singleTag = { __proto__: null, area: true, base: true, basefont: true, br: true, col: true, command: true, embed: true, frame: true, hr: true, img: true, input: true, isindex: true, keygen: true, link: true, meta: true, param: true, source: true, track: true, wbr: true, }; var render = module.exports = function(dom, opts) { if (!Array.isArray(dom) && !dom.cheerio) dom = [dom]; opts = opts || {}; var output = ''; for(var i = 0; i < dom.length; i++){ var elem = dom[i]; if (elem.type === 'root') output += render(elem.children, opts); else if (ElementType.isTag(elem)) output += renderTag(elem, opts); else if (elem.type === ElementType.Directive) output += renderDirective(elem); else if (elem.type === ElementType.Comment) output += renderComment(elem); else if (elem.type === ElementType.CDATA) output += renderCdata(elem); else output += renderText(elem, opts); } return output; }; function renderTag(elem, opts) { // Handle SVG if (elem.name === "svg") opts = {decodeEntities: opts.decodeEntities, xmlMode: true}; var tag = '<' + elem.name, attribs = formatAttrs(elem.attribs, opts); if (attribs) { tag += ' ' + attribs; } if ( opts.xmlMode && (!elem.children || elem.children.length === 0) ) { tag += '/>'; } else { tag += '>'; if (elem.children) { tag += render(elem.children, opts); } if (!singleTag[elem.name] || opts.xmlMode) { tag += '</' + elem.name + '>'; } } return tag; } function renderDirective(elem) { return '<' + elem.data + '>'; } function renderText(elem, opts) { var data = elem.data || ''; // if entities weren't decoded, no need to encode them back if (opts.decodeEntities && !(elem.parent && elem.parent.name in unencodedElements)) { data = entities.encodeXML(data); } return data; } function renderCdata(elem) { return '<![CDATA[' + elem.children[0].data + ']]>'; } function renderComment(elem) { return '<!--' + elem.data + '-->'; } ```
/content/code_sandbox/node_modules/dom-serializer/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
791
```javascript "use strict"; const util_1 = require("util"); const escodegen_1 = require("escodegen"); const esprima_1 = require("esprima"); const ast_types_1 = require("ast-types"); const vm2_1 = require("vm2"); /** * Compiles sync JavaScript code into JavaScript with async Functions. * * @param {String} code JavaScript string to convert * @param {Array} names Array of function names to add `await` operators to * @return {String} Converted JavaScript string with async/await injected * @api public */ function degenerator(code, _names) { if (!Array.isArray(_names)) { throw new TypeError('an array of async function "names" is required'); } // Duplicate the `names` array since it's rude to augment the user args const names = _names.slice(0); const ast = esprima_1.parseScript(code); // First pass is to find the `function` nodes and turn them into async or // generator functions only if their body includes `CallExpressions` to // function in `names`. We also add the names of the functions to the `names` // array. We'll iterate several time, as every iteration might add new items // to the `names` array, until no new names were added in the iteration. let lastNamesLength = 0; do { lastNamesLength = names.length; ast_types_1.visit(ast, { visitVariableDeclaration(path) { if (path.node.declarations) { for (let i = 0; i < path.node.declarations.length; i++) { const declaration = path.node.declarations[i]; if (ast_types_1.namedTypes.VariableDeclarator.check(declaration) && ast_types_1.namedTypes.Identifier.check(declaration.init) && ast_types_1.namedTypes.Identifier.check(declaration.id) && checkName(declaration.init.name, names) && !checkName(declaration.id.name, names)) { names.push(declaration.id.name); } } } return false; }, visitAssignmentExpression(path) { if (ast_types_1.namedTypes.Identifier.check(path.node.left) && ast_types_1.namedTypes.Identifier.check(path.node.right) && checkName(path.node.right.name, names) && !checkName(path.node.left.name, names)) { names.push(path.node.left.name); } return false; }, visitFunction(path) { if (path.node.id) { let shouldDegenerate = false; ast_types_1.visit(path.node, { visitCallExpression(path) { if (checkNames(path.node, names)) { shouldDegenerate = true; } return false; }, }); if (!shouldDegenerate) { return false; } // Got a "function" expression/statement, // convert it into an async function path.node.async = true; // Add function name to `names` array if (!checkName(path.node.id.name, names)) { names.push(path.node.id.name); } } this.traverse(path); }, }); } while (lastNamesLength !== names.length); // Second pass is for adding `await`/`yield` statements to any function // invocations that match the given `names` array. ast_types_1.visit(ast, { visitCallExpression(path) { if (checkNames(path.node, names)) { // A "function invocation" expression, // we need to inject a `AwaitExpression`/`YieldExpression` const delegate = false; const { name, parent: { node: pNode }, } = path; const expr = ast_types_1.builders.awaitExpression(path.node, delegate); if (ast_types_1.namedTypes.CallExpression.check(pNode)) { pNode.arguments[name] = expr; } else { pNode[name] = expr; } } this.traverse(path); }, }); return escodegen_1.generate(ast); } (function (degenerator) { function compile(code, returnName, names, options = {}) { const compiled = degenerator(code, names); const vm = new vm2_1.VM(options); const script = new vm2_1.VMScript(`${compiled};${returnName}`, { filename: options.filename, }); const fn = vm.run(script); if (typeof fn !== 'function') { throw new Error(`Expected a "function" to be returned for \`${returnName}\`, but got "${typeof fn}"`); } const r = function (...args) { try { const p = fn.apply(this, args); if (typeof (p === null || p === void 0 ? void 0 : p.then) === 'function') { return p; } return Promise.resolve(p); } catch (err) { return Promise.reject(err); } }; Object.defineProperty(r, 'toString', { value: fn.toString.bind(fn), enumerable: false, }); return r; } degenerator.compile = compile; })(degenerator || (degenerator = {})); /** * Returns `true` if `node` has a matching name to one of the entries in the * `names` array. * * @param {types.Node} node * @param {Array} names Array of function names to return true for * @return {Boolean} * @api private */ function checkNames({ callee }, names) { let name; if (ast_types_1.namedTypes.Identifier.check(callee)) { name = callee.name; } else if (ast_types_1.namedTypes.MemberExpression.check(callee)) { if (ast_types_1.namedTypes.Identifier.check(callee.object) && ast_types_1.namedTypes.Identifier.check(callee.property)) { name = `${callee.object.name}.${callee.property.name}`; } else { return false; } } else if (ast_types_1.namedTypes.FunctionExpression.check(callee)) { if (callee.id) { name = callee.id.name; } else { return false; } } else { throw new Error(`Don't know how to get name for: ${callee.type}`); } return checkName(name, names); } function checkName(name, names) { // now that we have the `name`, check if any entries match in the `names` array for (let i = 0; i < names.length; i++) { const n = names[i]; if (util_1.isRegExp(n)) { if (n.test(name)) { return true; } } else if (name === n) { return true; } } return false; } module.exports = degenerator; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/degenerator/dist/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,488
```javascript /*! * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of Salesforce.com nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ 'use strict'; var net = require('net'); var urlParse = require('url').parse; var util = require('util'); var pubsuffix = require('./pubsuffix-psl'); var Store = require('./store').Store; var MemoryCookieStore = require('./memstore').MemoryCookieStore; var pathMatch = require('./pathMatch').pathMatch; var VERSION = require('./version'); var punycode; try { punycode = require('punycode'); } catch(e) { console.warn("tough-cookie: can't load punycode; won't use punycode for domain normalization"); } // From RFC6265 S4.1.1 // note that it excludes \x3B ";" var COOKIE_OCTETS = /^[\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]+$/; var CONTROL_CHARS = /[\x00-\x1F]/; // From Chromium // '\r', '\n' and '\0' should be treated as a terminator in // the "relaxed" mode, see: // path_to_url#L60 var TERMINATORS = ['\n', '\r', '\0']; // RFC6265 S4.1.1 defines path value as 'any CHAR except CTLs or ";"' // Note ';' is \x3B var PATH_VALUE = /[\x20-\x3A\x3C-\x7E]+/; // date-time parsing constants (RFC6265 S5.1.1) var DATE_DELIM = /[\x09\x20-\x2F\x3B-\x40\x5B-\x60\x7B-\x7E]/; var MONTH_TO_NUM = { jan:0, feb:1, mar:2, apr:3, may:4, jun:5, jul:6, aug:7, sep:8, oct:9, nov:10, dec:11 }; var NUM_TO_MONTH = [ 'Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec' ]; var NUM_TO_DAY = [ 'Sun','Mon','Tue','Wed','Thu','Fri','Sat' ]; var MAX_TIME = 2147483647000; // 31-bit max var MIN_TIME = 0; // 31-bit min /* * Parses a Natural number (i.e., non-negative integer) with either the * <min>*<max>DIGIT ( non-digit *OCTET ) * or * <min>*<max>DIGIT * grammar (RFC6265 S5.1.1). * * The "trailingOK" boolean controls if the grammar accepts a * "( non-digit *OCTET )" trailer. */ function parseDigits(token, minDigits, maxDigits, trailingOK) { var count = 0; while (count < token.length) { var c = token.charCodeAt(count); // "non-digit = %x00-2F / %x3A-FF" if (c <= 0x2F || c >= 0x3A) { break; } count++; } // constrain to a minimum and maximum number of digits. if (count < minDigits || count > maxDigits) { return null; } if (!trailingOK && count != token.length) { return null; } return parseInt(token.substr(0,count), 10); } function parseTime(token) { var parts = token.split(':'); var result = [0,0,0]; /* RF6256 S5.1.1: * time = hms-time ( non-digit *OCTET ) * hms-time = time-field ":" time-field ":" time-field * time-field = 1*2DIGIT */ if (parts.length !== 3) { return null; } for (var i = 0; i < 3; i++) { // "time-field" must be strictly "1*2DIGIT", HOWEVER, "hms-time" can be // followed by "( non-digit *OCTET )" so therefore the last time-field can // have a trailer var trailingOK = (i == 2); var num = parseDigits(parts[i], 1, 2, trailingOK); if (num === null) { return null; } result[i] = num; } return result; } function parseMonth(token) { token = String(token).substr(0,3).toLowerCase(); var num = MONTH_TO_NUM[token]; return num >= 0 ? num : null; } /* * RFC6265 S5.1.1 date parser (see RFC for full grammar) */ function parseDate(str) { if (!str) { return; } /* RFC6265 S5.1.1: * 2. Process each date-token sequentially in the order the date-tokens * appear in the cookie-date */ var tokens = str.split(DATE_DELIM); if (!tokens) { return; } var hour = null; var minute = null; var second = null; var dayOfMonth = null; var month = null; var year = null; for (var i=0; i<tokens.length; i++) { var token = tokens[i].trim(); if (!token.length) { continue; } var result; /* 2.1. If the found-time flag is not set and the token matches the time * production, set the found-time flag and set the hour- value, * minute-value, and second-value to the numbers denoted by the digits in * the date-token, respectively. Skip the remaining sub-steps and continue * to the next date-token. */ if (second === null) { result = parseTime(token); if (result) { hour = result[0]; minute = result[1]; second = result[2]; continue; } } /* 2.2. If the found-day-of-month flag is not set and the date-token matches * the day-of-month production, set the found-day-of- month flag and set * the day-of-month-value to the number denoted by the date-token. Skip * the remaining sub-steps and continue to the next date-token. */ if (dayOfMonth === null) { // "day-of-month = 1*2DIGIT ( non-digit *OCTET )" result = parseDigits(token, 1, 2, true); if (result !== null) { dayOfMonth = result; continue; } } /* 2.3. If the found-month flag is not set and the date-token matches the * month production, set the found-month flag and set the month-value to * the month denoted by the date-token. Skip the remaining sub-steps and * continue to the next date-token. */ if (month === null) { result = parseMonth(token); if (result !== null) { month = result; continue; } } /* 2.4. If the found-year flag is not set and the date-token matches the * year production, set the found-year flag and set the year-value to the * number denoted by the date-token. Skip the remaining sub-steps and * continue to the next date-token. */ if (year === null) { // "year = 2*4DIGIT ( non-digit *OCTET )" result = parseDigits(token, 2, 4, true); if (result !== null) { year = result; /* From S5.1.1: * 3. If the year-value is greater than or equal to 70 and less * than or equal to 99, increment the year-value by 1900. * 4. If the year-value is greater than or equal to 0 and less * than or equal to 69, increment the year-value by 2000. */ if (year >= 70 && year <= 99) { year += 1900; } else if (year >= 0 && year <= 69) { year += 2000; } } } } /* RFC 6265 S5.1.1 * "5. Abort these steps and fail to parse the cookie-date if: * * at least one of the found-day-of-month, found-month, found- * year, or found-time flags is not set, * * the day-of-month-value is less than 1 or greater than 31, * * the year-value is less than 1601, * * the hour-value is greater than 23, * * the minute-value is greater than 59, or * * the second-value is greater than 59. * (Note that leap seconds cannot be represented in this syntax.)" * * So, in order as above: */ if ( dayOfMonth === null || month === null || year === null || second === null || dayOfMonth < 1 || dayOfMonth > 31 || year < 1601 || hour > 23 || minute > 59 || second > 59 ) { return; } return new Date(Date.UTC(year, month, dayOfMonth, hour, minute, second)); } function formatDate(date) { var d = date.getUTCDate(); d = d >= 10 ? d : '0'+d; var h = date.getUTCHours(); h = h >= 10 ? h : '0'+h; var m = date.getUTCMinutes(); m = m >= 10 ? m : '0'+m; var s = date.getUTCSeconds(); s = s >= 10 ? s : '0'+s; return NUM_TO_DAY[date.getUTCDay()] + ', ' + d+' '+ NUM_TO_MONTH[date.getUTCMonth()] +' '+ date.getUTCFullYear() +' '+ h+':'+m+':'+s+' GMT'; } // S5.1.2 Canonicalized Host Names function canonicalDomain(str) { if (str == null) { return null; } str = str.trim().replace(/^\./,''); // S4.1.2.3 & S5.2.3: ignore leading . // convert to IDN if any non-ASCII characters if (punycode && /[^\u0001-\u007f]/.test(str)) { str = punycode.toASCII(str); } return str.toLowerCase(); } // S5.1.3 Domain Matching function domainMatch(str, domStr, canonicalize) { if (str == null || domStr == null) { return null; } if (canonicalize !== false) { str = canonicalDomain(str); domStr = canonicalDomain(domStr); } /* * "The domain string and the string are identical. (Note that both the * domain string and the string will have been canonicalized to lower case at * this point)" */ if (str == domStr) { return true; } /* "All of the following [three] conditions hold:" (order adjusted from the RFC) */ /* "* The string is a host name (i.e., not an IP address)." */ if (net.isIP(str)) { return false; } /* "* The domain string is a suffix of the string" */ var idx = str.indexOf(domStr); if (idx <= 0) { return false; // it's a non-match (-1) or prefix (0) } // e.g "a.b.c".indexOf("b.c") === 2 // 5 === 3+2 if (str.length !== domStr.length + idx) { // it's not a suffix return false; } /* "* The last character of the string that is not included in the domain * string is a %x2E (".") character." */ if (str.substr(idx-1,1) !== '.') { return false; } return true; } // RFC6265 S5.1.4 Paths and Path-Match /* * "The user agent MUST use an algorithm equivalent to the following algorithm * to compute the default-path of a cookie:" * * Assumption: the path (and not query part or absolute uri) is passed in. */ function defaultPath(path) { // "2. If the uri-path is empty or if the first character of the uri-path is not // a %x2F ("/") character, output %x2F ("/") and skip the remaining steps. if (!path || path.substr(0,1) !== "/") { return "/"; } // "3. If the uri-path contains no more than one %x2F ("/") character, output // %x2F ("/") and skip the remaining step." if (path === "/") { return path; } var rightSlash = path.lastIndexOf("/"); if (rightSlash === 0) { return "/"; } // "4. Output the characters of the uri-path from the first character up to, // but not including, the right-most %x2F ("/")." return path.slice(0, rightSlash); } function trimTerminator(str) { for (var t = 0; t < TERMINATORS.length; t++) { var terminatorIdx = str.indexOf(TERMINATORS[t]); if (terminatorIdx !== -1) { str = str.substr(0,terminatorIdx); } } return str; } function parseCookiePair(cookiePair, looseMode) { cookiePair = trimTerminator(cookiePair); var firstEq = cookiePair.indexOf('='); if (looseMode) { if (firstEq === 0) { // '=' is immediately at start cookiePair = cookiePair.substr(1); firstEq = cookiePair.indexOf('='); // might still need to split on '=' } } else { // non-loose mode if (firstEq <= 0) { // no '=' or is at start return; // needs to have non-empty "cookie-name" } } var cookieName, cookieValue; if (firstEq <= 0) { cookieName = ""; cookieValue = cookiePair.trim(); } else { cookieName = cookiePair.substr(0, firstEq).trim(); cookieValue = cookiePair.substr(firstEq+1).trim(); } if (CONTROL_CHARS.test(cookieName) || CONTROL_CHARS.test(cookieValue)) { return; } var c = new Cookie(); c.key = cookieName; c.value = cookieValue; return c; } function parse(str, options) { if (!options || typeof options !== 'object') { options = {}; } str = str.trim(); // We use a regex to parse the "name-value-pair" part of S5.2 var firstSemi = str.indexOf(';'); // S5.2 step 1 var cookiePair = (firstSemi === -1) ? str : str.substr(0, firstSemi); var c = parseCookiePair(cookiePair, !!options.loose); if (!c) { return; } if (firstSemi === -1) { return c; } // S5.2.3 "unparsed-attributes consist of the remainder of the set-cookie-string // (including the %x3B (";") in question)." plus later on in the same section // "discard the first ";" and trim". var unparsed = str.slice(firstSemi + 1).trim(); // "If the unparsed-attributes string is empty, skip the rest of these // steps." if (unparsed.length === 0) { return c; } /* * S5.2 says that when looping over the items "[p]rocess the attribute-name * and attribute-value according to the requirements in the following * subsections" for every item. Plus, for many of the individual attributes * in S5.3 it says to use the "attribute-value of the last attribute in the * cookie-attribute-list". Therefore, in this implementation, we overwrite * the previous value. */ var cookie_avs = unparsed.split(';'); while (cookie_avs.length) { var av = cookie_avs.shift().trim(); if (av.length === 0) { // happens if ";;" appears continue; } var av_sep = av.indexOf('='); var av_key, av_value; if (av_sep === -1) { av_key = av; av_value = null; } else { av_key = av.substr(0,av_sep); av_value = av.substr(av_sep+1); } av_key = av_key.trim().toLowerCase(); if (av_value) { av_value = av_value.trim(); } switch(av_key) { case 'expires': // S5.2.1 if (av_value) { var exp = parseDate(av_value); // "If the attribute-value failed to parse as a cookie date, ignore the // cookie-av." if (exp) { // over and underflow not realistically a concern: V8's getTime() seems to // store something larger than a 32-bit time_t (even with 32-bit node) c.expires = exp; } } break; case 'max-age': // S5.2.2 if (av_value) { // "If the first character of the attribute-value is not a DIGIT or a "-" // character ...[or]... If the remainder of attribute-value contains a // non-DIGIT character, ignore the cookie-av." if (/^-?[0-9]+$/.test(av_value)) { var delta = parseInt(av_value, 10); // "If delta-seconds is less than or equal to zero (0), let expiry-time // be the earliest representable date and time." c.setMaxAge(delta); } } break; case 'domain': // S5.2.3 // "If the attribute-value is empty, the behavior is undefined. However, // the user agent SHOULD ignore the cookie-av entirely." if (av_value) { // S5.2.3 "Let cookie-domain be the attribute-value without the leading %x2E // (".") character." var domain = av_value.trim().replace(/^\./, ''); if (domain) { // "Convert the cookie-domain to lower case." c.domain = domain.toLowerCase(); } } break; case 'path': // S5.2.4 /* * "If the attribute-value is empty or if the first character of the * attribute-value is not %x2F ("/"): * Let cookie-path be the default-path. * Otherwise: * Let cookie-path be the attribute-value." * * We'll represent the default-path as null since it depends on the * context of the parsing. */ c.path = av_value && av_value[0] === "/" ? av_value : null; break; case 'secure': // S5.2.5 /* * "If the attribute-name case-insensitively matches the string "Secure", * the user agent MUST append an attribute to the cookie-attribute-list * with an attribute-name of Secure and an empty attribute-value." */ c.secure = true; break; case 'httponly': // S5.2.6 -- effectively the same as 'secure' c.httpOnly = true; break; default: c.extensions = c.extensions || []; c.extensions.push(av); break; } } return c; } // avoid the V8 deoptimization monster! function jsonParse(str) { var obj; try { obj = JSON.parse(str); } catch (e) { return e; } return obj; } function fromJSON(str) { if (!str) { return null; } var obj; if (typeof str === 'string') { obj = jsonParse(str); if (obj instanceof Error) { return null; } } else { // assume it's an Object obj = str; } var c = new Cookie(); for (var i=0; i<Cookie.serializableProperties.length; i++) { var prop = Cookie.serializableProperties[i]; if (obj[prop] === undefined || obj[prop] === Cookie.prototype[prop]) { continue; // leave as prototype default } if (prop === 'expires' || prop === 'creation' || prop === 'lastAccessed') { if (obj[prop] === null) { c[prop] = null; } else { c[prop] = obj[prop] == "Infinity" ? "Infinity" : new Date(obj[prop]); } } else { c[prop] = obj[prop]; } } return c; } /* Section 5.4 part 2: * "* Cookies with longer paths are listed before cookies with * shorter paths. * * * Among cookies that have equal-length path fields, cookies with * earlier creation-times are listed before cookies with later * creation-times." */ function cookieCompare(a,b) { var cmp = 0; // descending for length: b CMP a var aPathLen = a.path ? a.path.length : 0; var bPathLen = b.path ? b.path.length : 0; cmp = bPathLen - aPathLen; if (cmp !== 0) { return cmp; } // ascending for time: a CMP b var aTime = a.creation ? a.creation.getTime() : MAX_TIME; var bTime = b.creation ? b.creation.getTime() : MAX_TIME; cmp = aTime - bTime; if (cmp !== 0) { return cmp; } // break ties for the same millisecond (precision of JavaScript's clock) cmp = a.creationIndex - b.creationIndex; return cmp; } // Gives the permutation of all possible pathMatch()es of a given path. The // array is in longest-to-shortest order. Handy for indexing. function permutePath(path) { if (path === '/') { return ['/']; } if (path.lastIndexOf('/') === path.length-1) { path = path.substr(0,path.length-1); } var permutations = [path]; while (path.length > 1) { var lindex = path.lastIndexOf('/'); if (lindex === 0) { break; } path = path.substr(0,lindex); permutations.push(path); } permutations.push('/'); return permutations; } function getCookieContext(url) { if (url instanceof Object) { return url; } // NOTE: decodeURI will throw on malformed URIs (see GH-32). // Therefore, we will just skip decoding for such URIs. try { url = decodeURI(url); } catch(err) { // Silently swallow error } return urlParse(url); } function Cookie(options) { options = options || {}; Object.keys(options).forEach(function(prop) { if (Cookie.prototype.hasOwnProperty(prop) && Cookie.prototype[prop] !== options[prop] && prop.substr(0,1) !== '_') { this[prop] = options[prop]; } }, this); this.creation = this.creation || new Date(); // used to break creation ties in cookieCompare(): Object.defineProperty(this, 'creationIndex', { configurable: false, enumerable: false, // important for assert.deepEqual checks writable: true, value: ++Cookie.cookiesCreated }); } Cookie.cookiesCreated = 0; // incremented each time a cookie is created Cookie.parse = parse; Cookie.fromJSON = fromJSON; Cookie.prototype.key = ""; Cookie.prototype.value = ""; // the order in which the RFC has them: Cookie.prototype.expires = "Infinity"; // coerces to literal Infinity Cookie.prototype.maxAge = null; // takes precedence over expires for TTL Cookie.prototype.domain = null; Cookie.prototype.path = null; Cookie.prototype.secure = false; Cookie.prototype.httpOnly = false; Cookie.prototype.extensions = null; // set by the CookieJar: Cookie.prototype.hostOnly = null; // boolean when set Cookie.prototype.pathIsDefault = null; // boolean when set Cookie.prototype.creation = null; // Date when set; defaulted by Cookie.parse Cookie.prototype.lastAccessed = null; // Date when set Object.defineProperty(Cookie.prototype, 'creationIndex', { configurable: true, enumerable: false, writable: true, value: 0 }); Cookie.serializableProperties = Object.keys(Cookie.prototype) .filter(function(prop) { return !( Cookie.prototype[prop] instanceof Function || prop === 'creationIndex' || prop.substr(0,1) === '_' ); }); Cookie.prototype.inspect = function inspect() { var now = Date.now(); return 'Cookie="'+this.toString() + '; hostOnly='+(this.hostOnly != null ? this.hostOnly : '?') + '; aAge='+(this.lastAccessed ? (now-this.lastAccessed.getTime())+'ms' : '?') + '; cAge='+(this.creation ? (now-this.creation.getTime())+'ms' : '?') + '"'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { Cookie.prototype[util.inspect.custom] = Cookie.prototype.inspect; } Cookie.prototype.toJSON = function() { var obj = {}; var props = Cookie.serializableProperties; for (var i=0; i<props.length; i++) { var prop = props[i]; if (this[prop] === Cookie.prototype[prop]) { continue; // leave as prototype default } if (prop === 'expires' || prop === 'creation' || prop === 'lastAccessed') { if (this[prop] === null) { obj[prop] = null; } else { obj[prop] = this[prop] == "Infinity" ? // intentionally not === "Infinity" : this[prop].toISOString(); } } else if (prop === 'maxAge') { if (this[prop] !== null) { // again, intentionally not === obj[prop] = (this[prop] == Infinity || this[prop] == -Infinity) ? this[prop].toString() : this[prop]; } } else { if (this[prop] !== Cookie.prototype[prop]) { obj[prop] = this[prop]; } } } return obj; }; Cookie.prototype.clone = function() { return fromJSON(this.toJSON()); }; Cookie.prototype.validate = function validate() { if (!COOKIE_OCTETS.test(this.value)) { return false; } if (this.expires != Infinity && !(this.expires instanceof Date) && !parseDate(this.expires)) { return false; } if (this.maxAge != null && this.maxAge <= 0) { return false; // "Max-Age=" non-zero-digit *DIGIT } if (this.path != null && !PATH_VALUE.test(this.path)) { return false; } var cdomain = this.cdomain(); if (cdomain) { if (cdomain.match(/\.$/)) { return false; // S4.1.2.3 suggests that this is bad. domainMatch() tests confirm this } var suffix = pubsuffix.getPublicSuffix(cdomain); if (suffix == null) { // it's a public suffix return false; } } return true; }; Cookie.prototype.setExpires = function setExpires(exp) { if (exp instanceof Date) { this.expires = exp; } else { this.expires = parseDate(exp) || "Infinity"; } }; Cookie.prototype.setMaxAge = function setMaxAge(age) { if (age === Infinity || age === -Infinity) { this.maxAge = age.toString(); // so JSON.stringify() works } else { this.maxAge = age; } }; // gives Cookie header format Cookie.prototype.cookieString = function cookieString() { var val = this.value; if (val == null) { val = ''; } if (this.key === '') { return val; } return this.key+'='+val; }; // gives Set-Cookie header format Cookie.prototype.toString = function toString() { var str = this.cookieString(); if (this.expires != Infinity) { if (this.expires instanceof Date) { str += '; Expires='+formatDate(this.expires); } else { str += '; Expires='+this.expires; } } if (this.maxAge != null && this.maxAge != Infinity) { str += '; Max-Age='+this.maxAge; } if (this.domain && !this.hostOnly) { str += '; Domain='+this.domain; } if (this.path) { str += '; Path='+this.path; } if (this.secure) { str += '; Secure'; } if (this.httpOnly) { str += '; HttpOnly'; } if (this.extensions) { this.extensions.forEach(function(ext) { str += '; '+ext; }); } return str; }; // TTL() partially replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere) // S5.3 says to give the "latest representable date" for which we use Infinity // For "expired" we use 0 Cookie.prototype.TTL = function TTL(now) { /* RFC6265 S4.1.2.2 If a cookie has both the Max-Age and the Expires * attribute, the Max-Age attribute has precedence and controls the * expiration date of the cookie. * (Concurs with S5.3 step 3) */ if (this.maxAge != null) { return this.maxAge<=0 ? 0 : this.maxAge*1000; } var expires = this.expires; if (expires != Infinity) { if (!(expires instanceof Date)) { expires = parseDate(expires) || Infinity; } if (expires == Infinity) { return Infinity; } return expires.getTime() - (now || Date.now()); } return Infinity; }; // expiryTime() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere) Cookie.prototype.expiryTime = function expiryTime(now) { if (this.maxAge != null) { var relativeTo = now || this.creation || new Date(); var age = (this.maxAge <= 0) ? -Infinity : this.maxAge*1000; return relativeTo.getTime() + age; } if (this.expires == Infinity) { return Infinity; } return this.expires.getTime(); }; // expiryDate() replaces the "expiry-time" parts of S5.3 step 3 (setCookie() // elsewhere), except it returns a Date Cookie.prototype.expiryDate = function expiryDate(now) { var millisec = this.expiryTime(now); if (millisec == Infinity) { return new Date(MAX_TIME); } else if (millisec == -Infinity) { return new Date(MIN_TIME); } else { return new Date(millisec); } }; // This replaces the "persistent-flag" parts of S5.3 step 3 Cookie.prototype.isPersistent = function isPersistent() { return (this.maxAge != null || this.expires != Infinity); }; // Mostly S5.1.2 and S5.2.3: Cookie.prototype.cdomain = Cookie.prototype.canonicalizedDomain = function canonicalizedDomain() { if (this.domain == null) { return null; } return canonicalDomain(this.domain); }; function CookieJar(store, options) { if (typeof options === "boolean") { options = {rejectPublicSuffixes: options}; } else if (options == null) { options = {}; } if (options.rejectPublicSuffixes != null) { this.rejectPublicSuffixes = options.rejectPublicSuffixes; } if (options.looseMode != null) { this.enableLooseMode = options.looseMode; } if (!store) { store = new MemoryCookieStore(); } this.store = store; } CookieJar.prototype.store = null; CookieJar.prototype.rejectPublicSuffixes = true; CookieJar.prototype.enableLooseMode = false; var CAN_BE_SYNC = []; CAN_BE_SYNC.push('setCookie'); CookieJar.prototype.setCookie = function(cookie, url, options, cb) { var err; var context = getCookieContext(url); if (options instanceof Function) { cb = options; options = {}; } var host = canonicalDomain(context.hostname); var loose = this.enableLooseMode; if (options.loose != null) { loose = options.loose; } // S5.3 step 1 if (!(cookie instanceof Cookie)) { cookie = Cookie.parse(cookie, { loose: loose }); } if (!cookie) { err = new Error("Cookie failed to parse"); return cb(options.ignoreError ? null : err); } // S5.3 step 2 var now = options.now || new Date(); // will assign later to save effort in the face of errors // S5.3 step 3: NOOP; persistent-flag and expiry-time is handled by getCookie() // S5.3 step 4: NOOP; domain is null by default // S5.3 step 5: public suffixes if (this.rejectPublicSuffixes && cookie.domain) { var suffix = pubsuffix.getPublicSuffix(cookie.cdomain()); if (suffix == null) { // e.g. "com" err = new Error("Cookie has domain set to a public suffix"); return cb(options.ignoreError ? null : err); } } // S5.3 step 6: if (cookie.domain) { if (!domainMatch(host, cookie.cdomain(), false)) { err = new Error("Cookie not in this host's domain. Cookie:"+cookie.cdomain()+" Request:"+host); return cb(options.ignoreError ? null : err); } if (cookie.hostOnly == null) { // don't reset if already set cookie.hostOnly = false; } } else { cookie.hostOnly = true; cookie.domain = host; } //S5.2.4 If the attribute-value is empty or if the first character of the //attribute-value is not %x2F ("/"): //Let cookie-path be the default-path. if (!cookie.path || cookie.path[0] !== '/') { cookie.path = defaultPath(context.pathname); cookie.pathIsDefault = true; } // S5.3 step 8: NOOP; secure attribute // S5.3 step 9: NOOP; httpOnly attribute // S5.3 step 10 if (options.http === false && cookie.httpOnly) { err = new Error("Cookie is HttpOnly and this isn't an HTTP API"); return cb(options.ignoreError ? null : err); } var store = this.store; if (!store.updateCookie) { store.updateCookie = function(oldCookie, newCookie, cb) { this.putCookie(newCookie, cb); }; } function withCookie(err, oldCookie) { if (err) { return cb(err); } var next = function(err) { if (err) { return cb(err); } else { cb(null, cookie); } }; if (oldCookie) { // S5.3 step 11 - "If the cookie store contains a cookie with the same name, // domain, and path as the newly created cookie:" if (options.http === false && oldCookie.httpOnly) { // step 11.2 err = new Error("old Cookie is HttpOnly and this isn't an HTTP API"); return cb(options.ignoreError ? null : err); } cookie.creation = oldCookie.creation; // step 11.3 cookie.creationIndex = oldCookie.creationIndex; // preserve tie-breaker cookie.lastAccessed = now; // Step 11.4 (delete cookie) is implied by just setting the new one: store.updateCookie(oldCookie, cookie, next); // step 12 } else { cookie.creation = cookie.lastAccessed = now; store.putCookie(cookie, next); // step 12 } } store.findCookie(cookie.domain, cookie.path, cookie.key, withCookie); }; // RFC6365 S5.4 CAN_BE_SYNC.push('getCookies'); CookieJar.prototype.getCookies = function(url, options, cb) { var context = getCookieContext(url); if (options instanceof Function) { cb = options; options = {}; } var host = canonicalDomain(context.hostname); var path = context.pathname || '/'; var secure = options.secure; if (secure == null && context.protocol && (context.protocol == 'https:' || context.protocol == 'wss:')) { secure = true; } var http = options.http; if (http == null) { http = true; } var now = options.now || Date.now(); var expireCheck = options.expire !== false; var allPaths = !!options.allPaths; var store = this.store; function matchingCookie(c) { // "Either: // The cookie's host-only-flag is true and the canonicalized // request-host is identical to the cookie's domain. // Or: // The cookie's host-only-flag is false and the canonicalized // request-host domain-matches the cookie's domain." if (c.hostOnly) { if (c.domain != host) { return false; } } else { if (!domainMatch(host, c.domain, false)) { return false; } } // "The request-uri's path path-matches the cookie's path." if (!allPaths && !pathMatch(path, c.path)) { return false; } // "If the cookie's secure-only-flag is true, then the request-uri's // scheme must denote a "secure" protocol" if (c.secure && !secure) { return false; } // "If the cookie's http-only-flag is true, then exclude the cookie if the // cookie-string is being generated for a "non-HTTP" API" if (c.httpOnly && !http) { return false; } // deferred from S5.3 // non-RFC: allow retention of expired cookies by choice if (expireCheck && c.expiryTime() <= now) { store.removeCookie(c.domain, c.path, c.key, function(){}); // result ignored return false; } return true; } store.findCookies(host, allPaths ? null : path, function(err,cookies) { if (err) { return cb(err); } cookies = cookies.filter(matchingCookie); // sorting of S5.4 part 2 if (options.sort !== false) { cookies = cookies.sort(cookieCompare); } // S5.4 part 3 var now = new Date(); cookies.forEach(function(c) { c.lastAccessed = now; }); // TODO persist lastAccessed cb(null,cookies); }); }; CAN_BE_SYNC.push('getCookieString'); CookieJar.prototype.getCookieString = function(/*..., cb*/) { var args = Array.prototype.slice.call(arguments,0); var cb = args.pop(); var next = function(err,cookies) { if (err) { cb(err); } else { cb(null, cookies .sort(cookieCompare) .map(function(c){ return c.cookieString(); }) .join('; ')); } }; args.push(next); this.getCookies.apply(this,args); }; CAN_BE_SYNC.push('getSetCookieStrings'); CookieJar.prototype.getSetCookieStrings = function(/*..., cb*/) { var args = Array.prototype.slice.call(arguments,0); var cb = args.pop(); var next = function(err,cookies) { if (err) { cb(err); } else { cb(null, cookies.map(function(c){ return c.toString(); })); } }; args.push(next); this.getCookies.apply(this,args); }; CAN_BE_SYNC.push('serialize'); CookieJar.prototype.serialize = function(cb) { var type = this.store.constructor.name; if (type === 'Object') { type = null; } // update README.md "Serialization Format" if you change this, please! var serialized = { // The version of tough-cookie that serialized this jar. Generally a good // practice since future versions can make data import decisions based on // known past behavior. When/if this matters, use `semver`. version: 'tough-cookie@'+VERSION, // add the store type, to make humans happy: storeType: type, // CookieJar configuration: rejectPublicSuffixes: !!this.rejectPublicSuffixes, // this gets filled from getAllCookies: cookies: [] }; if (!(this.store.getAllCookies && typeof this.store.getAllCookies === 'function')) { return cb(new Error('store does not support getAllCookies and cannot be serialized')); } this.store.getAllCookies(function(err,cookies) { if (err) { return cb(err); } serialized.cookies = cookies.map(function(cookie) { // convert to serialized 'raw' cookies cookie = (cookie instanceof Cookie) ? cookie.toJSON() : cookie; // Remove the index so new ones get assigned during deserialization delete cookie.creationIndex; return cookie; }); return cb(null, serialized); }); }; // well-known name that JSON.stringify calls CookieJar.prototype.toJSON = function() { return this.serializeSync(); }; // use the class method CookieJar.deserialize instead of calling this directly CAN_BE_SYNC.push('_importCookies'); CookieJar.prototype._importCookies = function(serialized, cb) { var jar = this; var cookies = serialized.cookies; if (!cookies || !Array.isArray(cookies)) { return cb(new Error('serialized jar has no cookies array')); } cookies = cookies.slice(); // do not modify the original function putNext(err) { if (err) { return cb(err); } if (!cookies.length) { return cb(err, jar); } var cookie; try { cookie = fromJSON(cookies.shift()); } catch (e) { return cb(e); } if (cookie === null) { return putNext(null); // skip this cookie } jar.store.putCookie(cookie, putNext); } putNext(); }; CookieJar.deserialize = function(strOrObj, store, cb) { if (arguments.length !== 3) { // store is optional cb = store; store = null; } var serialized; if (typeof strOrObj === 'string') { serialized = jsonParse(strOrObj); if (serialized instanceof Error) { return cb(serialized); } } else { serialized = strOrObj; } var jar = new CookieJar(store, serialized.rejectPublicSuffixes); jar._importCookies(serialized, function(err) { if (err) { return cb(err); } cb(null, jar); }); }; CookieJar.deserializeSync = function(strOrObj, store) { var serialized = typeof strOrObj === 'string' ? JSON.parse(strOrObj) : strOrObj; var jar = new CookieJar(store, serialized.rejectPublicSuffixes); // catch this mistake early: if (!jar.store.synchronous) { throw new Error('CookieJar store is not synchronous; use async API instead.'); } jar._importCookiesSync(serialized); return jar; }; CookieJar.fromJSON = CookieJar.deserializeSync; CookieJar.prototype.clone = function(newStore, cb) { if (arguments.length === 1) { cb = newStore; newStore = null; } this.serialize(function(err,serialized) { if (err) { return cb(err); } CookieJar.deserialize(serialized, newStore, cb); }); }; CAN_BE_SYNC.push('removeAllCookies'); CookieJar.prototype.removeAllCookies = function(cb) { var store = this.store; // Check that the store implements its own removeAllCookies(). The default // implementation in Store will immediately call the callback with a "not // implemented" Error. if (store.removeAllCookies instanceof Function && store.removeAllCookies !== Store.prototype.removeAllCookies) { return store.removeAllCookies(cb); } store.getAllCookies(function(err, cookies) { if (err) { return cb(err); } if (cookies.length === 0) { return cb(null); } var completedCount = 0; var removeErrors = []; function removeCookieCb(removeErr) { if (removeErr) { removeErrors.push(removeErr); } completedCount++; if (completedCount === cookies.length) { return cb(removeErrors.length ? removeErrors[0] : null); } } cookies.forEach(function(cookie) { store.removeCookie(cookie.domain, cookie.path, cookie.key, removeCookieCb); }); }); }; CookieJar.prototype._cloneSync = syncWrap('clone'); CookieJar.prototype.cloneSync = function(newStore) { if (!newStore.synchronous) { throw new Error('CookieJar clone destination store is not synchronous; use async API instead.'); } return this._cloneSync(newStore); }; // Use a closure to provide a true imperative API for synchronous stores. function syncWrap(method) { return function() { if (!this.store.synchronous) { throw new Error('CookieJar store is not synchronous; use async API instead.'); } var args = Array.prototype.slice.call(arguments); var syncErr, syncResult; args.push(function syncCb(err, result) { syncErr = err; syncResult = result; }); this[method].apply(this, args); if (syncErr) { throw syncErr; } return syncResult; }; } // wrap all declared CAN_BE_SYNC methods in the sync wrapper CAN_BE_SYNC.forEach(function(method) { CookieJar.prototype[method+'Sync'] = syncWrap(method); }); exports.version = VERSION; exports.CookieJar = CookieJar; exports.Cookie = Cookie; exports.Store = Store; exports.MemoryCookieStore = MemoryCookieStore; exports.parseDate = parseDate; exports.formatDate = formatDate; exports.parse = parse; exports.fromJSON = fromJSON; exports.domainMatch = domainMatch; exports.defaultPath = defaultPath; exports.pathMatch = pathMatch; exports.getPublicSuffix = pubsuffix.getPublicSuffix; exports.cookieCompare = cookieCompare; exports.permuteDomain = require('./permuteDomain').permuteDomain; exports.permutePath = permutePath; exports.canonicalDomain = canonicalDomain; ```
/content/code_sandbox/node_modules/tough-cookie/lib/cookie.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,753
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/types.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
16
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.visit = exports.use = exports.Type = exports.someField = exports.PathVisitor = exports.Path = exports.NodePath = exports.namedTypes = exports.getSupertypeNames = exports.getFieldValue = exports.getFieldNames = exports.getBuilderName = exports.finalize = exports.eachField = exports.defineMethod = exports.builtInTypes = exports.builders = exports.astNodesAreEquivalent = void 0; var tslib_1 = require("tslib"); var fork_1 = tslib_1.__importDefault(require("./fork")); var core_1 = tslib_1.__importDefault(require("./def/core")); var es6_1 = tslib_1.__importDefault(require("./def/es6")); var es7_1 = tslib_1.__importDefault(require("./def/es7")); var es2020_1 = tslib_1.__importDefault(require("./def/es2020")); var jsx_1 = tslib_1.__importDefault(require("./def/jsx")); var flow_1 = tslib_1.__importDefault(require("./def/flow")); var esprima_1 = tslib_1.__importDefault(require("./def/esprima")); var babel_1 = tslib_1.__importDefault(require("./def/babel")); var typescript_1 = tslib_1.__importDefault(require("./def/typescript")); var es_proposals_1 = tslib_1.__importDefault(require("./def/es-proposals")); var namedTypes_1 = require("./gen/namedTypes"); Object.defineProperty(exports, "namedTypes", { enumerable: true, get: function () { return namedTypes_1.namedTypes; } }); var _a = fork_1.default([ // This core module of AST types captures ES5 as it is parsed today by // git://github.com/ariya/esprima.git#master. core_1.default, // Feel free to add to or remove from this list of extension modules to // configure the precise type hierarchy that you need. es6_1.default, es7_1.default, es2020_1.default, jsx_1.default, flow_1.default, esprima_1.default, babel_1.default, typescript_1.default, es_proposals_1.default, ]), astNodesAreEquivalent = _a.astNodesAreEquivalent, builders = _a.builders, builtInTypes = _a.builtInTypes, defineMethod = _a.defineMethod, eachField = _a.eachField, finalize = _a.finalize, getBuilderName = _a.getBuilderName, getFieldNames = _a.getFieldNames, getFieldValue = _a.getFieldValue, getSupertypeNames = _a.getSupertypeNames, n = _a.namedTypes, NodePath = _a.NodePath, Path = _a.Path, PathVisitor = _a.PathVisitor, someField = _a.someField, Type = _a.Type, use = _a.use, visit = _a.visit; exports.astNodesAreEquivalent = astNodesAreEquivalent; exports.builders = builders; exports.builtInTypes = builtInTypes; exports.defineMethod = defineMethod; exports.eachField = eachField; exports.finalize = finalize; exports.getBuilderName = getBuilderName; exports.getFieldNames = getFieldNames; exports.getFieldValue = getFieldValue; exports.getSupertypeNames = getSupertypeNames; exports.NodePath = NodePath; exports.Path = Path; exports.PathVisitor = PathVisitor; exports.someField = someField; exports.Type = Type; exports.use = use; exports.visit = visit; // Populate the exported fields of the namedTypes namespace, while still // retaining its member types. Object.assign(namedTypes_1.namedTypes, n); ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/main.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
769
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./lib/types")); var path_visitor_1 = tslib_1.__importDefault(require("./lib/path-visitor")); var equiv_1 = tslib_1.__importDefault(require("./lib/equiv")); var path_1 = tslib_1.__importDefault(require("./lib/path")); var node_path_1 = tslib_1.__importDefault(require("./lib/node-path")); function default_1(defs) { var fork = createFork(); var types = fork.use(types_1.default); defs.forEach(fork.use); types.finalize(); var PathVisitor = fork.use(path_visitor_1.default); return { Type: types.Type, builtInTypes: types.builtInTypes, namedTypes: types.namedTypes, builders: types.builders, defineMethod: types.defineMethod, getFieldNames: types.getFieldNames, getFieldValue: types.getFieldValue, eachField: types.eachField, someField: types.someField, getSupertypeNames: types.getSupertypeNames, getBuilderName: types.getBuilderName, astNodesAreEquivalent: fork.use(equiv_1.default), finalize: types.finalize, Path: fork.use(path_1.default), NodePath: fork.use(node_path_1.default), PathVisitor: PathVisitor, use: fork.use, visit: PathVisitor.visit, }; } exports.default = default_1; function createFork() { var used = []; var usedResult = []; function use(plugin) { var idx = used.indexOf(plugin); if (idx === -1) { idx = used.length; used.push(plugin); usedResult[idx] = plugin(fork); } return usedResult[idx]; } var fork = { use: use }; return fork; } module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/fork.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
421
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.namedTypes = void 0; var namedTypes; (function (namedTypes) { })(namedTypes = exports.namedTypes || (exports.namedTypes = {})); ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/gen/namedTypes.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
48
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Def = void 0; var tslib_1 = require("tslib"); var Op = Object.prototype; var objToStr = Op.toString; var hasOwn = Op.hasOwnProperty; var BaseType = /** @class */ (function () { function BaseType() { } BaseType.prototype.assert = function (value, deep) { if (!this.check(value, deep)) { var str = shallowStringify(value); throw new Error(str + " does not match type " + this); } return true; }; BaseType.prototype.arrayOf = function () { var elemType = this; return new ArrayType(elemType); }; return BaseType; }()); var ArrayType = /** @class */ (function (_super) { tslib_1.__extends(ArrayType, _super); function ArrayType(elemType) { var _this = _super.call(this) || this; _this.elemType = elemType; _this.kind = "ArrayType"; return _this; } ArrayType.prototype.toString = function () { return "[" + this.elemType + "]"; }; ArrayType.prototype.check = function (value, deep) { var _this = this; return Array.isArray(value) && value.every(function (elem) { return _this.elemType.check(elem, deep); }); }; return ArrayType; }(BaseType)); var IdentityType = /** @class */ (function (_super) { tslib_1.__extends(IdentityType, _super); function IdentityType(value) { var _this = _super.call(this) || this; _this.value = value; _this.kind = "IdentityType"; return _this; } IdentityType.prototype.toString = function () { return String(this.value); }; IdentityType.prototype.check = function (value, deep) { var result = value === this.value; if (!result && typeof deep === "function") { deep(this, value); } return result; }; return IdentityType; }(BaseType)); var ObjectType = /** @class */ (function (_super) { tslib_1.__extends(ObjectType, _super); function ObjectType(fields) { var _this = _super.call(this) || this; _this.fields = fields; _this.kind = "ObjectType"; return _this; } ObjectType.prototype.toString = function () { return "{ " + this.fields.join(", ") + " }"; }; ObjectType.prototype.check = function (value, deep) { return (objToStr.call(value) === objToStr.call({}) && this.fields.every(function (field) { return field.type.check(value[field.name], deep); })); }; return ObjectType; }(BaseType)); var OrType = /** @class */ (function (_super) { tslib_1.__extends(OrType, _super); function OrType(types) { var _this = _super.call(this) || this; _this.types = types; _this.kind = "OrType"; return _this; } OrType.prototype.toString = function () { return this.types.join(" | "); }; OrType.prototype.check = function (value, deep) { return this.types.some(function (type) { return type.check(value, deep); }); }; return OrType; }(BaseType)); var PredicateType = /** @class */ (function (_super) { tslib_1.__extends(PredicateType, _super); function PredicateType(name, predicate) { var _this = _super.call(this) || this; _this.name = name; _this.predicate = predicate; _this.kind = "PredicateType"; return _this; } PredicateType.prototype.toString = function () { return this.name; }; PredicateType.prototype.check = function (value, deep) { var result = this.predicate(value, deep); if (!result && typeof deep === "function") { deep(this, value); } return result; }; return PredicateType; }(BaseType)); var Def = /** @class */ (function () { function Def(type, typeName) { this.type = type; this.typeName = typeName; this.baseNames = []; this.ownFields = Object.create(null); // Includes own typeName. Populated during finalization. this.allSupertypes = Object.create(null); // Linear inheritance hierarchy. Populated during finalization. this.supertypeList = []; // Includes inherited fields. this.allFields = Object.create(null); // Non-hidden keys of allFields. this.fieldNames = []; // This property will be overridden as true by individual Def instances // when they are finalized. this.finalized = false; // False by default until .build(...) is called on an instance. this.buildable = false; this.buildParams = []; } Def.prototype.isSupertypeOf = function (that) { if (that instanceof Def) { if (this.finalized !== true || that.finalized !== true) { throw new Error(""); } return hasOwn.call(that.allSupertypes, this.typeName); } else { throw new Error(that + " is not a Def"); } }; Def.prototype.checkAllFields = function (value, deep) { var allFields = this.allFields; if (this.finalized !== true) { throw new Error("" + this.typeName); } function checkFieldByName(name) { var field = allFields[name]; var type = field.type; var child = field.getValue(value); return type.check(child, deep); } return value !== null && typeof value === "object" && Object.keys(allFields).every(checkFieldByName); }; Def.prototype.bases = function () { var supertypeNames = []; for (var _i = 0; _i < arguments.length; _i++) { supertypeNames[_i] = arguments[_i]; } var bases = this.baseNames; if (this.finalized) { if (supertypeNames.length !== bases.length) { throw new Error(""); } for (var i = 0; i < supertypeNames.length; i++) { if (supertypeNames[i] !== bases[i]) { throw new Error(""); } } return this; } supertypeNames.forEach(function (baseName) { // This indexOf lookup may be O(n), but the typical number of base // names is very small, and indexOf is a native Array method. if (bases.indexOf(baseName) < 0) { bases.push(baseName); } }); return this; // For chaining. }; return Def; }()); exports.Def = Def; var Field = /** @class */ (function () { function Field(name, type, defaultFn, hidden) { this.name = name; this.type = type; this.defaultFn = defaultFn; this.hidden = !!hidden; } Field.prototype.toString = function () { return JSON.stringify(this.name) + ": " + this.type; }; Field.prototype.getValue = function (obj) { var value = obj[this.name]; if (typeof value !== "undefined") { return value; } if (typeof this.defaultFn === "function") { value = this.defaultFn.call(obj); } return value; }; return Field; }()); function shallowStringify(value) { if (Array.isArray(value)) { return "[" + value.map(shallowStringify).join(", ") + "]"; } if (value && typeof value === "object") { return "{ " + Object.keys(value).map(function (key) { return key + ": " + value[key]; }).join(", ") + " }"; } return JSON.stringify(value); } function typesPlugin(_fork) { var Type = { or: function () { var types = []; for (var _i = 0; _i < arguments.length; _i++) { types[_i] = arguments[_i]; } return new OrType(types.map(function (type) { return Type.from(type); })); }, from: function (value, name) { if (value instanceof ArrayType || value instanceof IdentityType || value instanceof ObjectType || value instanceof OrType || value instanceof PredicateType) { return value; } // The Def type is used as a helper for constructing compound // interface types for AST nodes. if (value instanceof Def) { return value.type; } // Support [ElemType] syntax. if (isArray.check(value)) { if (value.length !== 1) { throw new Error("only one element type is permitted for typed arrays"); } return new ArrayType(Type.from(value[0])); } // Support { someField: FieldType, ... } syntax. if (isObject.check(value)) { return new ObjectType(Object.keys(value).map(function (name) { return new Field(name, Type.from(value[name], name)); })); } if (typeof value === "function") { var bicfIndex = builtInCtorFns.indexOf(value); if (bicfIndex >= 0) { return builtInCtorTypes[bicfIndex]; } if (typeof name !== "string") { throw new Error("missing name"); } return new PredicateType(name, value); } // As a last resort, toType returns a type that matches any value that // is === from. This is primarily useful for literal values like // toType(null), but it has the additional advantage of allowing // toType to be a total function. return new IdentityType(value); }, // Define a type whose name is registered in a namespace (the defCache) so // that future definitions will return the same type given the same name. // In particular, this system allows for circular and forward definitions. // The Def object d returned from Type.def may be used to configure the // type d.type by calling methods such as d.bases, d.build, and d.field. def: function (typeName) { return hasOwn.call(defCache, typeName) ? defCache[typeName] : defCache[typeName] = new DefImpl(typeName); }, hasDef: function (typeName) { return hasOwn.call(defCache, typeName); } }; var builtInCtorFns = []; var builtInCtorTypes = []; function defBuiltInType(name, example) { var objStr = objToStr.call(example); var type = new PredicateType(name, function (value) { return objToStr.call(value) === objStr; }); if (example && typeof example.constructor === "function") { builtInCtorFns.push(example.constructor); builtInCtorTypes.push(type); } return type; } // These types check the underlying [[Class]] attribute of the given // value, rather than using the problematic typeof operator. Note however // that no subtyping is considered; so, for instance, isObject.check // returns false for [], /./, new Date, and null. var isString = defBuiltInType("string", "truthy"); var isFunction = defBuiltInType("function", function () { }); var isArray = defBuiltInType("array", []); var isObject = defBuiltInType("object", {}); var isRegExp = defBuiltInType("RegExp", /./); var isDate = defBuiltInType("Date", new Date()); var isNumber = defBuiltInType("number", 3); var isBoolean = defBuiltInType("boolean", true); var isNull = defBuiltInType("null", null); var isUndefined = defBuiltInType("undefined", undefined); var builtInTypes = { string: isString, function: isFunction, array: isArray, object: isObject, RegExp: isRegExp, Date: isDate, number: isNumber, boolean: isBoolean, null: isNull, undefined: isUndefined, }; // In order to return the same Def instance every time Type.def is called // with a particular name, those instances need to be stored in a cache. var defCache = Object.create(null); function defFromValue(value) { if (value && typeof value === "object") { var type = value.type; if (typeof type === "string" && hasOwn.call(defCache, type)) { var d = defCache[type]; if (d.finalized) { return d; } } } return null; } var DefImpl = /** @class */ (function (_super) { tslib_1.__extends(DefImpl, _super); function DefImpl(typeName) { var _this = _super.call(this, new PredicateType(typeName, function (value, deep) { return _this.check(value, deep); }), typeName) || this; return _this; } DefImpl.prototype.check = function (value, deep) { if (this.finalized !== true) { throw new Error("prematurely checking unfinalized type " + this.typeName); } // A Def type can only match an object value. if (value === null || typeof value !== "object") { return false; } var vDef = defFromValue(value); if (!vDef) { // If we couldn't infer the Def associated with the given value, // and we expected it to be a SourceLocation or a Position, it was // probably just missing a "type" field (because Esprima does not // assign a type property to such nodes). Be optimistic and let // this.checkAllFields make the final decision. if (this.typeName === "SourceLocation" || this.typeName === "Position") { return this.checkAllFields(value, deep); } // Calling this.checkAllFields for any other type of node is both // bad for performance and way too forgiving. return false; } // If checking deeply and vDef === this, then we only need to call // checkAllFields once. Calling checkAllFields is too strict when deep // is false, because then we only care about this.isSupertypeOf(vDef). if (deep && vDef === this) { return this.checkAllFields(value, deep); } // In most cases we rely exclusively on isSupertypeOf to make O(1) // subtyping determinations. This suffices in most situations outside // of unit tests, since interface conformance is checked whenever new // instances are created using builder functions. if (!this.isSupertypeOf(vDef)) { return false; } // The exception is when deep is true; then, we recursively check all // fields. if (!deep) { return true; } // Use the more specific Def (vDef) to perform the deep check, but // shallow-check fields defined by the less specific Def (this). return vDef.checkAllFields(value, deep) && this.checkAllFields(value, false); }; DefImpl.prototype.build = function () { var _this = this; var buildParams = []; for (var _i = 0; _i < arguments.length; _i++) { buildParams[_i] = arguments[_i]; } // Calling Def.prototype.build multiple times has the effect of merely // redefining this property. this.buildParams = buildParams; if (this.buildable) { // If this Def is already buildable, update self.buildParams and // continue using the old builder function. return this; } // Every buildable type will have its "type" field filled in // automatically. This includes types that are not subtypes of Node, // like SourceLocation, but that seems harmless (TODO?). this.field("type", String, function () { return _this.typeName; }); // Override Dp.buildable for this Def instance. this.buildable = true; var addParam = function (built, param, arg, isArgAvailable) { if (hasOwn.call(built, param)) return; var all = _this.allFields; if (!hasOwn.call(all, param)) { throw new Error("" + param); } var field = all[param]; var type = field.type; var value; if (isArgAvailable) { value = arg; } else if (field.defaultFn) { // Expose the partially-built object to the default // function as its `this` object. value = field.defaultFn.call(built); } else { var message = "no value or default function given for field " + JSON.stringify(param) + " of " + _this.typeName + "(" + _this.buildParams.map(function (name) { return all[name]; }).join(", ") + ")"; throw new Error(message); } if (!type.check(value)) { throw new Error(shallowStringify(value) + " does not match field " + field + " of type " + _this.typeName); } built[param] = value; }; // Calling the builder function will construct an instance of the Def, // with positional arguments mapped to the fields original passed to .build. // If not enough arguments are provided, the default value for the remaining fields // will be used. var builder = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var argc = args.length; if (!_this.finalized) { throw new Error("attempting to instantiate unfinalized type " + _this.typeName); } var built = Object.create(nodePrototype); _this.buildParams.forEach(function (param, i) { if (i < argc) { addParam(built, param, args[i], true); } else { addParam(built, param, null, false); } }); Object.keys(_this.allFields).forEach(function (param) { // Use the default value. addParam(built, param, null, false); }); // Make sure that the "type" field was filled automatically. if (built.type !== _this.typeName) { throw new Error(""); } return built; }; // Calling .from on the builder function will construct an instance of the Def, // using field values from the passed object. For fields missing from the passed object, // their default value will be used. builder.from = function (obj) { if (!_this.finalized) { throw new Error("attempting to instantiate unfinalized type " + _this.typeName); } var built = Object.create(nodePrototype); Object.keys(_this.allFields).forEach(function (param) { if (hasOwn.call(obj, param)) { addParam(built, param, obj[param], true); } else { addParam(built, param, null, false); } }); // Make sure that the "type" field was filled automatically. if (built.type !== _this.typeName) { throw new Error(""); } return built; }; Object.defineProperty(builders, getBuilderName(this.typeName), { enumerable: true, value: builder }); return this; }; // The reason fields are specified using .field(...) instead of an object // literal syntax is somewhat subtle: the object literal syntax would // support only one key and one value, but with .field(...) we can pass // any number of arguments to specify the field. DefImpl.prototype.field = function (name, type, defaultFn, hidden) { if (this.finalized) { console.error("Ignoring attempt to redefine field " + JSON.stringify(name) + " of finalized type " + JSON.stringify(this.typeName)); return this; } this.ownFields[name] = new Field(name, Type.from(type), defaultFn, hidden); return this; // For chaining. }; DefImpl.prototype.finalize = function () { var _this = this; // It's not an error to finalize a type more than once, but only the // first call to .finalize does anything. if (!this.finalized) { var allFields = this.allFields; var allSupertypes = this.allSupertypes; this.baseNames.forEach(function (name) { var def = defCache[name]; if (def instanceof Def) { def.finalize(); extend(allFields, def.allFields); extend(allSupertypes, def.allSupertypes); } else { var message = "unknown supertype name " + JSON.stringify(name) + " for subtype " + JSON.stringify(_this.typeName); throw new Error(message); } }); // TODO Warn if fields are overridden with incompatible types. extend(allFields, this.ownFields); allSupertypes[this.typeName] = this; this.fieldNames.length = 0; for (var fieldName in allFields) { if (hasOwn.call(allFields, fieldName) && !allFields[fieldName].hidden) { this.fieldNames.push(fieldName); } } // Types are exported only once they have been finalized. Object.defineProperty(namedTypes, this.typeName, { enumerable: true, value: this.type }); this.finalized = true; // A linearization of the inheritance hierarchy. populateSupertypeList(this.typeName, this.supertypeList); if (this.buildable && this.supertypeList.lastIndexOf("Expression") >= 0) { wrapExpressionBuilderWithStatement(this.typeName); } } }; return DefImpl; }(Def)); // Note that the list returned by this function is a copy of the internal // supertypeList, *without* the typeName itself as the first element. function getSupertypeNames(typeName) { if (!hasOwn.call(defCache, typeName)) { throw new Error(""); } var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } return d.supertypeList.slice(1); } // Returns an object mapping from every known type in the defCache to the // most specific supertype whose name is an own property of the candidates // object. function computeSupertypeLookupTable(candidates) { var table = {}; var typeNames = Object.keys(defCache); var typeNameCount = typeNames.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNames[i]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error("" + typeName); } for (var j = 0; j < d.supertypeList.length; ++j) { var superTypeName = d.supertypeList[j]; if (hasOwn.call(candidates, superTypeName)) { table[typeName] = superTypeName; break; } } } return table; } var builders = Object.create(null); // This object is used as prototype for any node created by a builder. var nodePrototype = {}; // Call this function to define a new method to be shared by all AST // nodes. The replaced method (if any) is returned for easy wrapping. function defineMethod(name, func) { var old = nodePrototype[name]; // Pass undefined as func to delete nodePrototype[name]. if (isUndefined.check(func)) { delete nodePrototype[name]; } else { isFunction.assert(func); Object.defineProperty(nodePrototype, name, { enumerable: true, configurable: true, value: func }); } return old; } function getBuilderName(typeName) { return typeName.replace(/^[A-Z]+/, function (upperCasePrefix) { var len = upperCasePrefix.length; switch (len) { case 0: return ""; // If there's only one initial capital letter, just lower-case it. case 1: return upperCasePrefix.toLowerCase(); default: // If there's more than one initial capital letter, lower-case // all but the last one, so that XMLDefaultDeclaration (for // example) becomes xmlDefaultDeclaration. return upperCasePrefix.slice(0, len - 1).toLowerCase() + upperCasePrefix.charAt(len - 1); } }); } function getStatementBuilderName(typeName) { typeName = getBuilderName(typeName); return typeName.replace(/(Expression)?$/, "Statement"); } var namedTypes = {}; // Like Object.keys, but aware of what fields each AST type should have. function getFieldNames(object) { var d = defFromValue(object); if (d) { return d.fieldNames.slice(0); } if ("type" in object) { throw new Error("did not recognize object of type " + JSON.stringify(object.type)); } return Object.keys(object); } // Get the value of an object property, taking object.type and default // functions into account. function getFieldValue(object, fieldName) { var d = defFromValue(object); if (d) { var field = d.allFields[fieldName]; if (field) { return field.getValue(object); } } return object && object[fieldName]; } // Iterate over all defined fields of an object, including those missing // or undefined, passing each field name and effective value (as returned // by getFieldValue) to the callback. If the object has no corresponding // Def, the callback will never be called. function eachField(object, callback, context) { getFieldNames(object).forEach(function (name) { callback.call(this, name, getFieldValue(object, name)); }, context); } // Similar to eachField, except that iteration stops as soon as the // callback returns a truthy value. Like Array.prototype.some, the final // result is either true or false to indicates whether the callback // returned true for any element or not. function someField(object, callback, context) { return getFieldNames(object).some(function (name) { return callback.call(this, name, getFieldValue(object, name)); }, context); } // Adds an additional builder for Expression subtypes // that wraps the built Expression in an ExpressionStatements. function wrapExpressionBuilderWithStatement(typeName) { var wrapperName = getStatementBuilderName(typeName); // skip if the builder already exists if (builders[wrapperName]) return; // the builder function to wrap with builders.ExpressionStatement var wrapped = builders[getBuilderName(typeName)]; // skip if there is nothing to wrap if (!wrapped) return; var builder = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return builders.expressionStatement(wrapped.apply(builders, args)); }; builder.from = function () { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } return builders.expressionStatement(wrapped.from.apply(builders, args)); }; builders[wrapperName] = builder; } function populateSupertypeList(typeName, list) { list.length = 0; list.push(typeName); var lastSeen = Object.create(null); for (var pos = 0; pos < list.length; ++pos) { typeName = list[pos]; var d = defCache[typeName]; if (d.finalized !== true) { throw new Error(""); } // If we saw typeName earlier in the breadth-first traversal, // delete the last-seen occurrence. if (hasOwn.call(lastSeen, typeName)) { delete list[lastSeen[typeName]]; } // Record the new index of the last-seen occurrence of typeName. lastSeen[typeName] = pos; // Enqueue the base names of this type. list.push.apply(list, d.baseNames); } // Compaction loop to remove array holes. for (var to = 0, from = to, len = list.length; from < len; ++from) { if (hasOwn.call(list, from)) { list[to++] = list[from]; } } list.length = to; } function extend(into, from) { Object.keys(from).forEach(function (name) { into[name] = from[name]; }); return into; } function finalize() { Object.keys(defCache).forEach(function (name) { defCache[name].finalize(); }); } return { Type: Type, builtInTypes: builtInTypes, getSupertypeNames: getSupertypeNames, computeSupertypeLookupTable: computeSupertypeLookupTable, builders: builders, defineMethod: defineMethod, getBuilderName: getBuilderName, getStatementBuilderName: getStatementBuilderName, namedTypes: namedTypes, getFieldNames: getFieldNames, getFieldValue: getFieldValue, eachField: eachField, someField: someField, finalize: finalize, }; } exports.default = typesPlugin; ; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/types.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
6,493
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); function default_1(fork) { var types = fork.use(types_1.default); var Type = types.Type; var builtin = types.builtInTypes; var isNumber = builtin.number; // An example of constructing a new type with arbitrary constraints from // an existing type. function geq(than) { return Type.from(function (value) { return isNumber.check(value) && value >= than; }, isNumber + " >= " + than); } ; // Default value-returning functions that may optionally be passed as a // third argument to Def.prototype.field. var defaults = { // Functions were used because (among other reasons) that's the most // elegant way to allow for the emptyArray one always to give a new // array instance. "null": function () { return null; }, "emptyArray": function () { return []; }, "false": function () { return false; }, "true": function () { return true; }, "undefined": function () { }, "use strict": function () { return "use strict"; } }; var naiveIsPrimitive = Type.or(builtin.string, builtin.number, builtin.boolean, builtin.null, builtin.undefined); var isPrimitive = Type.from(function (value) { if (value === null) return true; var type = typeof value; if (type === "object" || type === "function") { return false; } return true; }, naiveIsPrimitive.toString()); return { geq: geq, defaults: defaults, isPrimitive: isPrimitive, }; } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/shared.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
408
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); var Op = Object.prototype; var hasOwn = Op.hasOwnProperty; function pathPlugin(fork) { var types = fork.use(types_1.default); var isArray = types.builtInTypes.array; var isNumber = types.builtInTypes.number; var Path = function Path(value, parentPath, name) { if (!(this instanceof Path)) { throw new Error("Path constructor cannot be invoked without 'new'"); } if (parentPath) { if (!(parentPath instanceof Path)) { throw new Error(""); } } else { parentPath = null; name = null; } // The value encapsulated by this Path, generally equal to // parentPath.value[name] if we have a parentPath. this.value = value; // The immediate parent Path of this Path. this.parentPath = parentPath; // The name of the property of parentPath.value through which this // Path's value was reached. this.name = name; // Calling path.get("child") multiple times always returns the same // child Path object, for both performance and consistency reasons. this.__childCache = null; }; var Pp = Path.prototype; function getChildCache(path) { // Lazily create the child cache. This also cheapens cache // invalidation, since you can just reset path.__childCache to null. return path.__childCache || (path.__childCache = Object.create(null)); } function getChildPath(path, name) { var cache = getChildCache(path); var actualChildValue = path.getValueProperty(name); var childPath = cache[name]; if (!hasOwn.call(cache, name) || // Ensure consistency between cache and reality. childPath.value !== actualChildValue) { childPath = cache[name] = new path.constructor(actualChildValue, path, name); } return childPath; } // This method is designed to be overridden by subclasses that need to // handle missing properties, etc. Pp.getValueProperty = function getValueProperty(name) { return this.value[name]; }; Pp.get = function get() { var names = []; for (var _i = 0; _i < arguments.length; _i++) { names[_i] = arguments[_i]; } var path = this; var count = names.length; for (var i = 0; i < count; ++i) { path = getChildPath(path, names[i]); } return path; }; Pp.each = function each(callback, context) { var childPaths = []; var len = this.value.length; var i = 0; // Collect all the original child paths before invoking the callback. for (var i = 0; i < len; ++i) { if (hasOwn.call(this.value, i)) { childPaths[i] = this.get(i); } } // Invoke the callback on just the original child paths, regardless of // any modifications made to the array by the callback. I chose these // semantics over cleverly invoking the callback on new elements because // this way is much easier to reason about. context = context || this; for (i = 0; i < len; ++i) { if (hasOwn.call(childPaths, i)) { callback.call(context, childPaths[i]); } } }; Pp.map = function map(callback, context) { var result = []; this.each(function (childPath) { result.push(callback.call(this, childPath)); }, context); return result; }; Pp.filter = function filter(callback, context) { var result = []; this.each(function (childPath) { if (callback.call(this, childPath)) { result.push(childPath); } }, context); return result; }; function emptyMoves() { } function getMoves(path, offset, start, end) { isArray.assert(path.value); if (offset === 0) { return emptyMoves; } var length = path.value.length; if (length < 1) { return emptyMoves; } var argc = arguments.length; if (argc === 2) { start = 0; end = length; } else if (argc === 3) { start = Math.max(start, 0); end = length; } else { start = Math.max(start, 0); end = Math.min(end, length); } isNumber.assert(start); isNumber.assert(end); var moves = Object.create(null); var cache = getChildCache(path); for (var i = start; i < end; ++i) { if (hasOwn.call(path.value, i)) { var childPath = path.get(i); if (childPath.name !== i) { throw new Error(""); } var newIndex = i + offset; childPath.name = newIndex; moves[newIndex] = childPath; delete cache[i]; } } delete cache.length; return function () { for (var newIndex in moves) { var childPath = moves[newIndex]; if (childPath.name !== +newIndex) { throw new Error(""); } cache[newIndex] = childPath; path.value[newIndex] = childPath.value; } }; } Pp.shift = function shift() { var move = getMoves(this, -1); var result = this.value.shift(); move(); return result; }; Pp.unshift = function unshift() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var move = getMoves(this, args.length); var result = this.value.unshift.apply(this.value, args); move(); return result; }; Pp.push = function push() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } isArray.assert(this.value); delete getChildCache(this).length; return this.value.push.apply(this.value, args); }; Pp.pop = function pop() { isArray.assert(this.value); var cache = getChildCache(this); delete cache[this.value.length - 1]; delete cache.length; return this.value.pop(); }; Pp.insertAt = function insertAt(index) { var argc = arguments.length; var move = getMoves(this, argc - 1, index); if (move === emptyMoves && argc <= 1) { return this; } index = Math.max(index, 0); for (var i = 1; i < argc; ++i) { this.value[index + i - 1] = arguments[i]; } move(); return this; }; Pp.insertBefore = function insertBefore() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(args[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; Pp.insertAfter = function insertAfter() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var pp = this.parentPath; var argc = args.length; var insertAtArgs = [this.name + 1]; for (var i = 0; i < argc; ++i) { insertAtArgs.push(args[i]); } return pp.insertAt.apply(pp, insertAtArgs); }; function repairRelationshipWithParent(path) { if (!(path instanceof Path)) { throw new Error(""); } var pp = path.parentPath; if (!pp) { // Orphan paths have no relationship to repair. return path; } var parentValue = pp.value; var parentCache = getChildCache(pp); // Make sure parentCache[path.name] is populated. if (parentValue[path.name] === path.value) { parentCache[path.name] = path; } else if (isArray.check(parentValue)) { // Something caused path.name to become out of date, so attempt to // recover by searching for path.value in parentValue. var i = parentValue.indexOf(path.value); if (i >= 0) { parentCache[path.name = i] = path; } } else { // If path.value disagrees with parentValue[path.name], and // path.name is not an array index, let path.value become the new // parentValue[path.name] and update parentCache accordingly. parentValue[path.name] = path.value; parentCache[path.name] = path; } if (parentValue[path.name] !== path.value) { throw new Error(""); } if (path.parentPath.get(path.name) !== path) { throw new Error(""); } return path; } Pp.replace = function replace(replacement) { var results = []; var parentValue = this.parentPath.value; var parentCache = getChildCache(this.parentPath); var count = arguments.length; repairRelationshipWithParent(this); if (isArray.check(parentValue)) { var originalLength = parentValue.length; var move = getMoves(this.parentPath, count - 1, this.name + 1); var spliceArgs = [this.name, 1]; for (var i = 0; i < count; ++i) { spliceArgs.push(arguments[i]); } var splicedOut = parentValue.splice.apply(parentValue, spliceArgs); if (splicedOut[0] !== this.value) { throw new Error(""); } if (parentValue.length !== (originalLength - 1 + count)) { throw new Error(""); } move(); if (count === 0) { delete this.value; delete parentCache[this.name]; this.__childCache = null; } else { if (parentValue[this.name] !== replacement) { throw new Error(""); } if (this.value !== replacement) { this.value = replacement; this.__childCache = null; } for (i = 0; i < count; ++i) { results.push(this.parentPath.get(this.name + i)); } if (results[0] !== this) { throw new Error(""); } } } else if (count === 1) { if (this.value !== replacement) { this.__childCache = null; } this.value = parentValue[this.name] = replacement; results.push(this); } else if (count === 0) { delete parentValue[this.name]; delete this.value; this.__childCache = null; // Leave this path cached as parentCache[this.name], even though // it no longer has a value defined. } else { throw new Error("Could not replace path"); } return results; }; return Path; } exports.default = pathPlugin; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/path.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,553
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); function default_1(fork) { var types = fork.use(types_1.default); var getFieldNames = types.getFieldNames; var getFieldValue = types.getFieldValue; var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var isDate = types.builtInTypes.Date; var isRegExp = types.builtInTypes.RegExp; var hasOwn = Object.prototype.hasOwnProperty; function astNodesAreEquivalent(a, b, problemPath) { if (isArray.check(problemPath)) { problemPath.length = 0; } else { problemPath = null; } return areEquivalent(a, b, problemPath); } astNodesAreEquivalent.assert = function (a, b) { var problemPath = []; if (!astNodesAreEquivalent(a, b, problemPath)) { if (problemPath.length === 0) { if (a !== b) { throw new Error("Nodes must be equal"); } } else { throw new Error("Nodes differ in the following path: " + problemPath.map(subscriptForProperty).join("")); } } }; function subscriptForProperty(property) { if (/[_$a-z][_$a-z0-9]*/i.test(property)) { return "." + property; } return "[" + JSON.stringify(property) + "]"; } function areEquivalent(a, b, problemPath) { if (a === b) { return true; } if (isArray.check(a)) { return arraysAreEquivalent(a, b, problemPath); } if (isObject.check(a)) { return objectsAreEquivalent(a, b, problemPath); } if (isDate.check(a)) { return isDate.check(b) && (+a === +b); } if (isRegExp.check(a)) { return isRegExp.check(b) && (a.source === b.source && a.global === b.global && a.multiline === b.multiline && a.ignoreCase === b.ignoreCase); } return a == b; } function arraysAreEquivalent(a, b, problemPath) { isArray.assert(a); var aLength = a.length; if (!isArray.check(b) || b.length !== aLength) { if (problemPath) { problemPath.push("length"); } return false; } for (var i = 0; i < aLength; ++i) { if (problemPath) { problemPath.push(i); } if (i in a !== i in b) { return false; } if (!areEquivalent(a[i], b[i], problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== i) { throw new Error("" + problemPathTail); } } } return true; } function objectsAreEquivalent(a, b, problemPath) { isObject.assert(a); if (!isObject.check(b)) { return false; } // Fast path for a common property of AST nodes. if (a.type !== b.type) { if (problemPath) { problemPath.push("type"); } return false; } var aNames = getFieldNames(a); var aNameCount = aNames.length; var bNames = getFieldNames(b); var bNameCount = bNames.length; if (aNameCount === bNameCount) { for (var i = 0; i < aNameCount; ++i) { var name = aNames[i]; var aChild = getFieldValue(a, name); var bChild = getFieldValue(b, name); if (problemPath) { problemPath.push(name); } if (!areEquivalent(aChild, bChild, problemPath)) { return false; } if (problemPath) { var problemPathTail = problemPath.pop(); if (problemPathTail !== name) { throw new Error("" + problemPathTail); } } } return true; } if (!problemPath) { return false; } // Since aNameCount !== bNameCount, we need to find some name that's // missing in aNames but present in bNames, or vice-versa. var seenNames = Object.create(null); for (i = 0; i < aNameCount; ++i) { seenNames[aNames[i]] = true; } for (i = 0; i < bNameCount; ++i) { name = bNames[i]; if (!hasOwn.call(seenNames, name)) { problemPath.push(name); return false; } delete seenNames[name]; } for (name in seenNames) { problemPath.push(name); break; } return false; } return astNodesAreEquivalent; } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/equiv.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,137
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); var hasOwn = Object.prototype.hasOwnProperty; function scopePlugin(fork) { var types = fork.use(types_1.default); var Type = types.Type; var namedTypes = types.namedTypes; var Node = namedTypes.Node; var Expression = namedTypes.Expression; var isArray = types.builtInTypes.array; var b = types.builders; var Scope = function Scope(path, parentScope) { if (!(this instanceof Scope)) { throw new Error("Scope constructor cannot be invoked without 'new'"); } ScopeType.assert(path.value); var depth; if (parentScope) { if (!(parentScope instanceof Scope)) { throw new Error(""); } depth = parentScope.depth + 1; } else { parentScope = null; depth = 0; } Object.defineProperties(this, { path: { value: path }, node: { value: path.value }, isGlobal: { value: !parentScope, enumerable: true }, depth: { value: depth }, parent: { value: parentScope }, bindings: { value: {} }, types: { value: {} }, }); }; var scopeTypes = [ // Program nodes introduce global scopes. namedTypes.Program, // Function is the supertype of FunctionExpression, // FunctionDeclaration, ArrowExpression, etc. namedTypes.Function, // In case you didn't know, the caught parameter shadows any variable // of the same name in an outer scope. namedTypes.CatchClause ]; var ScopeType = Type.or.apply(Type, scopeTypes); Scope.isEstablishedBy = function (node) { return ScopeType.check(node); }; var Sp = Scope.prototype; // Will be overridden after an instance lazily calls scanScope. Sp.didScan = false; Sp.declares = function (name) { this.scan(); return hasOwn.call(this.bindings, name); }; Sp.declaresType = function (name) { this.scan(); return hasOwn.call(this.types, name); }; Sp.declareTemporary = function (prefix) { if (prefix) { if (!/^[a-z$_]/i.test(prefix)) { throw new Error(""); } } else { prefix = "t$"; } // Include this.depth in the name to make sure the name does not // collide with any variables in nested/enclosing scopes. prefix += this.depth.toString(36) + "$"; this.scan(); var index = 0; while (this.declares(prefix + index)) { ++index; } var name = prefix + index; return this.bindings[name] = types.builders.identifier(name); }; Sp.injectTemporary = function (identifier, init) { identifier || (identifier = this.declareTemporary()); var bodyPath = this.path.get("body"); if (namedTypes.BlockStatement.check(bodyPath.value)) { bodyPath = bodyPath.get("body"); } bodyPath.unshift(b.variableDeclaration("var", [b.variableDeclarator(identifier, init || null)])); return identifier; }; Sp.scan = function (force) { if (force || !this.didScan) { for (var name in this.bindings) { // Empty out this.bindings, just in cases. delete this.bindings[name]; } scanScope(this.path, this.bindings, this.types); this.didScan = true; } }; Sp.getBindings = function () { this.scan(); return this.bindings; }; Sp.getTypes = function () { this.scan(); return this.types; }; function scanScope(path, bindings, scopeTypes) { var node = path.value; ScopeType.assert(node); if (namedTypes.CatchClause.check(node)) { // A catch clause establishes a new scope but the only variable // bound in that scope is the catch parameter. Any other // declarations create bindings in the outer scope. var param = path.get("param"); if (param.value) { addPattern(param, bindings); } } else { recursiveScanScope(path, bindings, scopeTypes); } } function recursiveScanScope(path, bindings, scopeTypes) { var node = path.value; if (path.parent && namedTypes.FunctionExpression.check(path.parent.node) && path.parent.node.id) { addPattern(path.parent.get("id"), bindings); } if (!node) { // None of the remaining cases matter if node is falsy. } else if (isArray.check(node)) { path.each(function (childPath) { recursiveScanChild(childPath, bindings, scopeTypes); }); } else if (namedTypes.Function.check(node)) { path.get("params").each(function (paramPath) { addPattern(paramPath, bindings); }); recursiveScanChild(path.get("body"), bindings, scopeTypes); } else if ((namedTypes.TypeAlias && namedTypes.TypeAlias.check(node)) || (namedTypes.InterfaceDeclaration && namedTypes.InterfaceDeclaration.check(node)) || (namedTypes.TSTypeAliasDeclaration && namedTypes.TSTypeAliasDeclaration.check(node)) || (namedTypes.TSInterfaceDeclaration && namedTypes.TSInterfaceDeclaration.check(node))) { addTypePattern(path.get("id"), scopeTypes); } else if (namedTypes.VariableDeclarator.check(node)) { addPattern(path.get("id"), bindings); recursiveScanChild(path.get("init"), bindings, scopeTypes); } else if (node.type === "ImportSpecifier" || node.type === "ImportNamespaceSpecifier" || node.type === "ImportDefaultSpecifier") { addPattern( // Esprima used to use the .name field to refer to the local // binding identifier for ImportSpecifier nodes, but .id for // ImportNamespaceSpecifier and ImportDefaultSpecifier nodes. // ESTree/Acorn/ESpree use .local for all three node types. path.get(node.local ? "local" : node.name ? "name" : "id"), bindings); } else if (Node.check(node) && !Expression.check(node)) { types.eachField(node, function (name, child) { var childPath = path.get(name); if (!pathHasValue(childPath, child)) { throw new Error(""); } recursiveScanChild(childPath, bindings, scopeTypes); }); } } function pathHasValue(path, value) { if (path.value === value) { return true; } // Empty arrays are probably produced by defaults.emptyArray, in which // case is makes sense to regard them as equivalent, if not ===. if (Array.isArray(path.value) && path.value.length === 0 && Array.isArray(value) && value.length === 0) { return true; } return false; } function recursiveScanChild(path, bindings, scopeTypes) { var node = path.value; if (!node || Expression.check(node)) { // Ignore falsy values and Expressions. } else if (namedTypes.FunctionDeclaration.check(node) && node.id !== null) { addPattern(path.get("id"), bindings); } else if (namedTypes.ClassDeclaration && namedTypes.ClassDeclaration.check(node)) { addPattern(path.get("id"), bindings); } else if (ScopeType.check(node)) { if (namedTypes.CatchClause.check(node) && // TODO Broaden this to accept any pattern. namedTypes.Identifier.check(node.param)) { var catchParamName = node.param.name; var hadBinding = hasOwn.call(bindings, catchParamName); // Any declarations that occur inside the catch body that do // not have the same name as the catch parameter should count // as bindings in the outer scope. recursiveScanScope(path.get("body"), bindings, scopeTypes); // If a new binding matching the catch parameter name was // created while scanning the catch body, ignore it because it // actually refers to the catch parameter and not the outer // scope that we're currently scanning. if (!hadBinding) { delete bindings[catchParamName]; } } } else { recursiveScanScope(path, bindings, scopeTypes); } } function addPattern(patternPath, bindings) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(bindings, pattern.name)) { bindings[pattern.name].push(patternPath); } else { bindings[pattern.name] = [patternPath]; } } else if (namedTypes.AssignmentPattern && namedTypes.AssignmentPattern.check(pattern)) { addPattern(patternPath.get('left'), bindings); } else if (namedTypes.ObjectPattern && namedTypes.ObjectPattern.check(pattern)) { patternPath.get('properties').each(function (propertyPath) { var property = propertyPath.value; if (namedTypes.Pattern.check(property)) { addPattern(propertyPath, bindings); } else if (namedTypes.Property.check(property)) { addPattern(propertyPath.get('value'), bindings); } else if (namedTypes.SpreadProperty && namedTypes.SpreadProperty.check(property)) { addPattern(propertyPath.get('argument'), bindings); } }); } else if (namedTypes.ArrayPattern && namedTypes.ArrayPattern.check(pattern)) { patternPath.get('elements').each(function (elementPath) { var element = elementPath.value; if (namedTypes.Pattern.check(element)) { addPattern(elementPath, bindings); } else if (namedTypes.SpreadElement && namedTypes.SpreadElement.check(element)) { addPattern(elementPath.get("argument"), bindings); } }); } else if (namedTypes.PropertyPattern && namedTypes.PropertyPattern.check(pattern)) { addPattern(patternPath.get('pattern'), bindings); } else if ((namedTypes.SpreadElementPattern && namedTypes.SpreadElementPattern.check(pattern)) || (namedTypes.SpreadPropertyPattern && namedTypes.SpreadPropertyPattern.check(pattern))) { addPattern(patternPath.get('argument'), bindings); } } function addTypePattern(patternPath, types) { var pattern = patternPath.value; namedTypes.Pattern.assert(pattern); if (namedTypes.Identifier.check(pattern)) { if (hasOwn.call(types, pattern.name)) { types[pattern.name].push(patternPath); } else { types[pattern.name] = [patternPath]; } } } Sp.lookup = function (name) { for (var scope = this; scope; scope = scope.parent) if (scope.declares(name)) break; return scope; }; Sp.lookupType = function (name) { for (var scope = this; scope; scope = scope.parent) if (scope.declaresType(name)) break; return scope; }; Sp.getGlobalScope = function () { var scope = this; while (!scope.isGlobal) scope = scope.parent; return scope; }; return Scope; } exports.default = scopePlugin; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/scope.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,486
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); var node_path_1 = tslib_1.__importDefault(require("./node-path")); var hasOwn = Object.prototype.hasOwnProperty; function pathVisitorPlugin(fork) { var types = fork.use(types_1.default); var NodePath = fork.use(node_path_1.default); var isArray = types.builtInTypes.array; var isObject = types.builtInTypes.object; var isFunction = types.builtInTypes.function; var undefined; var PathVisitor = function PathVisitor() { if (!(this instanceof PathVisitor)) { throw new Error("PathVisitor constructor cannot be invoked without 'new'"); } // Permanent state. this._reusableContextStack = []; this._methodNameTable = computeMethodNameTable(this); this._shouldVisitComments = hasOwn.call(this._methodNameTable, "Block") || hasOwn.call(this._methodNameTable, "Line"); this.Context = makeContextConstructor(this); // State reset every time PathVisitor.prototype.visit is called. this._visiting = false; this._changeReported = false; }; function computeMethodNameTable(visitor) { var typeNames = Object.create(null); for (var methodName in visitor) { if (/^visit[A-Z]/.test(methodName)) { typeNames[methodName.slice("visit".length)] = true; } } var supertypeTable = types.computeSupertypeLookupTable(typeNames); var methodNameTable = Object.create(null); var typeNameKeys = Object.keys(supertypeTable); var typeNameCount = typeNameKeys.length; for (var i = 0; i < typeNameCount; ++i) { var typeName = typeNameKeys[i]; methodName = "visit" + supertypeTable[typeName]; if (isFunction.check(visitor[methodName])) { methodNameTable[typeName] = methodName; } } return methodNameTable; } PathVisitor.fromMethodsObject = function fromMethodsObject(methods) { if (methods instanceof PathVisitor) { return methods; } if (!isObject.check(methods)) { // An empty visitor? return new PathVisitor; } var Visitor = function Visitor() { if (!(this instanceof Visitor)) { throw new Error("Visitor constructor cannot be invoked without 'new'"); } PathVisitor.call(this); }; var Vp = Visitor.prototype = Object.create(PVp); Vp.constructor = Visitor; extend(Vp, methods); extend(Visitor, PathVisitor); isFunction.assert(Visitor.fromMethodsObject); isFunction.assert(Visitor.visit); return new Visitor; }; function extend(target, source) { for (var property in source) { if (hasOwn.call(source, property)) { target[property] = source[property]; } } return target; } PathVisitor.visit = function visit(node, methods) { return PathVisitor.fromMethodsObject(methods).visit(node); }; var PVp = PathVisitor.prototype; PVp.visit = function () { if (this._visiting) { throw new Error("Recursively calling visitor.visit(path) resets visitor state. " + "Try this.visit(path) or this.traverse(path) instead."); } // Private state that needs to be reset before every traversal. this._visiting = true; this._changeReported = false; this._abortRequested = false; var argc = arguments.length; var args = new Array(argc); for (var i = 0; i < argc; ++i) { args[i] = arguments[i]; } if (!(args[0] instanceof NodePath)) { args[0] = new NodePath({ root: args[0] }).get("root"); } // Called with the same arguments as .visit. this.reset.apply(this, args); var didNotThrow; try { var root = this.visitWithoutReset(args[0]); didNotThrow = true; } finally { this._visiting = false; if (!didNotThrow && this._abortRequested) { // If this.visitWithoutReset threw an exception and // this._abortRequested was set to true, return the root of // the AST instead of letting the exception propagate, so that // client code does not have to provide a try-catch block to // intercept the AbortRequest exception. Other kinds of // exceptions will propagate without being intercepted and // rethrown by a catch block, so their stacks will accurately // reflect the original throwing context. return args[0].value; } } return root; }; PVp.AbortRequest = function AbortRequest() { }; PVp.abort = function () { var visitor = this; visitor._abortRequested = true; var request = new visitor.AbortRequest(); // If you decide to catch this exception and stop it from propagating, // make sure to call its cancel method to avoid silencing other // exceptions that might be thrown later in the traversal. request.cancel = function () { visitor._abortRequested = false; }; throw request; }; PVp.reset = function (_path /*, additional arguments */) { // Empty stub; may be reassigned or overridden by subclasses. }; PVp.visitWithoutReset = function (path) { if (this instanceof this.Context) { // Since this.Context.prototype === this, there's a chance we // might accidentally call context.visitWithoutReset. If that // happens, re-invoke the method against context.visitor. return this.visitor.visitWithoutReset(path); } if (!(path instanceof NodePath)) { throw new Error(""); } var value = path.value; var methodName = value && typeof value === "object" && typeof value.type === "string" && this._methodNameTable[value.type]; if (methodName) { var context = this.acquireContext(path); try { return context.invokeVisitorMethod(methodName); } finally { this.releaseContext(context); } } else { // If there was no visitor method to call, visit the children of // this node generically. return visitChildren(path, this); } }; function visitChildren(path, visitor) { if (!(path instanceof NodePath)) { throw new Error(""); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } var value = path.value; if (isArray.check(value)) { path.each(visitor.visitWithoutReset, visitor); } else if (!isObject.check(value)) { // No children to visit. } else { var childNames = types.getFieldNames(value); // The .comments field of the Node type is hidden, so we only // visit it if the visitor defines visitBlock or visitLine, and // value.comments is defined. if (visitor._shouldVisitComments && value.comments && childNames.indexOf("comments") < 0) { childNames.push("comments"); } var childCount = childNames.length; var childPaths = []; for (var i = 0; i < childCount; ++i) { var childName = childNames[i]; if (!hasOwn.call(value, childName)) { value[childName] = types.getFieldValue(value, childName); } childPaths.push(path.get(childName)); } for (var i = 0; i < childCount; ++i) { visitor.visitWithoutReset(childPaths[i]); } } return path.value; } PVp.acquireContext = function (path) { if (this._reusableContextStack.length === 0) { return new this.Context(path); } return this._reusableContextStack.pop().reset(path); }; PVp.releaseContext = function (context) { if (!(context instanceof this.Context)) { throw new Error(""); } this._reusableContextStack.push(context); context.currentPath = null; }; PVp.reportChanged = function () { this._changeReported = true; }; PVp.wasChangeReported = function () { return this._changeReported; }; function makeContextConstructor(visitor) { function Context(path) { if (!(this instanceof Context)) { throw new Error(""); } if (!(this instanceof PathVisitor)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } Object.defineProperty(this, "visitor", { value: visitor, writable: false, enumerable: true, configurable: false }); this.currentPath = path; this.needToCallTraverse = true; Object.seal(this); } if (!(visitor instanceof PathVisitor)) { throw new Error(""); } // Note that the visitor object is the prototype of Context.prototype, // so all visitor methods are inherited by context objects. var Cp = Context.prototype = Object.create(visitor); Cp.constructor = Context; extend(Cp, sharedContextProtoMethods); return Context; } // Every PathVisitor has a different this.Context constructor and // this.Context.prototype object, but those prototypes can all use the // same reset, invokeVisitorMethod, and traverse function objects. var sharedContextProtoMethods = Object.create(null); sharedContextProtoMethods.reset = function reset(path) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } this.currentPath = path; this.needToCallTraverse = true; return this; }; sharedContextProtoMethods.invokeVisitorMethod = function invokeVisitorMethod(methodName) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } var result = this.visitor[methodName].call(this, this.currentPath); if (result === false) { // Visitor methods return false to indicate that they have handled // their own traversal needs, and we should not complain if // this.needToCallTraverse is still true. this.needToCallTraverse = false; } else if (result !== undefined) { // Any other non-undefined value returned from the visitor method // is interpreted as a replacement value. this.currentPath = this.currentPath.replace(result)[0]; if (this.needToCallTraverse) { // If this.traverse still hasn't been called, visit the // children of the replacement node. this.traverse(this.currentPath); } } if (this.needToCallTraverse !== false) { throw new Error("Must either call this.traverse or return false in " + methodName); } var path = this.currentPath; return path && path.value; }; sharedContextProtoMethods.traverse = function traverse(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return visitChildren(path, PathVisitor.fromMethodsObject(newVisitor || this.visitor)); }; sharedContextProtoMethods.visit = function visit(path, newVisitor) { if (!(this instanceof this.Context)) { throw new Error(""); } if (!(path instanceof NodePath)) { throw new Error(""); } if (!(this.currentPath instanceof NodePath)) { throw new Error(""); } this.needToCallTraverse = false; return PathVisitor.fromMethodsObject(newVisitor || this.visitor).visitWithoutReset(path); }; sharedContextProtoMethods.reportChanged = function reportChanged() { this.visitor.reportChanged(); }; sharedContextProtoMethods.abort = function abort() { this.needToCallTraverse = false; this.visitor.abort(); }; return PathVisitor; } exports.default = pathVisitorPlugin; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/path-visitor.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,677
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var babel_core_1 = tslib_1.__importDefault(require("./babel-core")); var flow_1 = tslib_1.__importDefault(require("./flow")); function default_1(fork) { fork.use(babel_core_1.default); fork.use(flow_1.default); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/babel.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
98
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var es7_1 = tslib_1.__importDefault(require("./es7")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { fork.use(es7_1.default); var types = fork.use(types_1.default); var defaults = fork.use(shared_1.default).defaults; var def = types.Type.def; var or = types.Type.or; def("VariableDeclaration") .field("declarations", [or(def("VariableDeclarator"), def("Identifier") // Esprima deviation. )]); def("Property") .field("value", or(def("Expression"), def("Pattern") // Esprima deviation. )); def("ArrayPattern") .field("elements", [or(def("Pattern"), def("SpreadElement"), null)]); def("ObjectPattern") .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty") // Used by Esprima. )]); // Like ModuleSpecifier, except type:"ExportSpecifier" and buildable. // export {<id [as name]>} [from ...]; def("ExportSpecifier") .bases("ModuleSpecifier") .build("id", "name"); // export <*> from ...; def("ExportBatchSpecifier") .bases("Specifier") .build(); def("ExportDeclaration") .bases("Declaration") .build("default", "declaration", "specifiers", "source") .field("default", Boolean) .field("declaration", or(def("Declaration"), def("Expression"), // Implies default. null)) .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray) .field("source", or(def("Literal"), null), defaults["null"]); def("Block") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); def("Line") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/esprima.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
511
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("./types")); var path_1 = tslib_1.__importDefault(require("./path")); var scope_1 = tslib_1.__importDefault(require("./scope")); function nodePathPlugin(fork) { var types = fork.use(types_1.default); var n = types.namedTypes; var b = types.builders; var isNumber = types.builtInTypes.number; var isArray = types.builtInTypes.array; var Path = fork.use(path_1.default); var Scope = fork.use(scope_1.default); var NodePath = function NodePath(value, parentPath, name) { if (!(this instanceof NodePath)) { throw new Error("NodePath constructor cannot be invoked without 'new'"); } Path.call(this, value, parentPath, name); }; var NPp = NodePath.prototype = Object.create(Path.prototype, { constructor: { value: NodePath, enumerable: false, writable: true, configurable: true } }); Object.defineProperties(NPp, { node: { get: function () { Object.defineProperty(this, "node", { configurable: true, value: this._computeNode() }); return this.node; } }, parent: { get: function () { Object.defineProperty(this, "parent", { configurable: true, value: this._computeParent() }); return this.parent; } }, scope: { get: function () { Object.defineProperty(this, "scope", { configurable: true, value: this._computeScope() }); return this.scope; } } }); NPp.replace = function () { delete this.node; delete this.parent; delete this.scope; return Path.prototype.replace.apply(this, arguments); }; NPp.prune = function () { var remainingNodePath = this.parent; this.replace(); return cleanUpNodesAfterPrune(remainingNodePath); }; // The value of the first ancestor Path whose value is a Node. NPp._computeNode = function () { var value = this.value; if (n.Node.check(value)) { return value; } var pp = this.parentPath; return pp && pp.node || null; }; // The first ancestor Path whose value is a Node distinct from this.node. NPp._computeParent = function () { var value = this.value; var pp = this.parentPath; if (!n.Node.check(value)) { while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } if (pp) { pp = pp.parentPath; } } while (pp && !n.Node.check(pp.value)) { pp = pp.parentPath; } return pp || null; }; // The closest enclosing scope that governs this node. NPp._computeScope = function () { var value = this.value; var pp = this.parentPath; var scope = pp && pp.scope; if (n.Node.check(value) && Scope.isEstablishedBy(value)) { scope = new Scope(this, scope); } return scope || null; }; NPp.getValueProperty = function (name) { return types.getFieldValue(this.value, name); }; /** * Determine whether this.node needs to be wrapped in parentheses in order * for a parser to reproduce the same local AST structure. * * For instance, in the expression `(1 + 2) * 3`, the BinaryExpression * whose operator is "+" needs parentheses, because `1 + 2 * 3` would * parse differently. * * If assumeExpressionContext === true, we don't worry about edge cases * like an anonymous FunctionExpression appearing lexically first in its * enclosing statement and thus needing parentheses to avoid being parsed * as a FunctionDeclaration with a missing name. */ NPp.needsParens = function (assumeExpressionContext) { var pp = this.parentPath; if (!pp) { return false; } var node = this.value; // Only expressions need parentheses. if (!n.Expression.check(node)) { return false; } // Identifiers never need parentheses. if (node.type === "Identifier") { return false; } while (!n.Node.check(pp.value)) { pp = pp.parentPath; if (!pp) { return false; } } var parent = pp.value; switch (node.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return parent.type === "MemberExpression" && this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": switch (parent.type) { case "CallExpression": return this.name === "callee" && parent.callee === node; case "UnaryExpression": case "SpreadElement": case "SpreadProperty": return true; case "MemberExpression": return this.name === "object" && parent.object === node; case "BinaryExpression": case "LogicalExpression": { var n_1 = node; var po = parent.operator; var pp_1 = PRECEDENCE[po]; var no = n_1.operator; var np = PRECEDENCE[no]; if (pp_1 > np) { return true; } if (pp_1 === np && this.name === "right") { if (parent.right !== n_1) { throw new Error("Nodes must be equal"); } return true; } } default: return false; } case "SequenceExpression": switch (parent.type) { case "ForStatement": // Although parentheses wouldn't hurt around sequence // expressions in the head of for loops, traditional style // dictates that e.g. i++, j++ should not be wrapped with // parentheses. return false; case "ExpressionStatement": return this.name !== "expression"; default: // Otherwise err on the side of overparenthesization, adding // explicit exceptions above if this proves overzealous. return true; } case "YieldExpression": switch (parent.type) { case "BinaryExpression": case "LogicalExpression": case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "CallExpression": case "MemberExpression": case "NewExpression": case "ConditionalExpression": case "YieldExpression": return true; default: return false; } case "Literal": return parent.type === "MemberExpression" && isNumber.check(node.value) && this.name === "object" && parent.object === node; case "AssignmentExpression": case "ConditionalExpression": switch (parent.type) { case "UnaryExpression": case "SpreadElement": case "SpreadProperty": case "BinaryExpression": case "LogicalExpression": return true; case "CallExpression": return this.name === "callee" && parent.callee === node; case "ConditionalExpression": return this.name === "test" && parent.test === node; case "MemberExpression": return this.name === "object" && parent.object === node; default: return false; } default: if (parent.type === "NewExpression" && this.name === "callee" && parent.callee === node) { return containsCallExpression(node); } } if (assumeExpressionContext !== true && !this.canBeFirstInStatement() && this.firstInStatement()) return true; return false; }; function isBinary(node) { return n.BinaryExpression.check(node) || n.LogicalExpression.check(node); } // @ts-ignore 'isUnaryLike' is declared but its value is never read. [6133] function isUnaryLike(node) { return n.UnaryExpression.check(node) // I considered making SpreadElement and SpreadProperty subtypes // of UnaryExpression, but they're not really Expression nodes. || (n.SpreadElement && n.SpreadElement.check(node)) || (n.SpreadProperty && n.SpreadProperty.check(node)); } var PRECEDENCE = {}; [["||"], ["&&"], ["|"], ["^"], ["&"], ["==", "===", "!=", "!=="], ["<", ">", "<=", ">=", "in", "instanceof"], [">>", "<<", ">>>"], ["+", "-"], ["*", "/", "%"] ].forEach(function (tier, i) { tier.forEach(function (op) { PRECEDENCE[op] = i; }); }); function containsCallExpression(node) { if (n.CallExpression.check(node)) { return true; } if (isArray.check(node)) { return node.some(containsCallExpression); } if (n.Node.check(node)) { return types.someField(node, function (_name, child) { return containsCallExpression(child); }); } return false; } NPp.canBeFirstInStatement = function () { var node = this.node; return !n.FunctionExpression.check(node) && !n.ObjectExpression.check(node); }; NPp.firstInStatement = function () { return firstInStatement(this); }; function firstInStatement(path) { for (var node, parent; path.parent; path = path.parent) { node = path.node; parent = path.parent.node; if (n.BlockStatement.check(parent) && path.parent.name === "body" && path.name === 0) { if (parent.body[0] !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.ExpressionStatement.check(parent) && path.name === "expression") { if (parent.expression !== node) { throw new Error("Nodes must be equal"); } return true; } if (n.SequenceExpression.check(parent) && path.parent.name === "expressions" && path.name === 0) { if (parent.expressions[0] !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.CallExpression.check(parent) && path.name === "callee") { if (parent.callee !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.MemberExpression.check(parent) && path.name === "object") { if (parent.object !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.ConditionalExpression.check(parent) && path.name === "test") { if (parent.test !== node) { throw new Error("Nodes must be equal"); } continue; } if (isBinary(parent) && path.name === "left") { if (parent.left !== node) { throw new Error("Nodes must be equal"); } continue; } if (n.UnaryExpression.check(parent) && !parent.prefix && path.name === "argument") { if (parent.argument !== node) { throw new Error("Nodes must be equal"); } continue; } return false; } return true; } /** * Pruning certain nodes will result in empty or incomplete nodes, here we clean those nodes up. */ function cleanUpNodesAfterPrune(remainingNodePath) { if (n.VariableDeclaration.check(remainingNodePath.node)) { var declarations = remainingNodePath.get('declarations').value; if (!declarations || declarations.length === 0) { return remainingNodePath.prune(); } } else if (n.ExpressionStatement.check(remainingNodePath.node)) { if (!remainingNodePath.get('expression').value) { return remainingNodePath.prune(); } } else if (n.IfStatement.check(remainingNodePath.node)) { cleanUpIfStatementAfterPrune(remainingNodePath); } return remainingNodePath; } function cleanUpIfStatementAfterPrune(ifStatement) { var testExpression = ifStatement.get('test').value; var alternate = ifStatement.get('alternate').value; var consequent = ifStatement.get('consequent').value; if (!consequent && !alternate) { var testExpressionStatement = b.expressionStatement(testExpression); ifStatement.replace(testExpressionStatement); } else if (!consequent && alternate) { var negatedTestExpression = b.unaryExpression('!', testExpression, true); if (n.UnaryExpression.check(testExpression) && testExpression.operator === '!') { negatedTestExpression = testExpression.argument; } ifStatement.get("test").replace(negatedTestExpression); ifStatement.get("consequent").replace(alternate); ifStatement.get("alternate").replace(); } } return NodePath; } exports.default = nodePathPlugin; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/lib/node-path.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,905
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var es7_1 = tslib_1.__importDefault(require("./es7")); var types_1 = tslib_1.__importDefault(require("../lib/types")); function default_1(fork) { fork.use(es7_1.default); var types = fork.use(types_1.default); var def = types.Type.def; def("ImportExpression") .bases("Expression") .build("source") .field("source", def("Expression")); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/es2020.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
137
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { var types = fork.use(types_1.default); var Type = types.Type; var def = Type.def; var or = Type.or; var shared = fork.use(shared_1.default); var defaults = shared.defaults; var geq = shared.geq; // Abstract supertype of all syntactic entities that are allowed to have a // .loc field. def("Printable") .field("loc", or(def("SourceLocation"), null), defaults["null"], true); def("Node") .bases("Printable") .field("type", String) .field("comments", or([def("Comment")], null), defaults["null"], true); def("SourceLocation") .field("start", def("Position")) .field("end", def("Position")) .field("source", or(String, null), defaults["null"]); def("Position") .field("line", geq(1)) .field("column", geq(0)); def("File") .bases("Node") .build("program", "name") .field("program", def("Program")) .field("name", or(String, null), defaults["null"]); def("Program") .bases("Node") .build("body") .field("body", [def("Statement")]); def("Function") .bases("Node") .field("id", or(def("Identifier"), null), defaults["null"]) .field("params", [def("Pattern")]) .field("body", def("BlockStatement")) .field("generator", Boolean, defaults["false"]) .field("async", Boolean, defaults["false"]); def("Statement").bases("Node"); // The empty .build() here means that an EmptyStatement can be constructed // (i.e. it's not abstract) but that it needs no arguments. def("EmptyStatement").bases("Statement").build(); def("BlockStatement") .bases("Statement") .build("body") .field("body", [def("Statement")]); // TODO Figure out how to silently coerce Expressions to // ExpressionStatements where a Statement was expected. def("ExpressionStatement") .bases("Statement") .build("expression") .field("expression", def("Expression")); def("IfStatement") .bases("Statement") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Statement")) .field("alternate", or(def("Statement"), null), defaults["null"]); def("LabeledStatement") .bases("Statement") .build("label", "body") .field("label", def("Identifier")) .field("body", def("Statement")); def("BreakStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("ContinueStatement") .bases("Statement") .build("label") .field("label", or(def("Identifier"), null), defaults["null"]); def("WithStatement") .bases("Statement") .build("object", "body") .field("object", def("Expression")) .field("body", def("Statement")); def("SwitchStatement") .bases("Statement") .build("discriminant", "cases", "lexical") .field("discriminant", def("Expression")) .field("cases", [def("SwitchCase")]) .field("lexical", Boolean, defaults["false"]); def("ReturnStatement") .bases("Statement") .build("argument") .field("argument", or(def("Expression"), null)); def("ThrowStatement") .bases("Statement") .build("argument") .field("argument", def("Expression")); def("TryStatement") .bases("Statement") .build("block", "handler", "finalizer") .field("block", def("BlockStatement")) .field("handler", or(def("CatchClause"), null), function () { return this.handlers && this.handlers[0] || null; }) .field("handlers", [def("CatchClause")], function () { return this.handler ? [this.handler] : []; }, true) // Indicates this field is hidden from eachField iteration. .field("guardedHandlers", [def("CatchClause")], defaults.emptyArray) .field("finalizer", or(def("BlockStatement"), null), defaults["null"]); def("CatchClause") .bases("Node") .build("param", "guard", "body") // path_to_url .field("param", or(def("Pattern"), null), defaults["null"]) .field("guard", or(def("Expression"), null), defaults["null"]) .field("body", def("BlockStatement")); def("WhileStatement") .bases("Statement") .build("test", "body") .field("test", def("Expression")) .field("body", def("Statement")); def("DoWhileStatement") .bases("Statement") .build("body", "test") .field("body", def("Statement")) .field("test", def("Expression")); def("ForStatement") .bases("Statement") .build("init", "test", "update", "body") .field("init", or(def("VariableDeclaration"), def("Expression"), null)) .field("test", or(def("Expression"), null)) .field("update", or(def("Expression"), null)) .field("body", def("Statement")); def("ForInStatement") .bases("Statement") .build("left", "right", "body") .field("left", or(def("VariableDeclaration"), def("Expression"))) .field("right", def("Expression")) .field("body", def("Statement")); def("DebuggerStatement").bases("Statement").build(); def("Declaration").bases("Statement"); def("FunctionDeclaration") .bases("Function", "Declaration") .build("id", "params", "body") .field("id", def("Identifier")); def("FunctionExpression") .bases("Function", "Expression") .build("id", "params", "body"); def("VariableDeclaration") .bases("Declaration") .build("kind", "declarations") .field("kind", or("var", "let", "const")) .field("declarations", [def("VariableDeclarator")]); def("VariableDeclarator") .bases("Node") .build("id", "init") .field("id", def("Pattern")) .field("init", or(def("Expression"), null), defaults["null"]); def("Expression").bases("Node"); def("ThisExpression").bases("Expression").build(); def("ArrayExpression") .bases("Expression") .build("elements") .field("elements", [or(def("Expression"), null)]); def("ObjectExpression") .bases("Expression") .build("properties") .field("properties", [def("Property")]); // TODO Not in the Mozilla Parser API, but used by Esprima. def("Property") .bases("Node") // Want to be able to visit Property Nodes. .build("kind", "key", "value") .field("kind", or("init", "get", "set")) .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("Expression")); def("SequenceExpression") .bases("Expression") .build("expressions") .field("expressions", [def("Expression")]); var UnaryOperator = or("-", "+", "!", "~", "typeof", "void", "delete"); def("UnaryExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UnaryOperator) .field("argument", def("Expression")) // Esprima doesn't bother with this field, presumably because it's // always true for unary operators. .field("prefix", Boolean, defaults["true"]); var BinaryOperator = or("==", "!=", "===", "!==", "<", "<=", ">", ">=", "<<", ">>", ">>>", "+", "-", "*", "/", "%", "**", "&", // TODO Missing from the Parser API. "|", "^", "in", "instanceof"); def("BinaryExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", BinaryOperator) .field("left", def("Expression")) .field("right", def("Expression")); var AssignmentOperator = or("=", "+=", "-=", "*=", "/=", "%=", "<<=", ">>=", ">>>=", "|=", "^=", "&="); def("AssignmentExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", AssignmentOperator) .field("left", or(def("Pattern"), def("MemberExpression"))) .field("right", def("Expression")); var UpdateOperator = or("++", "--"); def("UpdateExpression") .bases("Expression") .build("operator", "argument", "prefix") .field("operator", UpdateOperator) .field("argument", def("Expression")) .field("prefix", Boolean); var LogicalOperator = or("||", "&&"); def("LogicalExpression") .bases("Expression") .build("operator", "left", "right") .field("operator", LogicalOperator) .field("left", def("Expression")) .field("right", def("Expression")); def("ConditionalExpression") .bases("Expression") .build("test", "consequent", "alternate") .field("test", def("Expression")) .field("consequent", def("Expression")) .field("alternate", def("Expression")); def("NewExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // The Mozilla Parser API gives this type as [or(def("Expression"), // null)], but null values don't really make sense at the call site. // TODO Report this nonsense. .field("arguments", [def("Expression")]); def("CallExpression") .bases("Expression") .build("callee", "arguments") .field("callee", def("Expression")) // See comment for NewExpression above. .field("arguments", [def("Expression")]); def("MemberExpression") .bases("Expression") .build("object", "property", "computed") .field("object", def("Expression")) .field("property", or(def("Identifier"), def("Expression"))) .field("computed", Boolean, function () { var type = this.property.type; if (type === 'Literal' || type === 'MemberExpression' || type === 'BinaryExpression') { return true; } return false; }); def("Pattern").bases("Node"); def("SwitchCase") .bases("Node") .build("test", "consequent") .field("test", or(def("Expression"), null)) .field("consequent", [def("Statement")]); def("Identifier") .bases("Expression", "Pattern") .build("name") .field("name", String) .field("optional", Boolean, defaults["false"]); def("Literal") .bases("Expression") .build("value") .field("value", or(String, Boolean, null, Number, RegExp)) .field("regex", or({ pattern: String, flags: String }, null), function () { if (this.value instanceof RegExp) { var flags = ""; if (this.value.ignoreCase) flags += "i"; if (this.value.multiline) flags += "m"; if (this.value.global) flags += "g"; return { pattern: this.value.source, flags: flags }; } return null; }); // Abstract (non-buildable) comment supertype. Not a Node. def("Comment") .bases("Printable") .field("value", String) // A .leading comment comes before the node, whereas a .trailing // comment comes after it. These two fields should not both be true, // but they might both be false when the comment falls inside a node // and the node has no children for the comment to lead or trail, // e.g. { /*dangling*/ }. .field("leading", Boolean, defaults["true"]) .field("trailing", Boolean, defaults["false"]); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/core.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,869
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); var es7_1 = tslib_1.__importDefault(require("./es7")); function default_1(fork) { fork.use(es7_1.default); var types = fork.use(types_1.default); var defaults = fork.use(shared_1.default).defaults; var def = types.Type.def; var or = types.Type.or; def("Noop") .bases("Statement") .build(); def("DoExpression") .bases("Expression") .build("body") .field("body", [def("Statement")]); def("Super") .bases("Expression") .build(); def("BindExpression") .bases("Expression") .build("object", "callee") .field("object", or(def("Expression"), null)) .field("callee", def("Expression")); def("Decorator") .bases("Node") .build("expression") .field("expression", def("Expression")); def("Property") .field("decorators", or([def("Decorator")], null), defaults["null"]); def("MethodDefinition") .field("decorators", or([def("Decorator")], null), defaults["null"]); def("MetaProperty") .bases("Expression") .build("meta", "property") .field("meta", def("Identifier")) .field("property", def("Identifier")); def("ParenthesizedExpression") .bases("Expression") .build("expression") .field("expression", def("Expression")); def("ImportSpecifier") .bases("ModuleSpecifier") .build("imported", "local") .field("imported", def("Identifier")); def("ImportDefaultSpecifier") .bases("ModuleSpecifier") .build("local"); def("ImportNamespaceSpecifier") .bases("ModuleSpecifier") .build("local"); def("ExportDefaultDeclaration") .bases("Declaration") .build("declaration") .field("declaration", or(def("Declaration"), def("Expression"))); def("ExportNamedDeclaration") .bases("Declaration") .build("declaration", "specifiers", "source") .field("declaration", or(def("Declaration"), null)) .field("specifiers", [def("ExportSpecifier")], defaults.emptyArray) .field("source", or(def("Literal"), null), defaults["null"]); def("ExportSpecifier") .bases("ModuleSpecifier") .build("local", "exported") .field("exported", def("Identifier")); def("ExportNamespaceSpecifier") .bases("Specifier") .build("exported") .field("exported", def("Identifier")); def("ExportDefaultSpecifier") .bases("Specifier") .build("exported") .field("exported", def("Identifier")); def("ExportAllDeclaration") .bases("Declaration") .build("exported", "source") .field("exported", or(def("Identifier"), null)) .field("source", def("Literal")); def("CommentBlock") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); def("CommentLine") .bases("Comment") .build("value", /*optional:*/ "leading", "trailing"); def("Directive") .bases("Node") .build("value") .field("value", def("DirectiveLiteral")); def("DirectiveLiteral") .bases("Node", "Expression") .build("value") .field("value", String, defaults["use strict"]); def("InterpreterDirective") .bases("Node") .build("value") .field("value", String); def("BlockStatement") .bases("Statement") .build("body") .field("body", [def("Statement")]) .field("directives", [def("Directive")], defaults.emptyArray); def("Program") .bases("Node") .build("body") .field("body", [def("Statement")]) .field("directives", [def("Directive")], defaults.emptyArray) .field("interpreter", or(def("InterpreterDirective"), null), defaults["null"]); // Split Literal def("StringLiteral") .bases("Literal") .build("value") .field("value", String); def("NumericLiteral") .bases("Literal") .build("value") .field("value", Number) .field("raw", or(String, null), defaults["null"]) .field("extra", { rawValue: Number, raw: String }, function getDefault() { return { rawValue: this.value, raw: this.value + "" }; }); def("BigIntLiteral") .bases("Literal") .build("value") // Only String really seems appropriate here, since BigInt values // often exceed the limits of JS numbers. .field("value", or(String, Number)) .field("extra", { rawValue: String, raw: String }, function getDefault() { return { rawValue: String(this.value), raw: this.value + "n" }; }); def("NullLiteral") .bases("Literal") .build() .field("value", null, defaults["null"]); def("BooleanLiteral") .bases("Literal") .build("value") .field("value", Boolean); def("RegExpLiteral") .bases("Literal") .build("pattern", "flags") .field("pattern", String) .field("flags", String) .field("value", RegExp, function () { return new RegExp(this.pattern, this.flags); }); var ObjectExpressionProperty = or(def("Property"), def("ObjectMethod"), def("ObjectProperty"), def("SpreadProperty"), def("SpreadElement")); // Split Property -> ObjectProperty and ObjectMethod def("ObjectExpression") .bases("Expression") .build("properties") .field("properties", [ObjectExpressionProperty]); // ObjectMethod hoist .value properties to own properties def("ObjectMethod") .bases("Node", "Function") .build("kind", "key", "params", "body", "computed") .field("kind", or("method", "get", "set")) .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("params", [def("Pattern")]) .field("body", def("BlockStatement")) .field("computed", Boolean, defaults["false"]) .field("generator", Boolean, defaults["false"]) .field("async", Boolean, defaults["false"]) .field("accessibility", // TypeScript or(def("Literal"), null), defaults["null"]) .field("decorators", or([def("Decorator")], null), defaults["null"]); def("ObjectProperty") .bases("Node") .build("key", "value") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("value", or(def("Expression"), def("Pattern"))) .field("accessibility", // TypeScript or(def("Literal"), null), defaults["null"]) .field("computed", Boolean, defaults["false"]); var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod")); // MethodDefinition -> ClassMethod def("ClassBody") .bases("Declaration") .build("body") .field("body", [ClassBodyElement]); def("ClassMethod") .bases("Declaration", "Function") .build("kind", "key", "params", "body", "computed", "static") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))); def("ClassPrivateMethod") .bases("Declaration", "Function") .build("key", "params", "body", "kind", "computed", "static") .field("key", def("PrivateName")); ["ClassMethod", "ClassPrivateMethod", ].forEach(function (typeName) { def(typeName) .field("kind", or("get", "set", "method", "constructor"), function () { return "method"; }) .field("body", def("BlockStatement")) .field("computed", Boolean, defaults["false"]) .field("static", or(Boolean, null), defaults["null"]) .field("abstract", or(Boolean, null), defaults["null"]) .field("access", or("public", "private", "protected", null), defaults["null"]) .field("accessibility", or("public", "private", "protected", null), defaults["null"]) .field("decorators", or([def("Decorator")], null), defaults["null"]) .field("optional", or(Boolean, null), defaults["null"]); }); def("ClassPrivateProperty") .bases("ClassProperty") .build("key", "value") .field("key", def("PrivateName")) .field("value", or(def("Expression"), null), defaults["null"]); def("PrivateName") .bases("Expression", "Pattern") .build("id") .field("id", def("Identifier")); var ObjectPatternProperty = or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"), def("SpreadProperty"), // Used by Esprima def("ObjectProperty"), // Babel 6 def("RestProperty") // Babel 6 ); // Split into RestProperty and SpreadProperty def("ObjectPattern") .bases("Pattern") .build("properties") .field("properties", [ObjectPatternProperty]) .field("decorators", or([def("Decorator")], null), defaults["null"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("RestProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ForAwaitStatement") .bases("Statement") .build("left", "right", "body") .field("left", or(def("VariableDeclaration"), def("Expression"))) .field("right", def("Expression")) .field("body", def("Statement")); // The callee node of a dynamic import(...) expression. def("Import") .bases("Expression") .build(); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/babel-core.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,366
```javascript "use strict";; /** * Type annotation defs shared between Flow and TypeScript. * These defs could not be defined in ./flow.ts or ./typescript.ts directly * because they use the same name. */ Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; var TypeAnnotation = or(def("TypeAnnotation"), def("TSTypeAnnotation"), null); var TypeParamDecl = or(def("TypeParameterDeclaration"), def("TSTypeParameterDeclaration"), null); def("Identifier") .field("typeAnnotation", TypeAnnotation, defaults["null"]); def("ObjectPattern") .field("typeAnnotation", TypeAnnotation, defaults["null"]); def("Function") .field("returnType", TypeAnnotation, defaults["null"]) .field("typeParameters", TypeParamDecl, defaults["null"]); def("ClassProperty") .build("key", "value", "typeAnnotation", "static") .field("value", or(def("Expression"), null)) .field("static", Boolean, defaults["false"]) .field("typeAnnotation", TypeAnnotation, defaults["null"]); ["ClassDeclaration", "ClassExpression", ].forEach(function (typeName) { def(typeName) .field("typeParameters", TypeParamDecl, defaults["null"]) .field("superTypeParameters", or(def("TypeParameterInstantiation"), def("TSTypeParameterInstantiation"), null), defaults["null"]) .field("implements", or([def("ClassImplements")], [def("TSExpressionWithTypeArguments")]), defaults.emptyArray); }); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/type-annotations.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
433
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); var core_1 = tslib_1.__importDefault(require("./core")); function default_1(fork) { fork.use(core_1.default); var types = fork.use(types_1.default); var Type = types.Type; var def = types.Type.def; var or = Type.or; var shared = fork.use(shared_1.default); var defaults = shared.defaults; // path_to_url // `a?.b` as per path_to_url def("OptionalMemberExpression") .bases("MemberExpression") .build("object", "property", "computed", "optional") .field("optional", Boolean, defaults["true"]); // a?.b() def("OptionalCallExpression") .bases("CallExpression") .build("callee", "arguments", "optional") .field("optional", Boolean, defaults["true"]); // path_to_url // `a ?? b` as per path_to_url var LogicalOperator = or("||", "&&", "??"); def("LogicalExpression") .field("operator", LogicalOperator); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/es-proposals.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
306
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var es7_1 = tslib_1.__importDefault(require("./es7")); var type_annotations_1 = tslib_1.__importDefault(require("./type-annotations")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { fork.use(es7_1.default); fork.use(type_annotations_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; // Base types def("Flow").bases("Node"); def("FlowType").bases("Flow"); // Type annotations def("AnyTypeAnnotation") .bases("FlowType") .build(); def("EmptyTypeAnnotation") .bases("FlowType") .build(); def("MixedTypeAnnotation") .bases("FlowType") .build(); def("VoidTypeAnnotation") .bases("FlowType") .build(); def("NumberTypeAnnotation") .bases("FlowType") .build(); def("NumberLiteralTypeAnnotation") .bases("FlowType") .build("value", "raw") .field("value", Number) .field("raw", String); // Babylon 6 differs in AST from Flow // same as NumberLiteralTypeAnnotation def("NumericLiteralTypeAnnotation") .bases("FlowType") .build("value", "raw") .field("value", Number) .field("raw", String); def("StringTypeAnnotation") .bases("FlowType") .build(); def("StringLiteralTypeAnnotation") .bases("FlowType") .build("value", "raw") .field("value", String) .field("raw", String); def("BooleanTypeAnnotation") .bases("FlowType") .build(); def("BooleanLiteralTypeAnnotation") .bases("FlowType") .build("value", "raw") .field("value", Boolean) .field("raw", String); def("TypeAnnotation") .bases("Node") .build("typeAnnotation") .field("typeAnnotation", def("FlowType")); def("NullableTypeAnnotation") .bases("FlowType") .build("typeAnnotation") .field("typeAnnotation", def("FlowType")); def("NullLiteralTypeAnnotation") .bases("FlowType") .build(); def("NullTypeAnnotation") .bases("FlowType") .build(); def("ThisTypeAnnotation") .bases("FlowType") .build(); def("ExistsTypeAnnotation") .bases("FlowType") .build(); def("ExistentialTypeParam") .bases("FlowType") .build(); def("FunctionTypeAnnotation") .bases("FlowType") .build("params", "returnType", "rest", "typeParameters") .field("params", [def("FunctionTypeParam")]) .field("returnType", def("FlowType")) .field("rest", or(def("FunctionTypeParam"), null)) .field("typeParameters", or(def("TypeParameterDeclaration"), null)); def("FunctionTypeParam") .bases("Node") .build("name", "typeAnnotation", "optional") .field("name", def("Identifier")) .field("typeAnnotation", def("FlowType")) .field("optional", Boolean); def("ArrayTypeAnnotation") .bases("FlowType") .build("elementType") .field("elementType", def("FlowType")); def("ObjectTypeAnnotation") .bases("FlowType") .build("properties", "indexers", "callProperties") .field("properties", [ or(def("ObjectTypeProperty"), def("ObjectTypeSpreadProperty")) ]) .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray) .field("callProperties", [def("ObjectTypeCallProperty")], defaults.emptyArray) .field("inexact", or(Boolean, void 0), defaults["undefined"]) .field("exact", Boolean, defaults["false"]) .field("internalSlots", [def("ObjectTypeInternalSlot")], defaults.emptyArray); def("Variance") .bases("Node") .build("kind") .field("kind", or("plus", "minus")); var LegacyVariance = or(def("Variance"), "plus", "minus", null); def("ObjectTypeProperty") .bases("Node") .build("key", "value", "optional") .field("key", or(def("Literal"), def("Identifier"))) .field("value", def("FlowType")) .field("optional", Boolean) .field("variance", LegacyVariance, defaults["null"]); def("ObjectTypeIndexer") .bases("Node") .build("id", "key", "value") .field("id", def("Identifier")) .field("key", def("FlowType")) .field("value", def("FlowType")) .field("variance", LegacyVariance, defaults["null"]); def("ObjectTypeCallProperty") .bases("Node") .build("value") .field("value", def("FunctionTypeAnnotation")) .field("static", Boolean, defaults["false"]); def("QualifiedTypeIdentifier") .bases("Node") .build("qualification", "id") .field("qualification", or(def("Identifier"), def("QualifiedTypeIdentifier"))) .field("id", def("Identifier")); def("GenericTypeAnnotation") .bases("FlowType") .build("id", "typeParameters") .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier"))) .field("typeParameters", or(def("TypeParameterInstantiation"), null)); def("MemberTypeAnnotation") .bases("FlowType") .build("object", "property") .field("object", def("Identifier")) .field("property", or(def("MemberTypeAnnotation"), def("GenericTypeAnnotation"))); def("UnionTypeAnnotation") .bases("FlowType") .build("types") .field("types", [def("FlowType")]); def("IntersectionTypeAnnotation") .bases("FlowType") .build("types") .field("types", [def("FlowType")]); def("TypeofTypeAnnotation") .bases("FlowType") .build("argument") .field("argument", def("FlowType")); def("ObjectTypeSpreadProperty") .bases("Node") .build("argument") .field("argument", def("FlowType")); def("ObjectTypeInternalSlot") .bases("Node") .build("id", "value", "optional", "static", "method") .field("id", def("Identifier")) .field("value", def("FlowType")) .field("optional", Boolean) .field("static", Boolean) .field("method", Boolean); def("TypeParameterDeclaration") .bases("Node") .build("params") .field("params", [def("TypeParameter")]); def("TypeParameterInstantiation") .bases("Node") .build("params") .field("params", [def("FlowType")]); def("TypeParameter") .bases("FlowType") .build("name", "variance", "bound") .field("name", String) .field("variance", LegacyVariance, defaults["null"]) .field("bound", or(def("TypeAnnotation"), null), defaults["null"]); def("ClassProperty") .field("variance", LegacyVariance, defaults["null"]); def("ClassImplements") .bases("Node") .build("id") .field("id", def("Identifier")) .field("superClass", or(def("Expression"), null), defaults["null"]) .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); def("InterfaceTypeAnnotation") .bases("FlowType") .build("body", "extends") .field("body", def("ObjectTypeAnnotation")) .field("extends", or([def("InterfaceExtends")], null), defaults["null"]); def("InterfaceDeclaration") .bases("Declaration") .build("id", "body", "extends") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterDeclaration"), null), defaults["null"]) .field("body", def("ObjectTypeAnnotation")) .field("extends", [def("InterfaceExtends")]); def("DeclareInterface") .bases("InterfaceDeclaration") .build("id", "body", "extends"); def("InterfaceExtends") .bases("Node") .build("id") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterInstantiation"), null), defaults["null"]); def("TypeAlias") .bases("Declaration") .build("id", "typeParameters", "right") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterDeclaration"), null)) .field("right", def("FlowType")); def("OpaqueType") .bases("Declaration") .build("id", "typeParameters", "impltype", "supertype") .field("id", def("Identifier")) .field("typeParameters", or(def("TypeParameterDeclaration"), null)) .field("impltype", def("FlowType")) .field("supertype", def("FlowType")); def("DeclareTypeAlias") .bases("TypeAlias") .build("id", "typeParameters", "right"); def("DeclareOpaqueType") .bases("TypeAlias") .build("id", "typeParameters", "supertype"); def("TypeCastExpression") .bases("Expression") .build("expression", "typeAnnotation") .field("expression", def("Expression")) .field("typeAnnotation", def("TypeAnnotation")); def("TupleTypeAnnotation") .bases("FlowType") .build("types") .field("types", [def("FlowType")]); def("DeclareVariable") .bases("Statement") .build("id") .field("id", def("Identifier")); def("DeclareFunction") .bases("Statement") .build("id") .field("id", def("Identifier")); def("DeclareClass") .bases("InterfaceDeclaration") .build("id"); def("DeclareModule") .bases("Statement") .build("id", "body") .field("id", or(def("Identifier"), def("Literal"))) .field("body", def("BlockStatement")); def("DeclareModuleExports") .bases("Statement") .build("typeAnnotation") .field("typeAnnotation", def("TypeAnnotation")); def("DeclareExportDeclaration") .bases("Declaration") .build("default", "declaration", "specifiers", "source") .field("default", Boolean) .field("declaration", or(def("DeclareVariable"), def("DeclareFunction"), def("DeclareClass"), def("FlowType"), // Implies default. null)) .field("specifiers", [or(def("ExportSpecifier"), def("ExportBatchSpecifier"))], defaults.emptyArray) .field("source", or(def("Literal"), null), defaults["null"]); def("DeclareExportAllDeclaration") .bases("Declaration") .build("source") .field("source", or(def("Literal"), null), defaults["null"]); def("FlowPredicate").bases("Flow"); def("InferredPredicate") .bases("FlowPredicate") .build(); def("DeclaredPredicate") .bases("FlowPredicate") .build("value") .field("value", def("Expression")); def("CallExpression") .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); def("NewExpression") .field("typeArguments", or(null, def("TypeParameterInstantiation")), defaults["null"]); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/flow.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,693
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var es7_1 = tslib_1.__importDefault(require("./es7")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { fork.use(es7_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("JSXAttribute") .bases("Node") .build("name", "value") .field("name", or(def("JSXIdentifier"), def("JSXNamespacedName"))) .field("value", or(def("Literal"), // attr="value" def("JSXExpressionContainer"), // attr={value} null // attr= or just attr ), defaults["null"]); def("JSXIdentifier") .bases("Identifier") .build("name") .field("name", String); def("JSXNamespacedName") .bases("Node") .build("namespace", "name") .field("namespace", def("JSXIdentifier")) .field("name", def("JSXIdentifier")); def("JSXMemberExpression") .bases("MemberExpression") .build("object", "property") .field("object", or(def("JSXIdentifier"), def("JSXMemberExpression"))) .field("property", def("JSXIdentifier")) .field("computed", Boolean, defaults.false); var JSXElementName = or(def("JSXIdentifier"), def("JSXNamespacedName"), def("JSXMemberExpression")); def("JSXSpreadAttribute") .bases("Node") .build("argument") .field("argument", def("Expression")); var JSXAttributes = [or(def("JSXAttribute"), def("JSXSpreadAttribute"))]; def("JSXExpressionContainer") .bases("Expression") .build("expression") .field("expression", def("Expression")); def("JSXElement") .bases("Expression") .build("openingElement", "closingElement", "children") .field("openingElement", def("JSXOpeningElement")) .field("closingElement", or(def("JSXClosingElement"), null), defaults["null"]) .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead. )], defaults.emptyArray) .field("name", JSXElementName, function () { // Little-known fact: the `this` object inside a default function // is none other than the partially-built object itself, and any // fields initialized directly from builder function arguments // (like openingElement, closingElement, and children) are // guaranteed to be available. return this.openingElement.name; }, true) // hidden from traversal .field("selfClosing", Boolean, function () { return this.openingElement.selfClosing; }, true) // hidden from traversal .field("attributes", JSXAttributes, function () { return this.openingElement.attributes; }, true); // hidden from traversal def("JSXOpeningElement") .bases("Node") // TODO Does this make sense? Can't really be an JSXElement. .build("name", "attributes", "selfClosing") .field("name", JSXElementName) .field("attributes", JSXAttributes, defaults.emptyArray) .field("selfClosing", Boolean, defaults["false"]); def("JSXClosingElement") .bases("Node") // TODO Same concern. .build("name") .field("name", JSXElementName); def("JSXFragment") .bases("Expression") .build("openingElement", "closingElement", "children") .field("openingElement", def("JSXOpeningFragment")) .field("closingElement", def("JSXClosingFragment")) .field("children", [or(def("JSXElement"), def("JSXExpressionContainer"), def("JSXFragment"), def("JSXText"), def("Literal") // TODO Esprima should return JSXText instead. )], defaults.emptyArray); def("JSXOpeningFragment") .bases("Node") // TODO Same concern. .build(); def("JSXClosingFragment") .bases("Node") // TODO Same concern. .build(); def("JSXText") .bases("Literal") .build("value") .field("value", String); def("JSXEmptyExpression").bases("Expression").build(); // This PR has caused many people issues, but supporting it seems like a // good idea anyway: path_to_url def("JSXSpreadChild") .bases("Expression") .build("expression") .field("expression", def("Expression")); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/jsx.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,119
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var es6_1 = tslib_1.__importDefault(require("./es6")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { fork.use(es6_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("Function") .field("async", Boolean, defaults["false"]); def("SpreadProperty") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ObjectExpression") .field("properties", [or(def("Property"), def("SpreadProperty"), def("SpreadElement"))]); def("SpreadPropertyPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("ObjectPattern") .field("properties", [or(def("Property"), def("PropertyPattern"), def("SpreadPropertyPattern"))]); def("AwaitExpression") .bases("Expression") .build("argument", "all") .field("argument", or(def("Expression"), null)) .field("all", Boolean, defaults["false"]); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/es7.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
324
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var babel_core_1 = tslib_1.__importDefault(require("./babel-core")); var type_annotations_1 = tslib_1.__importDefault(require("./type-annotations")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { // Since TypeScript is parsed by Babylon, include the core Babylon types // but omit the Flow-related types. fork.use(babel_core_1.default); fork.use(type_annotations_1.default); var types = fork.use(types_1.default); var n = types.namedTypes; var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; var StringLiteral = types.Type.from(function (value, deep) { if (n.StringLiteral && n.StringLiteral.check(value, deep)) { return true; } if (n.Literal && n.Literal.check(value, deep) && typeof value.value === "string") { return true; } return false; }, "StringLiteral"); def("TSType") .bases("Node"); var TSEntityName = or(def("Identifier"), def("TSQualifiedName")); def("TSTypeReference") .bases("TSType", "TSHasOptionalTypeParameterInstantiation") .build("typeName", "typeParameters") .field("typeName", TSEntityName); // An abstract (non-buildable) base type that provide a commonly-needed // optional .typeParameters field. def("TSHasOptionalTypeParameterInstantiation") .field("typeParameters", or(def("TSTypeParameterInstantiation"), null), defaults["null"]); // An abstract (non-buildable) base type that provide a commonly-needed // optional .typeParameters field. def("TSHasOptionalTypeParameters") .field("typeParameters", or(def("TSTypeParameterDeclaration"), null, void 0), defaults["null"]); // An abstract (non-buildable) base type that provide a commonly-needed // optional .typeAnnotation field. def("TSHasOptionalTypeAnnotation") .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]); def("TSQualifiedName") .bases("Node") .build("left", "right") .field("left", TSEntityName) .field("right", TSEntityName); def("TSAsExpression") .bases("Expression", "Pattern") .build("expression", "typeAnnotation") .field("expression", def("Expression")) .field("typeAnnotation", def("TSType")) .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); def("TSNonNullExpression") .bases("Expression", "Pattern") .build("expression") .field("expression", def("Expression")); [ "TSAnyKeyword", "TSBigIntKeyword", "TSBooleanKeyword", "TSNeverKeyword", "TSNullKeyword", "TSNumberKeyword", "TSObjectKeyword", "TSStringKeyword", "TSSymbolKeyword", "TSUndefinedKeyword", "TSUnknownKeyword", "TSVoidKeyword", "TSThisType", ].forEach(function (keywordType) { def(keywordType) .bases("TSType") .build(); }); def("TSArrayType") .bases("TSType") .build("elementType") .field("elementType", def("TSType")); def("TSLiteralType") .bases("TSType") .build("literal") .field("literal", or(def("NumericLiteral"), def("StringLiteral"), def("BooleanLiteral"), def("TemplateLiteral"), def("UnaryExpression"))); ["TSUnionType", "TSIntersectionType", ].forEach(function (typeName) { def(typeName) .bases("TSType") .build("types") .field("types", [def("TSType")]); }); def("TSConditionalType") .bases("TSType") .build("checkType", "extendsType", "trueType", "falseType") .field("checkType", def("TSType")) .field("extendsType", def("TSType")) .field("trueType", def("TSType")) .field("falseType", def("TSType")); def("TSInferType") .bases("TSType") .build("typeParameter") .field("typeParameter", def("TSTypeParameter")); def("TSParenthesizedType") .bases("TSType") .build("typeAnnotation") .field("typeAnnotation", def("TSType")); var ParametersType = [or(def("Identifier"), def("RestElement"), def("ArrayPattern"), def("ObjectPattern"))]; ["TSFunctionType", "TSConstructorType", ].forEach(function (typeName) { def(typeName) .bases("TSType", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") .build("parameters") .field("parameters", ParametersType); }); def("TSDeclareFunction") .bases("Declaration", "TSHasOptionalTypeParameters") .build("id", "params", "returnType") .field("declare", Boolean, defaults["false"]) .field("async", Boolean, defaults["false"]) .field("generator", Boolean, defaults["false"]) .field("id", or(def("Identifier"), null), defaults["null"]) .field("params", [def("Pattern")]) // tSFunctionTypeAnnotationCommon .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used? null), defaults["null"]); def("TSDeclareMethod") .bases("Declaration", "TSHasOptionalTypeParameters") .build("key", "params", "returnType") .field("async", Boolean, defaults["false"]) .field("generator", Boolean, defaults["false"]) .field("params", [def("Pattern")]) // classMethodOrPropertyCommon .field("abstract", Boolean, defaults["false"]) .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]) .field("static", Boolean, defaults["false"]) .field("computed", Boolean, defaults["false"]) .field("optional", Boolean, defaults["false"]) .field("key", or(def("Identifier"), def("StringLiteral"), def("NumericLiteral"), // Only allowed if .computed is true. def("Expression"))) // classMethodOrDeclareMethodCommon .field("kind", or("get", "set", "method", "constructor"), function getDefault() { return "method"; }) .field("access", // Not "accessibility"? or("public", "private", "protected", void 0), defaults["undefined"]) .field("decorators", or([def("Decorator")], null), defaults["null"]) // tSFunctionTypeAnnotationCommon .field("returnType", or(def("TSTypeAnnotation"), def("Noop"), // Still used? null), defaults["null"]); def("TSMappedType") .bases("TSType") .build("typeParameter", "typeAnnotation") .field("readonly", or(Boolean, "+", "-"), defaults["false"]) .field("typeParameter", def("TSTypeParameter")) .field("optional", or(Boolean, "+", "-"), defaults["false"]) .field("typeAnnotation", or(def("TSType"), null), defaults["null"]); def("TSTupleType") .bases("TSType") .build("elementTypes") .field("elementTypes", [or(def("TSType"), def("TSNamedTupleMember"))]); def("TSNamedTupleMember") .bases("TSType") .build("label", "elementType", "optional") .field("label", def("Identifier")) .field("optional", Boolean, defaults["false"]) .field("elementType", def("TSType")); def("TSRestType") .bases("TSType") .build("typeAnnotation") .field("typeAnnotation", def("TSType")); def("TSOptionalType") .bases("TSType") .build("typeAnnotation") .field("typeAnnotation", def("TSType")); def("TSIndexedAccessType") .bases("TSType") .build("objectType", "indexType") .field("objectType", def("TSType")) .field("indexType", def("TSType")); def("TSTypeOperator") .bases("TSType") .build("operator") .field("operator", String) .field("typeAnnotation", def("TSType")); def("TSTypeAnnotation") .bases("Node") .build("typeAnnotation") .field("typeAnnotation", or(def("TSType"), def("TSTypeAnnotation"))); def("TSIndexSignature") .bases("Declaration", "TSHasOptionalTypeAnnotation") .build("parameters", "typeAnnotation") .field("parameters", [def("Identifier")]) // Length === 1 .field("readonly", Boolean, defaults["false"]); def("TSPropertySignature") .bases("Declaration", "TSHasOptionalTypeAnnotation") .build("key", "typeAnnotation", "optional") .field("key", def("Expression")) .field("computed", Boolean, defaults["false"]) .field("readonly", Boolean, defaults["false"]) .field("optional", Boolean, defaults["false"]) .field("initializer", or(def("Expression"), null), defaults["null"]); def("TSMethodSignature") .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") .build("key", "parameters", "typeAnnotation") .field("key", def("Expression")) .field("computed", Boolean, defaults["false"]) .field("optional", Boolean, defaults["false"]) .field("parameters", ParametersType); def("TSTypePredicate") .bases("TSTypeAnnotation", "TSType") .build("parameterName", "typeAnnotation", "asserts") .field("parameterName", or(def("Identifier"), def("TSThisType"))) .field("typeAnnotation", or(def("TSTypeAnnotation"), null), defaults["null"]) .field("asserts", Boolean, defaults["false"]); ["TSCallSignatureDeclaration", "TSConstructSignatureDeclaration", ].forEach(function (typeName) { def(typeName) .bases("Declaration", "TSHasOptionalTypeParameters", "TSHasOptionalTypeAnnotation") .build("parameters", "typeAnnotation") .field("parameters", ParametersType); }); def("TSEnumMember") .bases("Node") .build("id", "initializer") .field("id", or(def("Identifier"), StringLiteral)) .field("initializer", or(def("Expression"), null), defaults["null"]); def("TSTypeQuery") .bases("TSType") .build("exprName") .field("exprName", or(TSEntityName, def("TSImportType"))); // Inferred from Babylon's tsParseTypeMember method. var TSTypeMember = or(def("TSCallSignatureDeclaration"), def("TSConstructSignatureDeclaration"), def("TSIndexSignature"), def("TSMethodSignature"), def("TSPropertySignature")); def("TSTypeLiteral") .bases("TSType") .build("members") .field("members", [TSTypeMember]); def("TSTypeParameter") .bases("Identifier") .build("name", "constraint", "default") .field("name", String) .field("constraint", or(def("TSType"), void 0), defaults["undefined"]) .field("default", or(def("TSType"), void 0), defaults["undefined"]); def("TSTypeAssertion") .bases("Expression", "Pattern") .build("typeAnnotation", "expression") .field("typeAnnotation", def("TSType")) .field("expression", def("Expression")) .field("extra", or({ parenthesized: Boolean }, null), defaults["null"]); def("TSTypeParameterDeclaration") .bases("Declaration") .build("params") .field("params", [def("TSTypeParameter")]); def("TSTypeParameterInstantiation") .bases("Node") .build("params") .field("params", [def("TSType")]); def("TSEnumDeclaration") .bases("Declaration") .build("id", "members") .field("id", def("Identifier")) .field("const", Boolean, defaults["false"]) .field("declare", Boolean, defaults["false"]) .field("members", [def("TSEnumMember")]) .field("initializer", or(def("Expression"), null), defaults["null"]); def("TSTypeAliasDeclaration") .bases("Declaration", "TSHasOptionalTypeParameters") .build("id", "typeAnnotation") .field("id", def("Identifier")) .field("declare", Boolean, defaults["false"]) .field("typeAnnotation", def("TSType")); def("TSModuleBlock") .bases("Node") .build("body") .field("body", [def("Statement")]); def("TSModuleDeclaration") .bases("Declaration") .build("id", "body") .field("id", or(StringLiteral, TSEntityName)) .field("declare", Boolean, defaults["false"]) .field("global", Boolean, defaults["false"]) .field("body", or(def("TSModuleBlock"), def("TSModuleDeclaration"), null), defaults["null"]); def("TSImportType") .bases("TSType", "TSHasOptionalTypeParameterInstantiation") .build("argument", "qualifier", "typeParameters") .field("argument", StringLiteral) .field("qualifier", or(TSEntityName, void 0), defaults["undefined"]); def("TSImportEqualsDeclaration") .bases("Declaration") .build("id", "moduleReference") .field("id", def("Identifier")) .field("isExport", Boolean, defaults["false"]) .field("moduleReference", or(TSEntityName, def("TSExternalModuleReference"))); def("TSExternalModuleReference") .bases("Declaration") .build("expression") .field("expression", StringLiteral); def("TSExportAssignment") .bases("Statement") .build("expression") .field("expression", def("Expression")); def("TSNamespaceExportDeclaration") .bases("Declaration") .build("id") .field("id", def("Identifier")); def("TSInterfaceBody") .bases("Node") .build("body") .field("body", [TSTypeMember]); def("TSExpressionWithTypeArguments") .bases("TSType", "TSHasOptionalTypeParameterInstantiation") .build("expression", "typeParameters") .field("expression", TSEntityName); def("TSInterfaceDeclaration") .bases("Declaration", "TSHasOptionalTypeParameters") .build("id", "body") .field("id", TSEntityName) .field("declare", Boolean, defaults["false"]) .field("extends", or([def("TSExpressionWithTypeArguments")], null), defaults["null"]) .field("body", def("TSInterfaceBody")); def("TSParameterProperty") .bases("Pattern") .build("parameter") .field("accessibility", or("public", "private", "protected", void 0), defaults["undefined"]) .field("readonly", Boolean, defaults["false"]) .field("parameter", or(def("Identifier"), def("AssignmentPattern"))); def("ClassProperty") .field("access", // Not "accessibility"? or("public", "private", "protected", void 0), defaults["undefined"]); // Defined already in es6 and babel-core. def("ClassBody") .field("body", [or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty"), def("ClassPrivateProperty"), def("ClassMethod"), def("ClassPrivateMethod"), // Just need to add these types: def("TSDeclareMethod"), TSTypeMember)]); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/typescript.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,715
```javascript "use strict";; Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var core_1 = tslib_1.__importDefault(require("./core")); var types_1 = tslib_1.__importDefault(require("../lib/types")); var shared_1 = tslib_1.__importDefault(require("../lib/shared")); function default_1(fork) { fork.use(core_1.default); var types = fork.use(types_1.default); var def = types.Type.def; var or = types.Type.or; var defaults = fork.use(shared_1.default).defaults; def("Function") .field("generator", Boolean, defaults["false"]) .field("expression", Boolean, defaults["false"]) .field("defaults", [or(def("Expression"), null)], defaults.emptyArray) // TODO This could be represented as a RestElement in .params. .field("rest", or(def("Identifier"), null), defaults["null"]); // The ESTree way of representing a ...rest parameter. def("RestElement") .bases("Pattern") .build("argument") .field("argument", def("Pattern")) .field("typeAnnotation", // for Babylon. Flow parser puts it on the identifier or(def("TypeAnnotation"), def("TSTypeAnnotation"), null), defaults["null"]); def("SpreadElementPattern") .bases("Pattern") .build("argument") .field("argument", def("Pattern")); def("FunctionDeclaration") .build("id", "params", "body", "generator", "expression"); def("FunctionExpression") .build("id", "params", "body", "generator", "expression"); // The Parser API calls this ArrowExpression, but Esprima and all other // actual parsers use ArrowFunctionExpression. def("ArrowFunctionExpression") .bases("Function", "Expression") .build("params", "body", "expression") // The forced null value here is compatible with the overridden // definition of the "id" field in the Function interface. .field("id", null, defaults["null"]) // Arrow function bodies are allowed to be expressions. .field("body", or(def("BlockStatement"), def("Expression"))) // The current spec forbids arrow generators, so I have taken the // liberty of enforcing that. TODO Report this. .field("generator", false, defaults["false"]); def("ForOfStatement") .bases("Statement") .build("left", "right", "body") .field("left", or(def("VariableDeclaration"), def("Pattern"))) .field("right", def("Expression")) .field("body", def("Statement")); def("YieldExpression") .bases("Expression") .build("argument", "delegate") .field("argument", or(def("Expression"), null)) .field("delegate", Boolean, defaults["false"]); def("GeneratorExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionExpression") .bases("Expression") .build("body", "blocks", "filter") .field("body", def("Expression")) .field("blocks", [def("ComprehensionBlock")]) .field("filter", or(def("Expression"), null)); def("ComprehensionBlock") .bases("Node") .build("left", "right", "each") .field("left", def("Pattern")) .field("right", def("Expression")) .field("each", Boolean); def("Property") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("value", or(def("Expression"), def("Pattern"))) .field("method", Boolean, defaults["false"]) .field("shorthand", Boolean, defaults["false"]) .field("computed", Boolean, defaults["false"]); def("ObjectProperty") .field("shorthand", Boolean, defaults["false"]); def("PropertyPattern") .bases("Pattern") .build("key", "pattern") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("pattern", def("Pattern")) .field("computed", Boolean, defaults["false"]); def("ObjectPattern") .bases("Pattern") .build("properties") .field("properties", [or(def("PropertyPattern"), def("Property"))]); def("ArrayPattern") .bases("Pattern") .build("elements") .field("elements", [or(def("Pattern"), null)]); def("MethodDefinition") .bases("Declaration") .build("kind", "key", "value", "static") .field("kind", or("constructor", "method", "get", "set")) .field("key", def("Expression")) .field("value", def("Function")) .field("computed", Boolean, defaults["false"]) .field("static", Boolean, defaults["false"]); def("SpreadElement") .bases("Node") .build("argument") .field("argument", def("Expression")); def("ArrayExpression") .field("elements", [or(def("Expression"), def("SpreadElement"), def("RestElement"), null)]); def("NewExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); def("CallExpression") .field("arguments", [or(def("Expression"), def("SpreadElement"))]); // Note: this node type is *not* an AssignmentExpression with a Pattern on // the left-hand side! The existing AssignmentExpression type already // supports destructuring assignments. AssignmentPattern nodes may appear // wherever a Pattern is allowed, and the right-hand side represents a // default value to be destructured against the left-hand side, if no // value is otherwise provided. For example: default parameter values. def("AssignmentPattern") .bases("Pattern") .build("left", "right") .field("left", def("Pattern")) .field("right", def("Expression")); var ClassBodyElement = or(def("MethodDefinition"), def("VariableDeclarator"), def("ClassPropertyDefinition"), def("ClassProperty")); def("ClassProperty") .bases("Declaration") .build("key") .field("key", or(def("Literal"), def("Identifier"), def("Expression"))) .field("computed", Boolean, defaults["false"]); def("ClassPropertyDefinition") // static property .bases("Declaration") .build("definition") // Yes, Virginia, circular definitions are permitted. .field("definition", ClassBodyElement); def("ClassBody") .bases("Declaration") .build("body") .field("body", [ClassBodyElement]); def("ClassDeclaration") .bases("Declaration") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null)) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]); def("ClassExpression") .bases("Expression") .build("id", "body", "superClass") .field("id", or(def("Identifier"), null), defaults["null"]) .field("body", def("ClassBody")) .field("superClass", or(def("Expression"), null), defaults["null"]); // Specifier and ModuleSpecifier are abstract non-standard types // introduced for definitional convenience. def("Specifier").bases("Node"); // This supertype is shared/abused by both def/babel.js and // def/esprima.js. In the future, it will be possible to load only one set // of definitions appropriate for a given parser, but until then we must // rely on default functions to reconcile the conflicting AST formats. def("ModuleSpecifier") .bases("Specifier") // This local field is used by Babel/Acorn. It should not technically // be optional in the Babel/Acorn AST format, but it must be optional // in the Esprima AST format. .field("local", or(def("Identifier"), null), defaults["null"]) // The id and name fields are used by Esprima. The id field should not // technically be optional in the Esprima AST format, but it must be // optional in the Babel/Acorn AST format. .field("id", or(def("Identifier"), null), defaults["null"]) .field("name", or(def("Identifier"), null), defaults["null"]); // Like ModuleSpecifier, except type:"ImportSpecifier" and buildable. // import {<id [as name]>} from ...; def("ImportSpecifier") .bases("ModuleSpecifier") .build("id", "name"); // import <* as id> from ...; def("ImportNamespaceSpecifier") .bases("ModuleSpecifier") .build("id"); // import <id> from ...; def("ImportDefaultSpecifier") .bases("ModuleSpecifier") .build("id"); def("ImportDeclaration") .bases("Declaration") .build("specifiers", "source", "importKind") .field("specifiers", [or(def("ImportSpecifier"), def("ImportNamespaceSpecifier"), def("ImportDefaultSpecifier"))], defaults.emptyArray) .field("source", def("Literal")) .field("importKind", or("value", "type"), function () { return "value"; }); def("TaggedTemplateExpression") .bases("Expression") .build("tag", "quasi") .field("tag", def("Expression")) .field("quasi", def("TemplateLiteral")); def("TemplateLiteral") .bases("Expression") .build("quasis", "expressions") .field("quasis", [def("TemplateElement")]) .field("expressions", [def("Expression")]); def("TemplateElement") .bases("Node") .build("value", "tail") .field("value", { "cooked": String, "raw": String }) .field("tail", Boolean); } exports.default = default_1; module.exports = exports["default"]; ```
/content/code_sandbox/node_modules/degenerator/node_modules/ast-types/def/es6.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,274
```javascript "use strict"; const path_1 = require("path"); /** * File URI to Path function. * * @param {String} uri * @return {String} path * @api public */ function fileUriToPath(uri) { if (typeof uri !== 'string' || uri.length <= 7 || uri.substring(0, 7) !== 'file://') { throw new TypeError('must pass in a file:// URI to convert to a file path'); } const rest = decodeURI(uri.substring(7)); const firstSlash = rest.indexOf('/'); let host = rest.substring(0, firstSlash); let path = rest.substring(firstSlash + 1); // 2. Scheme Definition // As a special case, <host> can be the string "localhost" or the empty // string; this is interpreted as "the machine from which the URL is // being interpreted". if (host === 'localhost') { host = ''; } if (host) { host = path_1.sep + path_1.sep + host; } // 3.2 Drives, drive letters, mount points, file system root // Drive letters are mapped into the top of a file URI in various ways, // depending on the implementation; some applications substitute // vertical bar ("|") for the colon after the drive letter, yielding // "file:///c|/tmp/test.txt". In some cases, the colon is left // unchanged, as in "file:///c:/tmp/test.txt". In other cases, the // colon is simply omitted, as in "file:///c/tmp/test.txt". path = path.replace(/^(.+)\|/, '$1:'); // for Windows, we need to invert the path separators from what a URI uses if (path_1.sep === '\\') { path = path.replace(/\//g, '\\'); } if (/^.+:/.test(path)) { // has Windows drive at beginning of path } else { // unix path path = path_1.sep + path; } return host + path; } module.exports = fileUriToPath; //# sourceMappingURL=index.js.map ```
/content/code_sandbox/node_modules/file-uri-to-path/dist/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
481
```javascript 'use strict'; var bind = require('function-bind'); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); ```
/content/code_sandbox/node_modules/has/src/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
24
```javascript 'use strict'; var test = require('tape'); var has = require('../'); test('has', function (t) { t.equal(has({}, 'hasOwnProperty'), false, 'object literal does not have own property "hasOwnProperty"'); t.equal(has(Object.prototype, 'hasOwnProperty'), true, 'Object.prototype has own property "hasOwnProperty"'); t.end(); }); ```
/content/code_sandbox/node_modules/has/test/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
79
```yaml parser: typescript printWidth: 120 tabWidth: 2 singleQuote: true trailingComma: none ```
/content/code_sandbox/node_modules/smart-buffer/.prettierrc.yaml
yaml
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
29
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const buffer_1 = require("buffer"); /** * Error strings */ const ERRORS = { INVALID_ENCODING: 'Invalid encoding provided. Please specify a valid encoding the internal Node.js Buffer supports.', INVALID_SMARTBUFFER_SIZE: 'Invalid size provided. Size must be a valid integer greater than zero.', INVALID_SMARTBUFFER_BUFFER: 'Invalid Buffer provided in SmartBufferOptions.', INVALID_SMARTBUFFER_OBJECT: 'Invalid SmartBufferOptions object supplied to SmartBuffer constructor or factory methods.', INVALID_OFFSET: 'An invalid offset value was provided.', INVALID_OFFSET_NON_NUMBER: 'An invalid offset value was provided. A numeric value is required.', INVALID_LENGTH: 'An invalid length value was provided.', INVALID_LENGTH_NON_NUMBER: 'An invalid length value was provived. A numeric value is required.', INVALID_TARGET_OFFSET: 'Target offset is beyond the bounds of the internal SmartBuffer data.', INVALID_TARGET_LENGTH: 'Specified length value moves cursor beyong the bounds of the internal SmartBuffer data.', INVALID_READ_BEYOND_BOUNDS: 'Attempted to read beyond the bounds of the managed data.', INVALID_WRITE_BEYOND_BOUNDS: 'Attempted to write beyond the bounds of the managed data.' }; exports.ERRORS = ERRORS; /** * Checks if a given encoding is a valid Buffer encoding. (Throws an exception if check fails) * * @param { String } encoding The encoding string to check. */ function checkEncoding(encoding) { if (!buffer_1.Buffer.isEncoding(encoding)) { throw new Error(ERRORS.INVALID_ENCODING); } } exports.checkEncoding = checkEncoding; /** * Checks if a given number is a finite integer. (Throws an exception if check fails) * * @param { Number } value The number value to check. */ function isFiniteInteger(value) { return typeof value === 'number' && isFinite(value) && isInteger(value); } exports.isFiniteInteger = isFiniteInteger; /** * Checks if an offset/length value is valid. (Throws an exception if check fails) * * @param value The value to check. * @param offset True if checking an offset, false if checking a length. */ function checkOffsetOrLengthValue(value, offset) { if (typeof value === 'number') { // Check for non finite/non integers if (!isFiniteInteger(value) || value < 0) { throw new Error(offset ? ERRORS.INVALID_OFFSET : ERRORS.INVALID_LENGTH); } } else { throw new Error(offset ? ERRORS.INVALID_OFFSET_NON_NUMBER : ERRORS.INVALID_LENGTH_NON_NUMBER); } } /** * Checks if a length value is valid. (Throws an exception if check fails) * * @param { Number } length The value to check. */ function checkLengthValue(length) { checkOffsetOrLengthValue(length, false); } exports.checkLengthValue = checkLengthValue; /** * Checks if a offset value is valid. (Throws an exception if check fails) * * @param { Number } offset The value to check. */ function checkOffsetValue(offset) { checkOffsetOrLengthValue(offset, true); } exports.checkOffsetValue = checkOffsetValue; /** * Checks if a target offset value is out of bounds. (Throws an exception if check fails) * * @param { Number } offset The offset value to check. * @param { SmartBuffer } buff The SmartBuffer instance to check against. */ function checkTargetOffset(offset, buff) { if (offset < 0 || offset > buff.length) { throw new Error(ERRORS.INVALID_TARGET_OFFSET); } } exports.checkTargetOffset = checkTargetOffset; /** * Determines whether a given number is a integer. * @param value The number to check. */ function isInteger(value) { return typeof value === 'number' && isFinite(value) && Math.floor(value) === value; } /** * Throws if Node.js version is too low to support bigint */ function bigIntAndBufferInt64Check(bufferMethod) { if (typeof BigInt === 'undefined') { throw new Error('Platform does not support JS BigInt type.'); } if (typeof buffer_1.Buffer.prototype[bufferMethod] === 'undefined') { throw new Error(`Platform does not support Buffer.prototype.${bufferMethod}.`); } } exports.bigIntAndBufferInt64Check = bigIntAndBufferInt64Check; //# sourceMappingURL=utils.js.map ```
/content/code_sandbox/node_modules/smart-buffer/build/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
931
```javascript /*! * bytes */ 'use strict'; /** * Module exports. * @public */ module.exports = bytes; module.exports.format = format; module.exports.parse = parse; /** * Module variables. * @private */ var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; var map = { b: 1, kb: 1 << 10, mb: 1 << 20, gb: 1 << 30, tb: Math.pow(1024, 4), pb: Math.pow(1024, 5), }; var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; /** * Convert the given value in bytes into a string or parse to string to an integer in bytes. * * @param {string|number} value * @param {{ * case: [string], * decimalPlaces: [number] * fixedDecimals: [boolean] * thousandsSeparator: [string] * unitSeparator: [string] * }} [options] bytes options. * * @returns {string|number|null} */ function bytes(value, options) { if (typeof value === 'string') { return parse(value); } if (typeof value === 'number') { return format(value, options); } return null; } /** * Format the given value in bytes into a string. * * If the value is negative, it is kept as such. If it is a float, * it is rounded. * * @param {number} value * @param {object} [options] * @param {number} [options.decimalPlaces=2] * @param {number} [options.fixedDecimals=false] * @param {string} [options.thousandsSeparator=] * @param {string} [options.unit=] * @param {string} [options.unitSeparator=] * * @returns {string|null} * @public */ function format(value, options) { if (!Number.isFinite(value)) { return null; } var mag = Math.abs(value); var thousandsSeparator = (options && options.thousandsSeparator) || ''; var unitSeparator = (options && options.unitSeparator) || ''; var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; var fixedDecimals = Boolean(options && options.fixedDecimals); var unit = (options && options.unit) || ''; if (!unit || !map[unit.toLowerCase()]) { if (mag >= map.pb) { unit = 'PB'; } else if (mag >= map.tb) { unit = 'TB'; } else if (mag >= map.gb) { unit = 'GB'; } else if (mag >= map.mb) { unit = 'MB'; } else if (mag >= map.kb) { unit = 'KB'; } else { unit = 'B'; } } var val = value / map[unit.toLowerCase()]; var str = val.toFixed(decimalPlaces); if (!fixedDecimals) { str = str.replace(formatDecimalsRegExp, '$1'); } if (thousandsSeparator) { str = str.split('.').map(function (s, i) { return i === 0 ? s.replace(formatThousandsRegExp, thousandsSeparator) : s }).join('.'); } return str + unitSeparator + unit; } /** * Parse the string value into an integer in bytes. * * If no unit is given, it is assumed the value is in bytes. * * @param {number|string} val * * @returns {number|null} * @public */ function parse(val) { if (typeof val === 'number' && !isNaN(val)) { return val; } if (typeof val !== 'string') { return null; } // Test if the string passed is valid var results = parseRegExp.exec(val); var floatValue; var unit = 'b'; if (!results) { // Nothing could be extracted from the given string floatValue = parseInt(val, 10); unit = 'b' } else { // Retrieve the value and the unit floatValue = parseFloat(results[1]); unit = results[4].toLowerCase(); } if (isNaN(floatValue)) { return null; } return Math.floor(map[unit] * floatValue); } ```
/content/code_sandbox/node_modules/bytes/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
994
```javascript var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; ```
/content/code_sandbox/node_modules/isarray/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
30
```javascript var isArray = require('./'); var test = require('tape'); test('is array', function(t){ t.ok(isArray([])); t.notOk(isArray({})); t.notOk(isArray(null)); t.notOk(isArray(false)); var obj = {}; obj[0] = true; t.notOk(isArray(obj)); var arr = []; arr.foo = 'bar'; t.ok(isArray(arr)); t.end(); }); ```
/content/code_sandbox/node_modules/isarray/test.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
98
```javascript // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var Buffer = require('buffer').Buffer; var isBufferEncoding = Buffer.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } } function assertEncoding(encoding) { if (encoding && !isBufferEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. CESU-8 is handled as part of the UTF-8 encoding. // // @TODO Handling all encodings inside a single object makes it very difficult // to reason about this code, so it should be split up in the future. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code // points as used by CESU-8. var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes this.surrogateSize = 3; break; case 'ucs2': case 'utf16le': // UTF-16 represents each of Surrogate Pair by 2-bytes this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; case 'base64': // Base-64 stores 3 bytes in 4 chars, and pads the remainder. this.surrogateSize = 3; this.detectIncompleteChar = base64DetectIncompleteChar; break; default: this.write = passThroughWrite; return; } // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. this.charLength = 0; }; // write decodes the given buffer and returns it as JS string that is // guaranteed to not contain any partial multi-byte characters. Any partial // character found at the end of the buffer is buffered up, and will be // returned when calling write again with the remaining bytes. // // Note: Converting a Buffer containing an orphan surrogate to a String // currently works, but converting a String to a Buffer (via `new Buffer`, or // Buffer#write) will replace incomplete surrogates with the unicode // replacement character. See path_to_url . StringDecoder.prototype.write = function(buffer) { var charStr = ''; // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char var available = (buffer.length >= this.charLength - this.charReceived) ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer buffer.copy(this.charBuffer, this.charReceived, 0, available); this.charReceived += available; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } // remove bytes belonging to the current character from the buffer buffer = buffer.slice(available, buffer.length); // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; charStr = ''; continue; } this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char if (buffer.length === 0) { return charStr; } break; } // determine and set charLength / charReceived this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); end -= this.charReceived; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); buffer.copy(this.charBuffer, 0, 0, size); return charStr.substring(0, end); } // or just emit the charStr return charStr; }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at // the end of the given buffer. If so, it sets this.charLength to the byte // length that character, and sets this.charReceived to the number of bytes // that are available for this character. StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an // incomplete char. for (; i > 0; i--) { var c = buffer[buffer.length - i]; // See path_to_url#Description // 110XXXXX if (i == 1 && c >> 5 == 0x06) { this.charLength = 2; break; } // 1110XXXX if (i <= 2 && c >> 4 == 0x0E) { this.charLength = 3; break; } // 11110XXX if (i <= 3 && c >> 3 == 0x1E) { this.charLength = 4; break; } } this.charReceived = i; }; StringDecoder.prototype.end = function(buffer) { var res = ''; if (buffer && buffer.length) res = this.write(buffer); if (this.charReceived) { var cr = this.charReceived; var buf = this.charBuffer; var enc = this.encoding; res += buf.slice(0, cr).toString(enc); } return res; }; function passThroughWrite(buffer) { return buffer.toString(this.encoding); } function utf16DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 2; this.charLength = this.charReceived ? 2 : 0; } function base64DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 3; this.charLength = this.charReceived ? 3 : 0; } ```
/content/code_sandbox/node_modules/string_decoder/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,898
```javascript 'use strict' /* eslint no-proto: 0 */ module.exports = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties) function setProtoOf (obj, proto) { obj.__proto__ = proto return obj } function mixinProperties (obj, proto) { for (var prop in proto) { if (!Object.prototype.hasOwnProperty.call(obj, prop)) { obj[prop] = proto[prop] } } return obj } ```
/content/code_sandbox/node_modules/setprototypeof/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
105
```javascript 'use strict' /* eslint-env mocha */ /* eslint no-proto: 0 */ var assert = require('assert') var setPrototypeOf = require('..') describe('setProtoOf(obj, proto)', function () { it('should merge objects', function () { var obj = { a: 1, b: 2 } var proto = { b: 3, c: 4 } var mergeObj = setPrototypeOf(obj, proto) if (Object.getPrototypeOf) { assert.strictEqual(Object.getPrototypeOf(obj), proto) } else if ({ __proto__: [] } instanceof Array) { assert.strictEqual(obj.__proto__, proto) } else { assert.strictEqual(obj.a, 1) assert.strictEqual(obj.b, 2) assert.strictEqual(obj.c, 4) } assert.strictEqual(mergeObj, obj) }) }) ```
/content/code_sandbox/node_modules/setprototypeof/test/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
183
```javascript var util = require('util'); var Stream = require('stream').Stream; var DelayedStream = require('delayed-stream'); var defer = require('./defer.js'); module.exports = CombinedStream; function CombinedStream() { this.writable = false; this.readable = true; this.dataSize = 0; this.maxDataSize = 2 * 1024 * 1024; this.pauseStreams = true; this._released = false; this._streams = []; this._currentStream = null; } util.inherits(CombinedStream, Stream); CombinedStream.create = function(options) { var combinedStream = new this(); options = options || {}; for (var option in options) { combinedStream[option] = options[option]; } return combinedStream; }; CombinedStream.isStreamLike = function(stream) { return (typeof stream !== 'function') && (typeof stream !== 'string') && (typeof stream !== 'boolean') && (typeof stream !== 'number') && (!Buffer.isBuffer(stream)); }; CombinedStream.prototype.append = function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { if (!(stream instanceof DelayedStream)) { var newStream = DelayedStream.create(stream, { maxDataSize: Infinity, pauseStream: this.pauseStreams, }); stream.on('data', this._checkDataSize.bind(this)); stream = newStream; } this._handleErrors(stream); if (this.pauseStreams) { stream.pause(); } } this._streams.push(stream); return this; }; CombinedStream.prototype.pipe = function(dest, options) { Stream.prototype.pipe.call(this, dest, options); this.resume(); return dest; }; CombinedStream.prototype._getNext = function() { this._currentStream = null; var stream = this._streams.shift(); if (typeof stream == 'undefined') { this.end(); return; } if (typeof stream !== 'function') { this._pipeNext(stream); return; } var getStream = stream; getStream(function(stream) { var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('data', this._checkDataSize.bind(this)); this._handleErrors(stream); } defer(this._pipeNext.bind(this, stream)); }.bind(this)); }; CombinedStream.prototype._pipeNext = function(stream) { this._currentStream = stream; var isStreamLike = CombinedStream.isStreamLike(stream); if (isStreamLike) { stream.on('end', this._getNext.bind(this)); stream.pipe(this, {end: false}); return; } var value = stream; this.write(value); this._getNext(); }; CombinedStream.prototype._handleErrors = function(stream) { var self = this; stream.on('error', function(err) { self._emitError(err); }); }; CombinedStream.prototype.write = function(data) { this.emit('data', data); }; CombinedStream.prototype.pause = function() { if (!this.pauseStreams) { return; } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); this.emit('pause'); }; CombinedStream.prototype.resume = function() { if (!this._released) { this._released = true; this.writable = true; this._getNext(); } if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); this.emit('resume'); }; CombinedStream.prototype.end = function() { this._reset(); this.emit('end'); }; CombinedStream.prototype.destroy = function() { this._reset(); this.emit('close'); }; CombinedStream.prototype._reset = function() { this.writable = false; this._streams = []; this._currentStream = null; }; CombinedStream.prototype._checkDataSize = function() { this._updateDataSize(); if (this.dataSize <= this.maxDataSize) { return; } var message = 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; this._emitError(new Error(message)); }; CombinedStream.prototype._updateDataSize = function() { this.dataSize = 0; var self = this; this._streams.forEach(function(stream) { if (!stream.dataSize) { return; } self.dataSize += stream.dataSize; }); if (this._currentStream && this._currentStream.dataSize) { this.dataSize += this._currentStream.dataSize; } }; CombinedStream.prototype._emitError = function(err) { this._reset(); this.emit('error', err); }; ```
/content/code_sandbox/node_modules/combined-stream/lib/combined_stream.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,050
```emacs lisp ((nil . ((indent-tabs-mode . nil) (tab-width . 8) (fill-column . 80))) (js-mode . ((js-indent-level . 2) (indent-tabs-mode . nil) ))) ```
/content/code_sandbox/node_modules/http-signature/.dir-locals.el
emacs lisp
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
49
```javascript var parser = require('./parser'); var signer = require('./signer'); var verify = require('./verify'); var utils = require('./utils'); ///--- API module.exports = { parse: parser.parseRequest, parseRequest: parser.parseRequest, sign: signer.signRequest, signRequest: signer.signRequest, createSigner: signer.createSigner, isSigner: signer.isSigner, sshKeyToPEM: utils.sshKeyToPEM, sshKeyFingerprint: utils.fingerprint, pemToRsaSSHKey: utils.pemToRsaSSHKey, verify: verify.verifySignature, verifySignature: verify.verifySignature, verifyHMAC: verify.verifyHMAC }; ```
/content/code_sandbox/node_modules/http-signature/lib/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
156
```javascript var assert = require('assert-plus'); var sshpk = require('sshpk'); var util = require('util'); var HASH_ALGOS = { 'sha1': true, 'sha256': true, 'sha512': true }; var PK_ALGOS = { 'rsa': true, 'dsa': true, 'ecdsa': true }; function HttpSignatureError(message, caller) { if (Error.captureStackTrace) Error.captureStackTrace(this, caller || HttpSignatureError); this.message = message; this.name = caller.name; } util.inherits(HttpSignatureError, Error); function InvalidAlgorithmError(message) { HttpSignatureError.call(this, message, InvalidAlgorithmError); } util.inherits(InvalidAlgorithmError, HttpSignatureError); function validateAlgorithm(algorithm) { var alg = algorithm.toLowerCase().split('-'); if (alg.length !== 2) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' + 'valid algorithm')); } if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) { throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' + 'are not supported')); } if (!HASH_ALGOS[alg[1]]) { throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' + 'supported hash algorithm')); } return (alg); } ///--- API module.exports = { HASH_ALGOS: HASH_ALGOS, PK_ALGOS: PK_ALGOS, HttpSignatureError: HttpSignatureError, InvalidAlgorithmError: InvalidAlgorithmError, validateAlgorithm: validateAlgorithm, /** * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file. * * The intent of this module is to interoperate with OpenSSL only, * specifically the node crypto module's `verify` method. * * @param {String} key an OpenSSH public key. * @return {String} PEM encoded form of the RSA public key. * @throws {TypeError} on bad input. * @throws {Error} on invalid ssh key formatted data. */ sshKeyToPEM: function sshKeyToPEM(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.toString('pem')); }, /** * Generates an OpenSSH fingerprint from an ssh public key. * * @param {String} key an OpenSSH public key. * @return {String} key fingerprint. * @throws {TypeError} on bad input. * @throws {Error} if what you passed doesn't look like an ssh public key. */ fingerprint: function fingerprint(key) { assert.string(key, 'ssh_key'); var k = sshpk.parseKey(key, 'ssh'); return (k.fingerprint('md5').toString('hex')); }, /** * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa) * * The reverse of the above function. */ pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) { assert.equal('string', typeof (pem), 'typeof pem'); var k = sshpk.parseKey(pem, 'pem'); k.comment = comment; return (k.toString('ssh')); } }; ```
/content/code_sandbox/node_modules/http-signature/lib/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
760
```javascript var assert = require('assert-plus'); var util = require('util'); var utils = require('./utils'); ///--- Globals var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var HttpSignatureError = utils.HttpSignatureError; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var validateAlgorithm = utils.validateAlgorithm; var State = { New: 0, Params: 1 }; var ParamsState = { Name: 0, Quote: 1, Value: 2, Comma: 3 }; ///--- Specific Errors function ExpiredRequestError(message) { HttpSignatureError.call(this, message, ExpiredRequestError); } util.inherits(ExpiredRequestError, HttpSignatureError); function InvalidHeaderError(message) { HttpSignatureError.call(this, message, InvalidHeaderError); } util.inherits(InvalidHeaderError, HttpSignatureError); function InvalidParamsError(message) { HttpSignatureError.call(this, message, InvalidParamsError); } util.inherits(InvalidParamsError, HttpSignatureError); function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); ///--- Exported API module.exports = { /** * Parses the 'Authorization' header out of an http.ServerRequest object. * * Note that this API will fully validate the Authorization header, and throw * on any error. It will not however check the signature, or the keyId format * as those are specific to your environment. You can use the options object * to pass in extra constraints. * * As a response object you can expect this: * * { * "scheme": "Signature", * "params": { * "keyId": "foo", * "algorithm": "rsa-sha256", * "headers": [ * "date" or "x-date", * "digest" * ], * "signature": "base64" * }, * "signingString": "ready to be passed to crypto.verify()" * } * * @param {Object} request an http.ServerRequest. * @param {Object} options an optional options object with: * - clockSkew: allowed clock skew in seconds (default 300). * - headers: required header names (def: date or x-date) * - algorithms: algorithms to support (default: all). * - strict: should enforce latest spec parsing * (default: false). * @return {Object} parsed out object (see above). * @throws {TypeError} on invalid input. * @throws {InvalidHeaderError} on an invalid Authorization header error. * @throws {InvalidParamsError} if the params in the scheme are invalid. * @throws {MissingHeaderError} if the params indicate a header not present, * either in the request headers from the params, * or not in the params from a required header * in options. * @throws {StrictParsingError} if old attributes are used in strict parsing * mode. * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew. */ parseRequest: function parseRequest(request, options) { assert.object(request, 'request'); assert.object(request.headers, 'request.headers'); if (options === undefined) { options = {}; } if (options.headers === undefined) { options.headers = [request.headers['x-date'] ? 'x-date' : 'date']; } assert.object(options, 'options'); assert.arrayOfString(options.headers, 'options.headers'); assert.optionalFinite(options.clockSkew, 'options.clockSkew'); var authzHeaderName = options.authorizationHeaderName || 'authorization'; if (!request.headers[authzHeaderName]) { throw new MissingHeaderError('no ' + authzHeaderName + ' header ' + 'present in the request'); } options.clockSkew = options.clockSkew || 300; var i = 0; var state = State.New; var substate = ParamsState.Name; var tmpName = ''; var tmpValue = ''; var parsed = { scheme: '', params: {}, signingString: '' }; var authz = request.headers[authzHeaderName]; for (i = 0; i < authz.length; i++) { var c = authz.charAt(i); switch (Number(state)) { case State.New: if (c !== ' ') parsed.scheme += c; else state = State.Params; break; case State.Params: switch (Number(substate)) { case ParamsState.Name: var code = c.charCodeAt(0); // restricted name of A-Z / a-z if ((code >= 0x41 && code <= 0x5a) || // A-Z (code >= 0x61 && code <= 0x7a)) { // a-z tmpName += c; } else if (c === '=') { if (tmpName.length === 0) throw new InvalidHeaderError('bad param format'); substate = ParamsState.Quote; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Quote: if (c === '"') { tmpValue = ''; substate = ParamsState.Value; } else { throw new InvalidHeaderError('bad param format'); } break; case ParamsState.Value: if (c === '"') { parsed.params[tmpName] = tmpValue; substate = ParamsState.Comma; } else { tmpValue += c; } break; case ParamsState.Comma: if (c === ',') { tmpName = ''; substate = ParamsState.Name; } else { throw new InvalidHeaderError('bad param format'); } break; default: throw new Error('Invalid substate'); } break; default: throw new Error('Invalid substate'); } } if (!parsed.params.headers || parsed.params.headers === '') { if (request.headers['x-date']) { parsed.params.headers = ['x-date']; } else { parsed.params.headers = ['date']; } } else { parsed.params.headers = parsed.params.headers.split(' '); } // Minimally validate the parsed object if (!parsed.scheme || parsed.scheme !== 'Signature') throw new InvalidHeaderError('scheme was not "Signature"'); if (!parsed.params.keyId) throw new InvalidHeaderError('keyId was not specified'); if (!parsed.params.algorithm) throw new InvalidHeaderError('algorithm was not specified'); if (!parsed.params.signature) throw new InvalidHeaderError('signature was not specified'); // Check the algorithm against the official list parsed.params.algorithm = parsed.params.algorithm.toLowerCase(); try { validateAlgorithm(parsed.params.algorithm); } catch (e) { if (e instanceof InvalidAlgorithmError) throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' + 'supported')); else throw (e); } // Build the signingString for (i = 0; i < parsed.params.headers.length; i++) { var h = parsed.params.headers[i].toLowerCase(); parsed.params.headers[i] = h; if (h === 'request-line') { if (!options.strict) { /* * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ parsed.signingString += request.method + ' ' + request.url + ' HTTP/' + request.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { parsed.signingString += '(request-target): ' + request.method.toLowerCase() + ' ' + request.url; } else { var value = request.headers[h]; if (value === undefined) throw new MissingHeaderError(h + ' was not in the request'); parsed.signingString += h + ': ' + value; } if ((i + 1) < parsed.params.headers.length) parsed.signingString += '\n'; } // Check against the constraints var date; if (request.headers.date || request.headers['x-date']) { if (request.headers['x-date']) { date = new Date(request.headers['x-date']); } else { date = new Date(request.headers.date); } var now = new Date(); var skew = Math.abs(now.getTime() - date.getTime()); if (skew > options.clockSkew * 1000) { throw new ExpiredRequestError('clock skew of ' + (skew / 1000) + 's was greater than ' + options.clockSkew + 's'); } } options.headers.forEach(function (hdr) { // Remember that we already checked any headers in the params // were in the request, so if this passes we're good. if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0) throw new MissingHeaderError(hdr + ' was not a signed header'); }); if (options.algorithms) { if (options.algorithms.indexOf(parsed.params.algorithm) === -1) throw new InvalidParamsError(parsed.params.algorithm + ' is not a supported algorithm'); } parsed.algorithm = parsed.params.algorithm.toUpperCase(); parsed.keyId = parsed.params.keyId; return parsed; } }; ```
/content/code_sandbox/node_modules/http-signature/lib/parser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,177
```javascript "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const utils_1 = require("./utils"); // The default Buffer size if one is not provided. const DEFAULT_SMARTBUFFER_SIZE = 4096; // The default string encoding to use for reading/writing strings. const DEFAULT_SMARTBUFFER_ENCODING = 'utf8'; class SmartBuffer { /** * Creates a new SmartBuffer instance. * * @param options { SmartBufferOptions } The SmartBufferOptions to apply to this instance. */ constructor(options) { this.length = 0; this._encoding = DEFAULT_SMARTBUFFER_ENCODING; this._writeOffset = 0; this._readOffset = 0; if (SmartBuffer.isSmartBufferOptions(options)) { // Checks for encoding if (options.encoding) { utils_1.checkEncoding(options.encoding); this._encoding = options.encoding; } // Checks for initial size length if (options.size) { if (utils_1.isFiniteInteger(options.size) && options.size > 0) { this._buff = Buffer.allocUnsafe(options.size); } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_SIZE); } // Check for initial Buffer } else if (options.buff) { if (Buffer.isBuffer(options.buff)) { this._buff = options.buff; this.length = options.buff.length; } else { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_BUFFER); } } else { this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } else { // If something was passed but it's not a SmartBufferOptions object if (typeof options !== 'undefined') { throw new Error(utils_1.ERRORS.INVALID_SMARTBUFFER_OBJECT); } // Otherwise default to sane options this._buff = Buffer.allocUnsafe(DEFAULT_SMARTBUFFER_SIZE); } } /** * Creates a new SmartBuffer instance with the provided internal Buffer size and optional encoding. * * @param size { Number } The size of the internal Buffer. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromSize(size, encoding) { return new this({ size: size, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided Buffer and optional encoding. * * @param buffer { Buffer } The Buffer to use as the internal Buffer value. * @param encoding { String } The BufferEncoding to use for strings. * * @return { SmartBuffer } */ static fromBuffer(buff, encoding) { return new this({ buff: buff, encoding: encoding }); } /** * Creates a new SmartBuffer instance with the provided SmartBufferOptions options. * * @param options { SmartBufferOptions } The options to use when creating the SmartBuffer instance. */ static fromOptions(options) { return new this(options); } /** * Type checking function that determines if an object is a SmartBufferOptions object. */ static isSmartBufferOptions(options) { const castOptions = options; return (castOptions && (castOptions.encoding !== undefined || castOptions.size !== undefined || castOptions.buff !== undefined)); } // Signed integers /** * Reads an Int8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt8(offset) { return this._readNumberValue(Buffer.prototype.readInt8, 1, offset); } /** * Reads an Int16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readInt16BE, 2, offset); } /** * Reads an Int16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readInt16LE, 2, offset); } /** * Reads an Int32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readInt32BE, 4, offset); } /** * Reads an Int32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readInt32LE, 4, offset); } /** * Reads a BigInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64BE'); return this._readNumberValue(Buffer.prototype.readBigInt64BE, 8, offset); } /** * Reads a BigInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigInt64LE'); return this._readNumberValue(Buffer.prototype.readBigInt64LE, 8, offset); } /** * Writes an Int8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt8(value, offset) { this._writeNumberValue(Buffer.prototype.writeInt8, 1, value, offset); return this; } /** * Inserts an Int8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt8, 1, value, offset); } /** * Writes an Int16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Inserts an Int16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16BE, 2, value, offset); } /** * Writes an Int16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Inserts an Int16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt16LE, 2, value, offset); } /** * Writes an Int32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Inserts an Int32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32BE, 4, value, offset); } /** * Writes an Int32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Inserts an Int32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeInt32LE, 4, value, offset); } /** * Writes a BigInt64BE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Inserts a BigInt64BE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64BE, 8, value, offset); } /** * Writes a BigInt64LE value to the current write position (or at optional offset). * * @param value { BigInt } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } /** * Inserts a Int64LE value at the given offset value. * * @param value { BigInt } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigInt64LE, 8, value, offset); } // Unsigned Integers /** * Reads an UInt8 value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt8(offset) { return this._readNumberValue(Buffer.prototype.readUInt8, 1, offset); } /** * Reads an UInt16BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16BE, 2, offset); } /** * Reads an UInt16LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt16LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt16LE, 2, offset); } /** * Reads an UInt32BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32BE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32BE, 4, offset); } /** * Reads an UInt32LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readUInt32LE(offset) { return this._readNumberValue(Buffer.prototype.readUInt32LE, 4, offset); } /** * Reads a BigUInt64BE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64BE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64BE'); return this._readNumberValue(Buffer.prototype.readBigUInt64BE, 8, offset); } /** * Reads a BigUInt64LE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { BigInt } */ readBigUInt64LE(offset) { utils_1.bigIntAndBufferInt64Check('readBigUInt64LE'); return this._readNumberValue(Buffer.prototype.readBigUInt64LE, 8, offset); } /** * Writes an UInt8 value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt8(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Inserts an UInt8 value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt8(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt8, 1, value, offset); } /** * Writes an UInt16BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Inserts an UInt16BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16BE, 2, value, offset); } /** * Writes an UInt16LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt16LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Inserts an UInt16LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt16LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt16LE, 2, value, offset); } /** * Writes an UInt32BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32BE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Inserts an UInt32BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32BE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32BE, 4, value, offset); } /** * Writes an UInt32LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeUInt32LE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Inserts an UInt32LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertUInt32LE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeUInt32LE, 4, value, offset); } /** * Writes a BigUInt64BE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Inserts a BigUInt64BE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64BE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64BE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64BE, 8, value, offset); } /** * Writes a BigUInt64LE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._writeNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } /** * Inserts a BigUInt64LE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertBigUInt64LE(value, offset) { utils_1.bigIntAndBufferInt64Check('writeBigUInt64LE'); return this._insertNumberValue(Buffer.prototype.writeBigUInt64LE, 8, value, offset); } // Floating Point /** * Reads an FloatBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatBE(offset) { return this._readNumberValue(Buffer.prototype.readFloatBE, 4, offset); } /** * Reads an FloatLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readFloatLE(offset) { return this._readNumberValue(Buffer.prototype.readFloatLE, 4, offset); } /** * Writes a FloatBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Inserts a FloatBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatBE, 4, value, offset); } /** * Writes a FloatLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeFloatLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } /** * Inserts a FloatLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertFloatLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeFloatLE, 4, value, offset); } // Double Floating Point /** * Reads an DoublEBE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleBE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleBE, 8, offset); } /** * Reads an DoubleLE value from the current read position or an optionally provided offset. * * @param offset { Number } The offset to read data from (optional) * @return { Number } */ readDoubleLE(offset) { return this._readNumberValue(Buffer.prototype.readDoubleLE, 8, offset); } /** * Writes a DoubleBE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleBE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Inserts a DoubleBE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleBE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleBE, 8, value, offset); } /** * Writes a DoubleLE value to the current write position (or at optional offset). * * @param value { Number } The value to write. * @param offset { Number } The offset to write the value at. * * @return this */ writeDoubleLE(value, offset) { return this._writeNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } /** * Inserts a DoubleLE value at the given offset value. * * @param value { Number } The value to insert. * @param offset { Number } The offset to insert the value at. * * @return this */ insertDoubleLE(value, offset) { return this._insertNumberValue(Buffer.prototype.writeDoubleLE, 8, value, offset); } // Strings /** * Reads a String from the current read position. * * @param arg1 { Number | String } The number of bytes to read as a String, or the BufferEncoding to use for * the string (Defaults to instance level encoding). * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readString(arg1, encoding) { let lengthVal; // Length provided if (typeof arg1 === 'number') { utils_1.checkLengthValue(arg1); lengthVal = Math.min(arg1, this.length - this._readOffset); } else { encoding = arg1; lengthVal = this.length - this._readOffset; } // Check encoding if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } const value = this._buff.slice(this._readOffset, this._readOffset + lengthVal).toString(encoding || this._encoding); this._readOffset += lengthVal; return value; } /** * Inserts a String * * @param value { String } The String value to insert. * @param offset { Number } The offset to insert the string at. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertString(value, offset, encoding) { utils_1.checkOffsetValue(offset); return this._handleString(value, true, offset, encoding); } /** * Writes a String * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeString(value, arg2, encoding) { return this._handleString(value, false, arg2, encoding); } /** * Reads a null-terminated String from the current read position. * * @param encoding { String } The BufferEncoding to use for the string (Defaults to instance level encoding). * * @return { String } */ readStringNT(encoding) { if (typeof encoding !== 'undefined') { utils_1.checkEncoding(encoding); } // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read string value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value.toString(encoding || this._encoding); } /** * Inserts a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ insertStringNT(value, offset, encoding) { utils_1.checkOffsetValue(offset); // Write Values this.insertString(value, offset, encoding); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated String. * * @param value { String } The String value to write. * @param arg2 { Number | String } The offset to write the string to, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). * * @return this */ writeStringNT(value, arg2, encoding) { // Write Values this.writeString(value, arg2, encoding); this.writeUInt8(0x00, typeof arg2 === 'number' ? arg2 + value.length : this.writeOffset); return this; } // Buffers /** * Reads a Buffer from the internal read position. * * @param length { Number } The length of data to read as a Buffer. * * @return { Buffer } */ readBuffer(length) { if (typeof length !== 'undefined') { utils_1.checkLengthValue(length); } const lengthVal = typeof length === 'number' ? length : this.length; const endPoint = Math.min(this.length, this._readOffset + lengthVal); // Read buffer value const value = this._buff.slice(this._readOffset, endPoint); // Increment internal Buffer read offset this._readOffset = endPoint; return value; } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBuffer(value, offset) { utils_1.checkOffsetValue(offset); return this._handleBuffer(value, true, offset); } /** * Writes a Buffer to the current write position. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBuffer(value, offset) { return this._handleBuffer(value, false, offset); } /** * Reads a null-terminated Buffer from the current read poisiton. * * @return { Buffer } */ readBufferNT() { // Set null character position to the end SmartBuffer instance. let nullPos = this.length; // Find next null character (if one is not found, default from above is used) for (let i = this._readOffset; i < this.length; i++) { if (this._buff[i] === 0x00) { nullPos = i; break; } } // Read value const value = this._buff.slice(this._readOffset, nullPos); // Increment internal Buffer read offset this._readOffset = nullPos + 1; return value; } /** * Inserts a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ insertBufferNT(value, offset) { utils_1.checkOffsetValue(offset); // Write Values this.insertBuffer(value, offset); this.insertUInt8(0x00, offset + value.length); return this; } /** * Writes a null-terminated Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. * * @return this */ writeBufferNT(value, offset) { // Checks for valid numberic value; if (typeof offset !== 'undefined') { utils_1.checkOffsetValue(offset); } // Write Values this.writeBuffer(value, offset); this.writeUInt8(0x00, typeof offset === 'number' ? offset + value.length : this._writeOffset); return this; } /** * Clears the SmartBuffer instance to its original empty state. */ clear() { this._writeOffset = 0; this._readOffset = 0; this.length = 0; return this; } /** * Gets the remaining data left to be read from the SmartBuffer instance. * * @return { Number } */ remaining() { return this.length - this._readOffset; } /** * Gets the current read offset value of the SmartBuffer instance. * * @return { Number } */ get readOffset() { return this._readOffset; } /** * Sets the read offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set readOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._readOffset = offset; } /** * Gets the current write offset value of the SmartBuffer instance. * * @return { Number } */ get writeOffset() { return this._writeOffset; } /** * Sets the write offset value of the SmartBuffer instance. * * @param offset { Number } - The offset value to set. */ set writeOffset(offset) { utils_1.checkOffsetValue(offset); // Check for bounds. utils_1.checkTargetOffset(offset, this); this._writeOffset = offset; } /** * Gets the currently set string encoding of the SmartBuffer instance. * * @return { BufferEncoding } The string Buffer encoding currently set. */ get encoding() { return this._encoding; } /** * Sets the string encoding of the SmartBuffer instance. * * @param encoding { BufferEncoding } The string Buffer encoding to set. */ set encoding(encoding) { utils_1.checkEncoding(encoding); this._encoding = encoding; } /** * Gets the underlying internal Buffer. (This includes unmanaged data in the Buffer) * * @return { Buffer } The Buffer value. */ get internalBuffer() { return this._buff; } /** * Gets the value of the internal managed Buffer (Includes managed data only) * * @param { Buffer } */ toBuffer() { return this._buff.slice(0, this.length); } /** * Gets the String value of the internal managed Buffer * * @param encoding { String } The BufferEncoding to display the Buffer as (defaults to instance level encoding). */ toString(encoding) { const encodingVal = typeof encoding === 'string' ? encoding : this._encoding; // Check for invalid encoding. utils_1.checkEncoding(encodingVal); return this._buff.toString(encodingVal, 0, this.length); } /** * Destroys the SmartBuffer instance. */ destroy() { this.clear(); return this; } /** * Handles inserting and writing strings. * * @param value { String } The String value to insert. * @param isInsert { Boolean } True if inserting a string, false if writing. * @param arg2 { Number | String } The offset to insert the string at, or the BufferEncoding to use. * @param encoding { String } The BufferEncoding to use for writing strings (defaults to instance encoding). */ _handleString(value, isInsert, arg3, encoding) { let offsetVal = this._writeOffset; let encodingVal = this._encoding; // Check for offset if (typeof arg3 === 'number') { offsetVal = arg3; // Check for encoding } else if (typeof arg3 === 'string') { utils_1.checkEncoding(arg3); encodingVal = arg3; } // Check for encoding (third param) if (typeof encoding === 'string') { utils_1.checkEncoding(encoding); encodingVal = encoding; } // Calculate bytelength of string. const byteLength = Buffer.byteLength(value, encodingVal); // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(byteLength, offsetVal); } else { this._ensureWriteable(byteLength, offsetVal); } // Write value this._buff.write(value, offsetVal, byteLength, encodingVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += byteLength; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof arg3 === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteLength); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteLength; } } return this; } /** * Handles writing or insert of a Buffer. * * @param value { Buffer } The Buffer to write. * @param offset { Number } The offset to write the Buffer to. */ _handleBuffer(value, isInsert, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. if (isInsert) { this.ensureInsertable(value.length, offsetVal); } else { this._ensureWriteable(value.length, offsetVal); } // Write buffer value value.copy(this._buff, offsetVal); // Increment internal Buffer write offset; if (isInsert) { this._writeOffset += value.length; } else { // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + value.length); } else { // If no offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += value.length; } } return this; } /** * Ensures that the internal Buffer is large enough to read data. * * @param length { Number } The length of the data that needs to be read. * @param offset { Number } The offset of the data that needs to be read. */ ensureReadable(length, offset) { // Offset value defaults to managed read offset. let offsetVal = this._readOffset; // If an offset was provided, use it. if (typeof offset !== 'undefined') { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Overide with custom offset. offsetVal = offset; } // Checks if offset is below zero, or the offset+length offset is beyond the total length of the managed data. if (offsetVal < 0 || offsetVal + length > this.length) { throw new Error(utils_1.ERRORS.INVALID_READ_BEYOND_BOUNDS); } } /** * Ensures that the internal Buffer is large enough to insert data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written. */ ensureInsertable(dataLength, offset) { // Checks for valid numberic value; utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. this._ensureCapacity(this.length + dataLength); // If an offset was provided and its not the very end of the buffer, copy data into appropriate location in regards to the offset. if (offset < this.length) { this._buff.copy(this._buff, offset + dataLength, offset, this._buff.length); } // Adjust tracked smart buffer length if (offset + dataLength > this.length) { this.length = offset + dataLength; } else { this.length += dataLength; } } /** * Ensures that the internal Buffer is large enough to write data. * * @param dataLength { Number } The length of the data that needs to be written. * @param offset { Number } The offset of the data to be written (defaults to writeOffset). */ _ensureWriteable(dataLength, offset) { const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure enough capacity to write data. this._ensureCapacity(offsetVal + dataLength); // Adjust SmartBuffer length (if offset + length is larger than managed length, adjust length) if (offsetVal + dataLength > this.length) { this.length = offsetVal + dataLength; } } /** * Ensures that the internal Buffer is large enough to write at least the given amount of data. * * @param minLength { Number } The minimum length of the data needs to be written. */ _ensureCapacity(minLength) { const oldLength = this._buff.length; if (minLength > oldLength) { let data = this._buff; let newLength = (oldLength * 3) / 2 + 1; if (newLength < minLength) { newLength = minLength; } this._buff = Buffer.allocUnsafe(newLength); data.copy(this._buff, 0, 0, oldLength); } } /** * Reads a numeric number value using the provided function. * * @typeparam T { number | bigint } The type of the value to be read * * @param func { Function(offset: number) => number } The function to read data on the internal Buffer with. * @param byteSize { Number } The number of bytes read. * @param offset { Number } The offset to read from (optional). When this is not provided, the managed readOffset is used instead. * * @returns { T } the number value */ _readNumberValue(func, byteSize, offset) { this.ensureReadable(byteSize, offset); // Call Buffer.readXXXX(); const value = func.call(this._buff, typeof offset === 'number' ? offset : this._readOffset); // Adjust internal read offset if an optional read offset was not provided. if (typeof offset === 'undefined') { this._readOffset += byteSize; } return value; } /** * Inserts a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _insertNumberValue(func, byteSize, value, offset) { // Check for invalid offset values. utils_1.checkOffsetValue(offset); // Ensure there is enough internal Buffer capacity. (raw offset is passed) this.ensureInsertable(byteSize, offset); // Call buffer.writeXXXX(); func.call(this._buff, value, offset); // Adjusts internally managed write offset. this._writeOffset += byteSize; return this; } /** * Writes a numeric number value based on the given offset and value. * * @typeparam T { number | bigint } The type of the value to be written * * @param func { Function(offset: T, offset?) => number} The function to write data on the internal Buffer with. * @param byteSize { Number } The number of bytes written. * @param value { T } The number value to write. * @param offset { Number } the offset to write the number at (REQUIRED). * * @returns SmartBuffer this buffer */ _writeNumberValue(func, byteSize, value, offset) { // If an offset was provided, validate it. if (typeof offset === 'number') { // Check if we're writing beyond the bounds of the managed data. if (offset < 0) { throw new Error(utils_1.ERRORS.INVALID_WRITE_BEYOND_BOUNDS); } utils_1.checkOffsetValue(offset); } // Default to writeOffset if no offset value was given. const offsetVal = typeof offset === 'number' ? offset : this._writeOffset; // Ensure there is enough internal Buffer capacity. (raw offset is passed) this._ensureWriteable(byteSize, offsetVal); func.call(this._buff, value, offsetVal); // If an offset was given, check to see if we wrote beyond the current writeOffset. if (typeof offset === 'number') { this._writeOffset = Math.max(this._writeOffset, offsetVal + byteSize); } else { // If no numeric offset was given, we wrote to the end of the SmartBuffer so increment writeOffset. this._writeOffset += byteSize; } return this; } } exports.SmartBuffer = SmartBuffer; //# sourceMappingURL=smartbuffer.js.map ```
/content/code_sandbox/node_modules/smart-buffer/build/smartbuffer.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,282
```javascript var assert = require('assert-plus'); var crypto = require('crypto'); var sshpk = require('sshpk'); var utils = require('./utils'); var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Exported API module.exports = { /** * Verify RSA/DSA signature against public key. You are expected to pass in * an object that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} pubkey RSA/DSA private key PEM. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifySignature: function verifySignature(parsedSignature, pubkey) { assert.object(parsedSignature, 'parsedSignature'); if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey)) pubkey = sshpk.parseKey(pubkey); assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] === 'hmac' || alg[0] !== pubkey.type) return (false); var v = pubkey.createVerify(alg[1]); v.update(parsedSignature.signingString); return (v.verify(parsedSignature.params.signature, 'base64')); }, /** * Verify HMAC against shared secret. You are expected to pass in an object * that was returned from `parse()`. * * @param {Object} parsedSignature the object you got from `parse`. * @param {String} secret HMAC shared secret. * @return {Boolean} true if valid, false otherwise. * @throws {TypeError} if you pass in bad arguments. * @throws {InvalidAlgorithmError} */ verifyHMAC: function verifyHMAC(parsedSignature, secret) { assert.object(parsedSignature, 'parsedHMAC'); assert.string(secret, 'secret'); var alg = validateAlgorithm(parsedSignature.algorithm); if (alg[0] !== 'hmac') return (false); var hashAlg = alg[1].toUpperCase(); var hmac = crypto.createHmac(hashAlg, secret); hmac.update(parsedSignature.signingString); /* * Now double-hash to avoid leaking timing information - there's * no easy constant-time compare in JS, so we use this approach * instead. See for more info: * path_to_url * verification.aspx */ var h1 = crypto.createHmac(hashAlg, secret); h1.update(hmac.digest()); h1 = h1.digest(); var h2 = crypto.createHmac(hashAlg, secret); h2.update(new Buffer(parsedSignature.params.signature, 'base64')); h2 = h2.digest(); /* Node 0.8 returns strings from .digest(). */ if (typeof (h1) === 'string') return (h1 === h2); /* And node 0.10 lacks the .equals() method on Buffers. */ if (Buffer.isBuffer(h1) && !h1.equals) return (h1.toString('binary') === h2.toString('binary')); return (h1.equals(h2)); } }; ```
/content/code_sandbox/node_modules/http-signature/lib/verify.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
768
```javascript 'use strict'; var bind = require('function-bind'); var GetIntrinsic = require('get-intrinsic'); var $apply = GetIntrinsic('%Function.prototype.apply%'); var $call = GetIntrinsic('%Function.prototype.call%'); var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); var $max = GetIntrinsic('%Math.max%'); if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = null; } } module.exports = function callBind(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD && $defineProperty) { var desc = $gOPD(func, 'length'); if (desc.configurable) { // original length, plus the receiver, minus any additional arguments (after the receiver) $defineProperty( func, 'length', { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } ); } } return func; }; var applyBind = function applyBind() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } ```
/content/code_sandbox/node_modules/call-bind/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
345
```javascript 'use strict'; var GetIntrinsic = require('get-intrinsic'); var callBind = require('./'); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBind(intrinsic); } return intrinsic; }; ```
/content/code_sandbox/node_modules/call-bind/callBound.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
96
```javascript 'use strict'; var callBind = require('../'); var bind = require('function-bind'); var test = require('tape'); /* * older engines have length nonconfigurable * in io.js v3, it is configurable except on bound functions, hence the .bind() */ var functionsHaveConfigurableLengths = !!( Object.getOwnPropertyDescriptor && Object.getOwnPropertyDescriptor(bind.call(function () {}), 'length').configurable ); test('callBind', function (t) { var sentinel = { sentinel: true }; var func = function (a, b) { // eslint-disable-next-line no-invalid-this return [this, a, b]; }; t.equal(func.length, 2, 'original function length is 2'); t.deepEqual(func(), [undefined, undefined, undefined], 'unbound func with too few args'); t.deepEqual(func(1, 2), [undefined, 1, 2], 'unbound func with right args'); t.deepEqual(func(1, 2, 3), [undefined, 1, 2], 'unbound func with too many args'); var bound = callBind(func); t.equal(bound.length, func.length + 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); t.deepEqual(bound(), [undefined, undefined, undefined], 'bound func with too few args'); t.deepEqual(bound(1, 2), [1, 2, undefined], 'bound func with right args'); t.deepEqual(bound(1, 2, 3), [1, 2, 3], 'bound func with too many args'); var boundR = callBind(func, sentinel); t.equal(boundR.length, func.length, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); t.deepEqual(boundR(), [sentinel, undefined, undefined], 'bound func with receiver, with too few args'); t.deepEqual(boundR(1, 2), [sentinel, 1, 2], 'bound func with receiver, with right args'); t.deepEqual(boundR(1, 2, 3), [sentinel, 1, 2], 'bound func with receiver, with too many args'); var boundArg = callBind(func, sentinel, 1); t.equal(boundArg.length, func.length - 1, 'function length is preserved', { skip: !functionsHaveConfigurableLengths }); t.deepEqual(boundArg(), [sentinel, 1, undefined], 'bound func with receiver and arg, with too few args'); t.deepEqual(boundArg(2), [sentinel, 1, 2], 'bound func with receiver and arg, with right arg'); t.deepEqual(boundArg(2, 3), [sentinel, 1, 2], 'bound func with receiver and arg, with too many args'); t.test('callBind.apply', function (st) { var aBound = callBind.apply(func); st.deepEqual(aBound(sentinel), [sentinel, undefined, undefined], 'apply-bound func with no args'); st.deepEqual(aBound(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); st.deepEqual(aBound(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); var aBoundArg = callBind.apply(func); st.deepEqual(aBoundArg(sentinel, [1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with too many args'); st.deepEqual(aBoundArg(sentinel, [1, 2], 4), [sentinel, 1, 2], 'apply-bound func with right args'); st.deepEqual(aBoundArg(sentinel, [1], 4), [sentinel, 1, undefined], 'apply-bound func with too few args'); var aBoundR = callBind.apply(func, sentinel); st.deepEqual(aBoundR([1, 2, 3], 4), [sentinel, 1, 2], 'apply-bound func with receiver and too many args'); st.deepEqual(aBoundR([1, 2], 4), [sentinel, 1, 2], 'apply-bound func with receiver and right args'); st.deepEqual(aBoundR([1], 4), [sentinel, 1, undefined], 'apply-bound func with receiver and too few args'); st.end(); }); t.end(); }); ```
/content/code_sandbox/node_modules/call-bind/test/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
965
```javascript 'use strict'; var test = require('tape'); var callBound = require('../callBound'); test('callBound', function (t) { // static primitive t.equal(callBound('Array.length'), Array.length, 'Array.length yields itself'); t.equal(callBound('%Array.length%'), Array.length, '%Array.length% yields itself'); // static non-function object t.equal(callBound('Array.prototype'), Array.prototype, 'Array.prototype yields itself'); t.equal(callBound('%Array.prototype%'), Array.prototype, '%Array.prototype% yields itself'); t.equal(callBound('Array.constructor'), Array.constructor, 'Array.constructor yields itself'); t.equal(callBound('%Array.constructor%'), Array.constructor, '%Array.constructor% yields itself'); // static function t.equal(callBound('Date.parse'), Date.parse, 'Date.parse yields itself'); t.equal(callBound('%Date.parse%'), Date.parse, '%Date.parse% yields itself'); // prototype primitive t.equal(callBound('Error.prototype.message'), Error.prototype.message, 'Error.prototype.message yields itself'); t.equal(callBound('%Error.prototype.message%'), Error.prototype.message, '%Error.prototype.message% yields itself'); // prototype function t.notEqual(callBound('Object.prototype.toString'), Object.prototype.toString, 'Object.prototype.toString does not yield itself'); t.notEqual(callBound('%Object.prototype.toString%'), Object.prototype.toString, '%Object.prototype.toString% does not yield itself'); t.equal(callBound('Object.prototype.toString')(true), Object.prototype.toString.call(true), 'call-bound Object.prototype.toString calls into the original'); t.equal(callBound('%Object.prototype.toString%')(true), Object.prototype.toString.call(true), 'call-bound %Object.prototype.toString% calls into the original'); t['throws']( function () { callBound('does not exist'); }, SyntaxError, 'nonexistent intrinsic throws' ); t['throws']( function () { callBound('does not exist', true); }, SyntaxError, 'allowMissing arg still throws for unknown intrinsic' ); /* globals WeakRef: false */ t.test('real but absent intrinsic', { skip: typeof WeakRef !== 'undefined' }, function (st) { st['throws']( function () { callBound('WeakRef'); }, TypeError, 'real but absent intrinsic throws' ); st.equal(callBound('WeakRef', true), undefined, 'allowMissing arg avoids exception'); st.end(); }); t.end(); }); ```
/content/code_sandbox/node_modules/call-bind/test/callBound.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
515
```yaml ui: mocha-bdd server: ./test/support/server.js tunnel_host: path_to_url browsers: - name: chrome version: latest - name: firefox version: latest - name: safari version: latest - name: ie version: 9..latest browserify: - transform: name: babelify configFile: './.dist.babelrc' ```
/content/code_sandbox/node_modules/superagent/.zuul.yml
yaml
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
97
```javascript var assert = require('assert-plus'); var crypto = require('crypto'); var http = require('http'); var util = require('util'); var sshpk = require('sshpk'); var jsprim = require('jsprim'); var utils = require('./utils'); var sprintf = require('util').format; var HASH_ALGOS = utils.HASH_ALGOS; var PK_ALGOS = utils.PK_ALGOS; var InvalidAlgorithmError = utils.InvalidAlgorithmError; var HttpSignatureError = utils.HttpSignatureError; var validateAlgorithm = utils.validateAlgorithm; ///--- Globals var AUTHZ_FMT = 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"'; ///--- Specific Errors function MissingHeaderError(message) { HttpSignatureError.call(this, message, MissingHeaderError); } util.inherits(MissingHeaderError, HttpSignatureError); function StrictParsingError(message) { HttpSignatureError.call(this, message, StrictParsingError); } util.inherits(StrictParsingError, HttpSignatureError); /* See createSigner() */ function RequestSigner(options) { assert.object(options, 'options'); var alg = []; if (options.algorithm !== undefined) { assert.string(options.algorithm, 'options.algorithm'); alg = validateAlgorithm(options.algorithm); } this.rs_alg = alg; /* * RequestSigners come in two varieties: ones with an rs_signFunc, and ones * with an rs_signer. * * rs_signFunc-based RequestSigners have to build up their entire signing * string within the rs_lines array and give it to rs_signFunc as a single * concat'd blob. rs_signer-based RequestSigners can add a line at a time to * their signing state by using rs_signer.update(), thus only needing to * buffer the hash function state and one line at a time. */ if (options.sign !== undefined) { assert.func(options.sign, 'options.sign'); this.rs_signFunc = options.sign; } else if (alg[0] === 'hmac' && options.key !== undefined) { assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key for HMAC must be a string or Buffer')); /* * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their * data in chunks rather than requiring it all to be given in one go * at the end, so they are more similar to signers than signFuncs. */ this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key); this.rs_signer.sign = function () { var digest = this.digest('base64'); return ({ hashAlgorithm: alg[1], toString: function () { return (digest); } }); }; } else if (options.key !== undefined) { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); this.rs_key = key; assert.string(options.keyId, 'options.keyId'); this.rs_keyId = options.keyId; if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } this.rs_signer = key.createSign(alg[1]); } else { throw (new TypeError('options.sign (func) or options.key is required')); } this.rs_headers = []; this.rs_lines = []; } /** * Adds a header to be signed, with its value, into this signer. * * @param {String} header * @param {String} value * @return {String} value written */ RequestSigner.prototype.writeHeader = function (header, value) { assert.string(header, 'header'); header = header.toLowerCase(); assert.string(value, 'value'); this.rs_headers.push(header); if (this.rs_signFunc) { this.rs_lines.push(header + ': ' + value); } else { var line = header + ': ' + value; if (this.rs_headers.length > 0) line = '\n' + line; this.rs_signer.update(line); } return (value); }; /** * Adds a default Date header, returning its value. * * @return {String} */ RequestSigner.prototype.writeDateHeader = function () { return (this.writeHeader('date', jsprim.rfc1123(new Date()))); }; /** * Adds the request target line to be signed. * * @param {String} method, HTTP method (e.g. 'get', 'post', 'put') * @param {String} path */ RequestSigner.prototype.writeTarget = function (method, path) { assert.string(method, 'method'); assert.string(path, 'path'); method = method.toLowerCase(); this.writeHeader('(request-target)', method + ' ' + path); }; /** * Calculate the value for the Authorization header on this request * asynchronously. * * @param {Func} callback (err, authz) */ RequestSigner.prototype.sign = function (cb) { assert.func(cb, 'callback'); if (this.rs_headers.length < 1) throw (new Error('At least one header must be signed')); var alg, authz; if (this.rs_signFunc) { var data = this.rs_lines.join('\n'); var self = this; this.rs_signFunc(data, function (err, sig) { if (err) { cb(err); return; } try { assert.object(sig, 'signature'); assert.string(sig.keyId, 'signature.keyId'); assert.string(sig.algorithm, 'signature.algorithm'); assert.string(sig.signature, 'signature.signature'); alg = validateAlgorithm(sig.algorithm); authz = sprintf(AUTHZ_FMT, sig.keyId, sig.algorithm, self.rs_headers.join(' '), sig.signature); } catch (e) { cb(e); return; } cb(null, authz); }); } else { try { var sigObj = this.rs_signer.sign(); } catch (e) { cb(e); return; } alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm; var signature = sigObj.toString(); authz = sprintf(AUTHZ_FMT, this.rs_keyId, alg, this.rs_headers.join(' '), signature); cb(null, authz); } }; ///--- Exported API module.exports = { /** * Identifies whether a given object is a request signer or not. * * @param {Object} object, the object to identify * @returns {Boolean} */ isSigner: function (obj) { if (typeof (obj) === 'object' && obj instanceof RequestSigner) return (true); return (false); }, /** * Creates a request signer, used to asynchronously build a signature * for a request (does not have to be an http.ClientRequest). * * @param {Object} options, either: * - {String} keyId * - {String|Buffer} key * - {String} algorithm (optional, required for HMAC) * or: * - {Func} sign (data, cb) * @return {RequestSigner} */ createSigner: function createSigner(options) { return (new RequestSigner(options)); }, /** * Adds an 'Authorization' header to an http.ClientRequest object. * * Note that this API will add a Date header if it's not already set. Any * other headers in the options.headers array MUST be present, or this * will throw. * * You shouldn't need to check the return type; it's just there if you want * to be pedantic. * * The optional flag indicates whether parsing should use strict enforcement * of the version draft-cavage-http-signatures-04 of the spec or beyond. * The default is to be loose and support * older versions for compatibility. * * @param {Object} request an instance of http.ClientRequest. * @param {Object} options signing parameters object: * - {String} keyId required. * - {String} key required (either a PEM or HMAC key). * - {Array} headers optional; defaults to ['date']. * - {String} algorithm optional (unless key is HMAC); * default is the same as the sshpk default * signing algorithm for the type of key given * - {String} httpVersion optional; defaults to '1.1'. * - {Boolean} strict optional; defaults to 'false'. * @return {Boolean} true if Authorization (and optionally Date) were added. * @throws {TypeError} on bad parameter types (input). * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with * the given key. * @throws {sshpk.KeyParseError} if key was bad. * @throws {MissingHeaderError} if a header to be signed was specified but * was not present. */ signRequest: function signRequest(request, options) { assert.object(request, 'request'); assert.object(options, 'options'); assert.optionalString(options.algorithm, 'options.algorithm'); assert.string(options.keyId, 'options.keyId'); assert.optionalArrayOfString(options.headers, 'options.headers'); assert.optionalString(options.httpVersion, 'options.httpVersion'); if (!request.getHeader('Date')) request.setHeader('Date', jsprim.rfc1123(new Date())); if (!options.headers) options.headers = ['date']; if (!options.httpVersion) options.httpVersion = '1.1'; var alg = []; if (options.algorithm) { options.algorithm = options.algorithm.toLowerCase(); alg = validateAlgorithm(options.algorithm); } var i; var stringToSign = ''; for (i = 0; i < options.headers.length; i++) { if (typeof (options.headers[i]) !== 'string') throw new TypeError('options.headers must be an array of Strings'); var h = options.headers[i].toLowerCase(); if (h === 'request-line') { if (!options.strict) { /** * We allow headers from the older spec drafts if strict parsing isn't * specified in options. */ stringToSign += request.method + ' ' + request.path + ' HTTP/' + options.httpVersion; } else { /* Strict parsing doesn't allow older draft headers. */ throw (new StrictParsingError('request-line is not a valid header ' + 'with strict parsing enabled.')); } } else if (h === '(request-target)') { stringToSign += '(request-target): ' + request.method.toLowerCase() + ' ' + request.path; } else { var value = request.getHeader(h); if (value === undefined || value === '') { throw new MissingHeaderError(h + ' was not in the request'); } stringToSign += h + ': ' + value; } if ((i + 1) < options.headers.length) stringToSign += '\n'; } /* This is just for unit tests. */ if (request.hasOwnProperty('_stringToSign')) { request._stringToSign = stringToSign; } var signature; if (alg[0] === 'hmac') { if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key)) throw (new TypeError('options.key must be a string or Buffer')); var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key); hmac.update(stringToSign); signature = hmac.digest('base64'); } else { var key = options.key; if (typeof (key) === 'string' || Buffer.isBuffer(key)) key = sshpk.parsePrivateKey(options.key); assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]), 'options.key must be a sshpk.PrivateKey'); if (!PK_ALGOS[key.type]) { throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' + 'keys are not supported')); } if (alg[0] !== undefined && key.type !== alg[0]) { throw (new InvalidAlgorithmError('options.key must be a ' + alg[0].toUpperCase() + ' key, was given a ' + key.type.toUpperCase() + ' key instead')); } var signer = key.createSign(alg[1]); signer.update(stringToSign); var sigObj = signer.sign(); if (!HASH_ALGOS[sigObj.hashAlgorithm]) { throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() + ' is not a supported hash algorithm')); } options.algorithm = key.type + '-' + sigObj.hashAlgorithm; signature = sigObj.toString(); assert.notStrictEqual(signature, '', 'empty signature produced'); } var authzHeaderName = options.authorizationHeaderName || 'Authorization'; request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT, options.keyId, options.algorithm, options.headers.join(' '), signature)); return true; } }; ```
/content/code_sandbox/node_modules/http-signature/lib/signer.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,047
```javascript "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ exports.type = function (str) { return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ exports.params = function (val) { var obj = {}; var _iterator = _createForOfIteratorHelper(val.split(/ *; */)), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var str = _step.value; var parts = str.split(/ *= */); var key = parts.shift(); var _val = parts.shift(); if (key && _val) obj[key] = _val; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return obj; }; /** * Parse Link header fields. * * @param {String} str * @return {Object} * @api private */ exports.parseLinks = function (val) { var obj = {}; var _iterator2 = _createForOfIteratorHelper(val.split(/ *, */)), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var str = _step2.value; var parts = str.split(/ *; */); var url = parts[0].slice(1, -1); var rel = parts[1].split(/ *= */)[1].slice(1, -1); obj[rel] = url; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return obj; }; /** * Strip content related fields from `header`. * * @param {Object} header * @return {Object} header * @api private */ exports.cleanHeader = function (header, changesOrigin) { delete header['content-type']; delete header['content-length']; delete header['transfer-encoding']; delete header.host; // secuirty if (changesOrigin) { delete header.authorization; delete header.cookie; } return header; }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcyA9ICh2YWwpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashICB9XG5cbiAgcmV0dXJuIGhlYWRlcjtcbn07XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,290
```javascript "use strict"; /** * Module dependencies. */ var utils = require('./utils'); /** * Expose `ResponseBase`. */ module.exports = ResponseBase; /** * Initialize a new `ResponseBase`. * * @api public */ function ResponseBase(obj) { if (obj) return mixin(obj); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in ResponseBase.prototype) { if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key]; } return obj; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ ResponseBase.prototype.get = function (field) { return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ ResponseBase.prototype._setHeaderProperties = function (header) { // TODO: moar! // TODO: make this a util // content-type var ct = header['content-type'] || ''; this.type = utils.type(ct); // params var params = utils.params(ct); for (var key in params) { if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key]; } this.links = {}; // links try { if (header.link) { this.links = utils.parseLinks(header.link); } } catch (_unused) {// ignore } }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ ResponseBase.prototype._setStatusProperties = function (status) { var type = status / 100 | 0; // status / class this.statusCode = status; this.status = this.statusCode; this.statusType = type; // basics this.info = type === 1; this.ok = type === 2; this.redirect = type === 3; this.clientError = type === 4; this.serverError = type === 5; this.error = type === 4 || type === 5 ? this.toError() : false; // sugar this.created = status === 201; this.accepted = status === 202; this.noContent = status === 204; this.badRequest = status === 400; this.unauthorized = status === 401; this.notAcceptable = status === 406; this.forbidden = status === 403; this.notFound = status === 404; this.unprocessableEntity = status === 422; }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashb2Nlc3NhYmxlRW50aXR5ID0gc3RhdHVzID09PSA0MjI7XG59O1xuIl19 ```
/content/code_sandbox/node_modules/superagent/lib/response-base.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,311
```html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>SuperAgent elegant API for AJAX in Node and browsers</title> <link rel="stylesheet" href="path_to_url"> <link rel="stylesheet" href="docs/style.css"> </head> <body> <ul id="menu"></ul> <div id="content"> <h1 id="superagent">SuperAgent</h1> <p>SuperAgent is light-weight progressive ajax API crafted for flexibility, readability, and a low learning curve after being frustrated with many of the existing request APIs. It also works with Node.js!</p> <pre><code> request .post(&#39;/api/pet&#39;) .send({ name: &#39;Manny&#39;, species: &#39;cat&#39; }) .set(&#39;X-API-Key&#39;, &#39;foobar&#39;) .set(&#39;Accept&#39;, &#39;application/json&#39;) .then(res =&gt; { alert(&#39;yay got &#39; + JSON.stringify(res.body)); });</code></pre> <h2 id="test-documentation">Test documentation</h2> <p>The following <a href="docs/test.html">test documentation</a> was generated with <a href="path_to_url">Mocha&#39;s</a> &quot;doc&quot; reporter, and directly reflects the test suite. This provides an additional source of documentation.</p> <h2 id="request-basics">Request basics</h2> <p>A request can be initiated by invoking the appropriate method on the <code>request</code> object, then calling <code>.then()</code> (or <code>.end()</code> <a href="#promise-and-generator-support">or <code>await</code></a>) to send the request. For example a simple <strong>GET</strong> request:</p> <pre><code> request .get(&#39;/search&#39;) .then(res =&gt; { // res.body, res.headers, res.status }) .catch(err =&gt; { // err.message, err.response });</code></pre> <p>HTTP method may also be passed as a string:</p> <pre><code>request(&#39;GET&#39;, &#39;/search&#39;).then(success, failure);</code></pre> <p>Old-style callbacks are also supported, but not recommended. <em>Instead of</em> <code>.then()</code> you can call <code>.end()</code>:</p> <pre><code>request(&#39;GET&#39;, &#39;/search&#39;).end(function(err, res){ if (res.ok) {} });</code></pre> <p>Absolute URLs can be used. In web browsers absolute URLs work only if the server implements <a href="#cors">CORS</a>.</p> <pre><code> request .get(&#39;path_to_url#39;) .then(res =&gt; { });</code></pre> <p>The <strong>Node</strong> client supports making requests to <a href="path_to_url">Unix Domain Sockets</a>:</p> <pre><code>// pattern: https?+unix://SOCKET_PATH/REQUEST_PATH // Use `%2F` as `/` in SOCKET_PATH try { const res = await request .get(&#39;http+unix://%2Fabsolute%2Fpath%2Fto%2Funix.sock/search&#39;); // res.body, res.headers, res.status } catch(err) { // err.message, err.response }</code></pre> <p><strong>DELETE</strong>, <strong>HEAD</strong>, <strong>PATCH</strong>, <strong>POST</strong>, and <strong>PUT</strong> requests can also be used, simply change the method name:</p> <pre><code>request .head(&#39;/favicon.ico&#39;) .then(res =&gt; { });</code></pre> <p><strong>DELETE</strong> can be also called as <code>.del()</code> for compatibility with old IE where <code>delete</code> is a reserved word.</p> <p>The HTTP method defaults to <strong>GET</strong>, so if you wish, the following is valid:</p> <pre><code> request(&#39;/search&#39;, (err, res) =&gt; { });</code></pre> <h2 id="setting-header-fields">Setting header fields</h2> <p>Setting header fields is simple, invoke <code>.set()</code> with a field name and value:</p> <pre><code> request .get(&#39;/search&#39;) .set(&#39;API-Key&#39;, &#39;foobar&#39;) .set(&#39;Accept&#39;, &#39;application/json&#39;) .then(callback);</code></pre> <p>You may also pass an object to set several fields in a single call:</p> <pre><code> request .get(&#39;/search&#39;) .set({ &#39;API-Key&#39;: &#39;foobar&#39;, Accept: &#39;application/json&#39; }) .then(callback);</code></pre> <h2 id="get-requests"><code>GET</code> requests</h2> <p>The <code>.query()</code> method accepts objects, which when used with the <strong>GET</strong> method will form a query-string. The following will produce the path <code>/search?query=Manny&amp;range=1..5&amp;order=desc</code>.</p> <pre><code> request .get(&#39;/search&#39;) .query({ query: &#39;Manny&#39; }) .query({ range: &#39;1..5&#39; }) .query({ order: &#39;desc&#39; }) .then(res =&gt; { });</code></pre> <p>Or as a single object:</p> <pre><code>request .get(&#39;/search&#39;) .query({ query: &#39;Manny&#39;, range: &#39;1..5&#39;, order: &#39;desc&#39; }) .then(res =&gt; { });</code></pre> <p>The <code>.query()</code> method accepts strings as well:</p> <pre><code> request .get(&#39;/querystring&#39;) .query(&#39;search=Manny&amp;range=1..5&#39;) .then(res =&gt; { });</code></pre> <p>Or joined:</p> <pre><code> request .get(&#39;/querystring&#39;) .query(&#39;search=Manny&#39;) .query(&#39;range=1..5&#39;) .then(res =&gt; { });</code></pre> <h2 id="head-requests"><code>HEAD</code> requests</h2> <p>You can also use the <code>.query()</code> method for HEAD requests. The following will produce the path <code>/users?email=joe@smith.com</code>.</p> <pre><code> request .head(&#39;/users&#39;) .query({ email: &#39;joe@smith.com&#39; }) .then(res =&gt; { });</code></pre> <h2 id="post--put-requests"><code>POST</code> / <code>PUT</code> requests</h2> <p>A typical JSON <strong>POST</strong> request might look a little like the following, where we set the Content-Type header field appropriately, and &quot;write&quot; some data, in this case just a JSON string.</p> <pre><code> request.post(&#39;/user&#39;) .set(&#39;Content-Type&#39;, &#39;application/json&#39;) .send(&#39;{&quot;name&quot;:&quot;tj&quot;,&quot;pet&quot;:&quot;tobi&quot;}&#39;) .then(callback) .catch(errorCallback)</code></pre> <p>Since JSON is undoubtedly the most common, it&#39;s the <em>default</em>! The following example is equivalent to the previous.</p> <pre><code> request.post(&#39;/user&#39;) .send({ name: &#39;tj&#39;, pet: &#39;tobi&#39; }) .then(callback, errorCallback)</code></pre> <p>Or using multiple <code>.send()</code> calls:</p> <pre><code> request.post(&#39;/user&#39;) .send({ name: &#39;tj&#39; }) .send({ pet: &#39;tobi&#39; }) .then(callback, errorCallback)</code></pre> <p>By default sending strings will set the <code>Content-Type</code> to <code>application/x-www-form-urlencoded</code>, multiple calls will be concatenated with <code>&amp;</code>, here resulting in <code>name=tj&amp;pet=tobi</code>:</p> <pre><code> request.post(&#39;/user&#39;) .send(&#39;name=tj&#39;) .send(&#39;pet=tobi&#39;) .then(callback, errorCallback);</code></pre> <p>SuperAgent formats are extensible, however by default &quot;json&quot; and &quot;form&quot; are supported. To send the data as <code>application/x-www-form-urlencoded</code> simply invoke <code>.type()</code> with &quot;form&quot;, where the default is &quot;json&quot;. This request will <strong>POST</strong> the body &quot;name=tj&amp;pet=tobi&quot;.</p> <pre><code> request.post(&#39;/user&#39;) .type(&#39;form&#39;) .send({ name: &#39;tj&#39; }) .send({ pet: &#39;tobi&#39; }) .then(callback, errorCallback)</code></pre> <p>Sending a <a href="path_to_url"><code>FormData</code></a> object is also supported. The following example will <strong>POST</strong> the content of the HTML form identified by id=&quot;myForm&quot;:</p> <pre><code> request.post(&#39;/user&#39;) .send(new FormData(document.getElementById(&#39;myForm&#39;))) .then(callback, errorCallback)</code></pre> <h2 id="setting-the-content-type">Setting the <code>Content-Type</code></h2> <p>The obvious solution is to use the <code>.set()</code> method:</p> <pre><code> request.post(&#39;/user&#39;) .set(&#39;Content-Type&#39;, &#39;application/json&#39;)</code></pre> <p>As a short-hand the <code>.type()</code> method is also available, accepting the canonicalized MIME type name complete with type/subtype, or simply the extension name such as &quot;xml&quot;, &quot;json&quot;, &quot;png&quot;, etc:</p> <pre><code> request.post(&#39;/user&#39;) .type(&#39;application/json&#39;) request.post(&#39;/user&#39;) .type(&#39;json&#39;) request.post(&#39;/user&#39;) .type(&#39;png&#39;)</code></pre> <h2 id="serializing-request-body">Serializing request body</h2> <p>SuperAgent will automatically serialize JSON and forms. You can setup automatic serialization for other types as well:</p> <pre><code class="language-js">request.serialize[&#39;application/xml&#39;] = function (obj) { return &#39;string generated from obj&#39;; }; // going forward, all requests with a Content-type of // &#39;application/xml&#39; will be automatically serialized</code></pre> <p>If you want to send the payload in a custom format, you can replace the built-in serialization with the <code>.serialize()</code> method on a per-request basis:</p> <pre><code class="language-js">request .post(&#39;/user&#39;) .send({foo: &#39;bar&#39;}) .serialize(obj =&gt; { return &#39;string generated from obj&#39;; });</code></pre> <h2 id="retrying-requests">Retrying requests</h2> <p>When given the <code>.retry()</code> method, SuperAgent will automatically retry requests, if they fail in a way that is transient or could be due to a flaky Internet connection.</p> <p>This method has two optional arguments: number of retries (default 1) and a callback. It calls <code>callback(err, res)</code> before each retry. The callback may return <code>true</code>/<code>false</code> to control whether the request should be retried (but the maximum number of retries is always applied).</p> <pre><code> request .get(&#39;path_to_url#39;) .retry(2) // or: .retry(2, callback) .then(finished); .catch(failed);</code></pre> <p>Use <code>.retry()</code> only with requests that are <em>idempotent</em> (i.e. multiple requests reaching the server won&#39;t cause undesirable side effects like duplicate purchases).</p> <p>All request methods are tried by default (which means if you do not want POST requests to be retried, you will need to pass a custom retry callback).</p> <p>By default the following status codes are retried:</p> <ul> <li><code>408</code></li> <li><code>413</code></li> <li><code>429</code></li> <li><code>500</code></li> <li><code>502</code></li> <li><code>503</code></li> <li><code>504</code></li> <li><code>521</code></li> <li><code>522</code></li> <li><code>524</code></li> </ul> <p>By default the following error codes are retried:</p> <ul> <li><code>&#39;ETIMEDOUT&#39;</code></li> <li><code>&#39;ECONNRESET&#39;</code></li> <li><code>&#39;EADDRINUSE&#39;</code></li> <li><code>&#39;ECONNREFUSED&#39;</code></li> <li><code>&#39;EPIPE&#39;</code></li> <li><code>&#39;ENOTFOUND&#39;</code></li> <li><code>&#39;ENETUNREACH&#39;</code></li> <li><code>&#39;EAI_AGAIN&#39;</code></li> </ul> <h2 id="setting-accept">Setting Accept</h2> <p>In a similar fashion to the <code>.type()</code> method it is also possible to set the <code>Accept</code> header via the short hand method <code>.accept()</code>. Which references <code>request.types</code> as well allowing you to specify either the full canonicalized MIME type name as <code>type/subtype</code>, or the extension suffix form as &quot;xml&quot;, &quot;json&quot;, &quot;png&quot;, etc. for convenience:</p> <pre><code> request.get(&#39;/user&#39;) .accept(&#39;application/json&#39;) request.get(&#39;/user&#39;) .accept(&#39;json&#39;) request.post(&#39;/user&#39;) .accept(&#39;png&#39;)</code></pre> <h3 id="facebook-and-accept-json">Facebook and Accept JSON</h3> <p>If you are calling Facebook&#39;s API, be sure to send an <code>Accept: application/json</code> header in your request. If you don&#39;t do this, Facebook will respond with <code>Content-Type: text/javascript; charset=UTF-8</code>, which SuperAgent will not parse and thus <code>res.body</code> will be undefined. You can do this with either <code>req.accept(&#39;json&#39;)</code> or <code>req.header(&#39;Accept&#39;, &#39;application/json&#39;)</code>. See <a href="path_to_url">issue 1078</a> for details.</p> <h2 id="query-strings">Query strings</h2> <p> <code>req.query(obj)</code> is a method which may be used to build up a query-string. For example populating <code>?format=json&amp;dest=/login</code> on a <strong>POST</strong>:</p> <pre><code>request .post(&#39;/&#39;) .query({ format: &#39;json&#39; }) .query({ dest: &#39;/login&#39; }) .send({ post: &#39;data&#39;, here: &#39;wahoo&#39; }) .then(callback);</code></pre> <p>By default the query string is not assembled in any particular order. An asciibetically-sorted query string can be enabled with <code>req.sortQuery()</code>. You may also provide a custom sorting comparison function with <code>req.sortQuery(myComparisonFn)</code>. The comparison function should take 2 arguments and return a negative/zero/positive integer.</p> <pre><code class="language-js"> // default order request.get(&#39;/user&#39;) .query(&#39;name=Nick&#39;) .query(&#39;search=Manny&#39;) .sortQuery() .then(callback) // customized sort function request.get(&#39;/user&#39;) .query(&#39;name=Nick&#39;) .query(&#39;search=Manny&#39;) .sortQuery((a, b) =&gt; a.length - b.length) .then(callback)</code></pre> <h2 id="tls-options">TLS options</h2> <p>In Node.js SuperAgent supports methods to configure HTTPS requests:</p> <ul> <li><code>.ca()</code>: Set the CA certificate(s) to trust</li> <li><code>.cert()</code>: Set the client certificate chain(s)</li> <li><code>.key()</code>: Set the client private key(s)</li> <li><code>.pfx()</code>: Set the client PFX or PKCS12 encoded private key and certificate chain</li> <li><code>.disableTLSCerts()</code>: Does not reject expired or invalid TLS certs. Sets internally <code>rejectUnauthorized=true</code>. <em>Be warned, this method allows MITM attacks.</em></li> </ul> <p>For more information, see Node.js <a href="path_to_url#https_https_request_options_callback">https.request docs</a>.</p> <pre><code class="language-js">var key = fs.readFileSync(&#39;key.pem&#39;), cert = fs.readFileSync(&#39;cert.pem&#39;); request .post(&#39;/client-auth&#39;) .key(key) .cert(cert) .then(callback);</code></pre> <pre><code class="language-js">var ca = fs.readFileSync(&#39;ca.cert.pem&#39;); request .post(&#39;path_to_url#39;) .ca(ca) .then(res =&gt; {});</code></pre> <h2 id="parsing-response-bodies">Parsing response bodies</h2> <p>SuperAgent will parse known response-body data for you, currently supporting <code>application/x-www-form-urlencoded</code>, <code>application/json</code>, and <code>multipart/form-data</code>. You can setup automatic parsing for other response-body data as well:</p> <pre><code class="language-js">//browser request.parse[&#39;application/xml&#39;] = function (str) { return {&#39;object&#39;: &#39;parsed from str&#39;}; }; //node request.parse[&#39;application/xml&#39;] = function (res, cb) { //parse response text and set res.body here cb(null, res); }; //going forward, responses of type &#39;application/xml&#39; //will be parsed automatically</code></pre> <p>You can set a custom parser (that takes precedence over built-in parsers) with the <code>.buffer(true).parse(fn)</code> method. If response buffering is not enabled (<code>.buffer(false)</code>) then the <code>response</code> event will be emitted without waiting for the body parser to finish, so <code>response.body</code> won&#39;t be available.</p> <h3 id="json--urlencoded">JSON / Urlencoded</h3> <p>The property <code>res.body</code> is the parsed object, for example if a request responded with the JSON string &#39;{&quot;user&quot;:{&quot;name&quot;:&quot;tobi&quot;}}&#39;, <code>res.body.user.name</code> would be &quot;tobi&quot;. Likewise the x-www-form-urlencoded value of &quot;user[name]=tobi&quot; would yield the same result. Only one level of nesting is supported. If you need more complex data, send JSON instead.</p> <p>Arrays are sent by repeating the key. <code>.send({color: [&#39;red&#39;,&#39;blue&#39;]})</code> sends <code>color=red&amp;color=blue</code>. If you want the array keys to contain <code>[]</code> in their name, you must add it yourself, as SuperAgent doesn&#39;t add it automatically.</p> <h3 id="multipart">Multipart</h3> <p>The Node client supports <em>multipart/form-data</em> via the <a href="path_to_url">Formidable</a> module. When parsing multipart responses, the object <code>res.files</code> is also available to you. Suppose for example a request responds with the following multipart body:</p> <pre><code>--whoop Content-Disposition: attachment; name=&quot;image&quot;; filename=&quot;tobi.png&quot; Content-Type: image/png ... data here ... --whoop Content-Disposition: form-data; name=&quot;name&quot; Content-Type: text/plain Tobi --whoop--</code></pre> <p>You would have the values <code>res.body.name</code> provided as &quot;Tobi&quot;, and <code>res.files.image</code> as a <code>File</code> object containing the path on disk, filename, and other properties.</p> <h3 id="binary">Binary</h3> <p>In browsers, you may use <code>.responseType(&#39;blob&#39;)</code> to request handling of binary response bodies. This API is unnecessary when running in node.js. The supported argument values for this method are</p> <ul> <li><code>&#39;blob&#39;</code> passed through to the XmlHTTPRequest <code>responseType</code> property</li> <li><code>&#39;arraybuffer&#39;</code> passed through to the XmlHTTPRequest <code>responseType</code> property</li> </ul> <pre><code class="language-js">req.get(&#39;/binary.data&#39;) .responseType(&#39;blob&#39;) .then(res =&gt; { // res.body will be a browser native Blob type here });</code></pre> <p>For more information, see the Mozilla Developer Network <a href="path_to_url">xhr.responseType docs</a>.</p> <h2 id="response-properties">Response properties</h2> <p>Many helpful flags and properties are set on the <code>Response</code> object, ranging from the response text, parsed response body, header fields, status flags and more.</p> <h3 id="response-text">Response text</h3> <p>The <code>res.text</code> property contains the unparsed response body string. This property is always present for the client API, and only when the mime type matches &quot;text/<em>&quot;, &quot;</em>/json&quot;, or &quot;x-www-form-urlencoded&quot; by default for node. The reasoning is to conserve memory, as buffering text of large bodies such as multipart files or images is extremely inefficient. To force buffering see the &quot;Buffering responses&quot; section.</p> <h3 id="response-body">Response body</h3> <p>Much like SuperAgent can auto-serialize request data, it can also automatically parse it. When a parser is defined for the Content-Type, it is parsed, which by default includes &quot;application/json&quot; and &quot;application/x-www-form-urlencoded&quot;. The parsed object is then available via <code>res.body</code>.</p> <h3 id="response-header-fields">Response header fields</h3> <p>The <code>res.header</code> contains an object of parsed header fields, lowercasing field names much like node does. For example <code>res.header[&#39;content-length&#39;]</code>.</p> <h3 id="response-content-type">Response Content-Type</h3> <p>The Content-Type response header is special-cased, providing <code>res.type</code>, which is void of the charset (if any). For example the Content-Type of &quot;text/html; charset=utf8&quot; will provide &quot;text/html&quot; as <code>res.type</code>, and the <code>res.charset</code> property would then contain &quot;utf8&quot;.</p> <h3 id="response-status">Response status</h3> <p>The response status flags help determine if the request was a success, among other useful information, making SuperAgent ideal for interacting with RESTful web services. These flags are currently defined as:</p> <pre><code> var type = status / 100 | 0; // status / class res.status = status; res.statusType = type; // basics res.info = 1 == type; res.ok = 2 == type; res.clientError = 4 == type; res.serverError = 5 == type; res.error = 4 == type || 5 == type; // sugar res.accepted = 202 == status; res.noContent = 204 == status || 1223 == status; res.badRequest = 400 == status; res.unauthorized = 401 == status; res.notAcceptable = 406 == status; res.notFound = 404 == status; res.forbidden = 403 == status;</code></pre> <h2 id="aborting-requests">Aborting requests</h2> <p>To abort requests simply invoke the <code>req.abort()</code> method.</p> <h2 id="timeouts">Timeouts</h2> <p>Sometimes networks and servers get &quot;stuck&quot; and never respond after accepting a request. Set timeouts to avoid requests waiting forever.</p> <ul> <li><p><code>req.timeout({deadline:ms})</code> or <code>req.timeout(ms)</code> (where <code>ms</code> is a number of milliseconds &gt; 0) sets a deadline for the entire request (including all uploads, redirects, server processing time) to complete. If the response isn&#39;t fully downloaded within that time, the request will be aborted.</p> </li> <li><p><code>req.timeout({response:ms})</code> sets maximum time to wait for the first byte to arrive from the server, but it does not limit how long the entire download can take. Response timeout should be at least few seconds longer than just the time it takes the server to respond, because it also includes time to make DNS lookup, TCP/IP and TLS connections, and time to upload request data.</p> </li> </ul> <p>You should use both <code>deadline</code> and <code>response</code> timeouts. This way you can use a short response timeout to detect unresponsive networks quickly, and a long deadline to give time for downloads on slow, but reliable, networks. Note that both of these timers limit how long <em>uploads</em> of attached files are allowed to take. Use long timeouts if you&#39;re uploading files.</p> <pre><code>request .get(&#39;/big-file?network=slow&#39;) .timeout({ response: 5000, // Wait 5 seconds for the server to start sending, deadline: 60000, // but allow 1 minute for the file to finish loading. }) .then(res =&gt; { /* responded in time */ }, err =&gt; { if (err.timeout) { /* timed out! */ } else { /* other error */ } });</code></pre> <p>Timeout errors have a <code>.timeout</code> property.</p> <h2 id="authentication">Authentication</h2> <p>In both Node and browsers auth available via the <code>.auth()</code> method:</p> <pre><code>request .get(&#39;path_to_url#39;) .auth(&#39;tobi&#39;, &#39;learnboost&#39;) .then(callback);</code></pre> <p>In the <em>Node</em> client Basic auth can be in the URL as &quot;user:pass&quot;:</p> <pre><code>request.get(&#39;path_to_url#39;).then(callback);</code></pre> <p>By default only <code>Basic</code> auth is used. In browser you can add <code>{type:&#39;auto&#39;}</code> to enable all methods built-in in the browser (Digest, NTLM, etc.):</p> <pre><code>request.auth(&#39;digest&#39;, &#39;secret&#39;, {type:&#39;auto&#39;})</code></pre> <p>The <code>auth</code> method also supports a <code>type</code> of <code>bearer</code>, to specify token-based authentication:</p> <pre><code>request.auth(&#39;my_token&#39;, { type: &#39;bearer&#39; })</code></pre> <h2 id="following-redirects">Following redirects</h2> <p>By default up to 5 redirects will be followed, however you may specify this with the <code>res.redirects(n)</code> method:</p> <pre><code>const response = await request.get(&#39;/some.png&#39;).redirects(2);</code></pre> <p>Redirects exceeding the limit are treated as errors. Use <code>.ok(res =&gt; res.status &lt; 400)</code> to read them as successful responses.</p> <h2 id="agents-for-global-state">Agents for global state</h2> <h3 id="saving-cookies">Saving cookies</h3> <p>In Node SuperAgent does not save cookies by default, but you can use the <code>.agent()</code> method to create a copy of SuperAgent that saves cookies. Each copy has a separate cookie jar.</p> <pre><code>const agent = request.agent(); agent .post(&#39;/login&#39;) .then(() =&gt; { return agent.get(&#39;/cookied-page&#39;); });</code></pre> <p>In browsers cookies are managed automatically by the browser, so the <code>.agent()</code> does not isolate cookies.</p> <h3 id="default-options-for-multiple-requests">Default options for multiple requests</h3> <p>Regular request methods called on the agent will be used as defaults for all requests made by that agent.</p> <pre><code>const agent = request.agent() .use(plugin) .auth(shared); await agent.get(&#39;/with-plugin-and-auth&#39;); await agent.get(&#39;/also-with-plugin-and-auth&#39;);</code></pre> <p>The complete list of methods that the agent can use to set defaults is: <code>use</code>, <code>on</code>, <code>once</code>, <code>set</code>, <code>query</code>, <code>type</code>, <code>accept</code>, <code>auth</code>, <code>withCredentials</code>, <code>sortQuery</code>, <code>retry</code>, <code>ok</code>, <code>redirects</code>, <code>timeout</code>, <code>buffer</code>, <code>serialize</code>, <code>parse</code>, <code>ca</code>, <code>key</code>, <code>pfx</code>, <code>cert</code>.</p> <h2 id="piping-data">Piping data</h2> <p>The Node client allows you to pipe data to and from the request. Please note that <code>.pipe()</code> is used <strong>instead of</strong> <code>.end()</code>/<code>.then()</code> methods.</p> <p>For example piping a file&#39;s contents as the request:</p> <pre><code>const request = require(&#39;superagent&#39;); const fs = require(&#39;fs&#39;); const stream = fs.createReadStream(&#39;path/to/my.json&#39;); const req = request.post(&#39;/somewhere&#39;); req.type(&#39;json&#39;); stream.pipe(req);</code></pre> <p>Note that when you pipe to a request, superagent sends the piped data with <a href="path_to_url">chunked transfer encoding</a>, which isn&#39;t supported by all servers (for instance, Python WSGI servers).</p> <p>Or piping the response to a file:</p> <pre><code>const stream = fs.createWriteStream(&#39;path/to/my.json&#39;); const req = request.get(&#39;/some.json&#39;); req.pipe(stream);</code></pre> <p> It&#39;s not possible to mix pipes and callbacks or promises. Note that you should <strong>NOT</strong> attempt to pipe the result of <code>.end()</code> or the <code>Response</code> object:</p> <pre><code>// Don&#39;t do either of these: const stream = getAWritableStream(); const req = request .get(&#39;/some.json&#39;) // BAD: this pipes garbage to the stream and fails in unexpected ways .end((err, this_does_not_work) =&gt; this_does_not_work.pipe(stream)) const req = request .get(&#39;/some.json&#39;) .end() // BAD: this is also unsupported, .pipe calls .end for you. .pipe(nope_its_too_late);</code></pre> <p>In a <a href="path_to_url">future version</a> of superagent, improper calls to <code>pipe()</code> will fail.</p> <h2 id="multipart-requests">Multipart requests</h2> <p>SuperAgent is also great for <em>building</em> multipart requests for which it provides methods <code>.attach()</code> and <code>.field()</code>.</p> <p>When you use <code>.field()</code> or <code>.attach()</code> you can&#39;t use <code>.send()</code> and you <em>must not</em> set <code>Content-Type</code> (the correct type will be set for you).</p> <h3 id="attaching-files">Attaching files</h3> <p>To send a file use <code>.attach(name, [file], [options])</code>. You can attach multiple files by calling <code>.attach</code> multiple times. The arguments are:</p> <ul> <li><code>name</code> field name in the form.</li> <li><code>file</code> either string with file path or <code>Blob</code>/<code>Buffer</code> object.</li> <li><code>options</code> (optional) either string with custom file name or <code>{filename: string}</code> object. In Node also <code>{contentType: &#39;mime/type&#39;}</code> is supported. In browser create a <code>Blob</code> with an appropriate type instead.</li> </ul> <br> <pre><code>request .post(&#39;/upload&#39;) .attach(&#39;image1&#39;, &#39;path/to/felix.jpeg&#39;) .attach(&#39;image2&#39;, imageBuffer, &#39;luna.jpeg&#39;) .field(&#39;caption&#39;, &#39;My cats&#39;) .then(callback);</code></pre> <h3 id="field-values">Field values</h3> <p>Much like form fields in HTML, you can set field values with <code>.field(name, value)</code> and <code>.field({name: value})</code>. Suppose you want to upload a few images with your name and email, your request might look something like this:</p> <pre><code> request .post(&#39;/upload&#39;) .field(&#39;user[name]&#39;, &#39;Tobi&#39;) .field(&#39;user[email]&#39;, &#39;tobi@learnboost.com&#39;) .field(&#39;friends[]&#39;, [&#39;loki&#39;, &#39;jane&#39;]) .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;) .then(callback);</code></pre> <h2 id="compression">Compression</h2> <p>The node client supports compressed responses, best of all, you don&#39;t have to do anything! It just works.</p> <h2 id="buffering-responses">Buffering responses</h2> <p>To force buffering of response bodies as <code>res.text</code> you may invoke <code>req.buffer()</code>. To undo the default of buffering for text responses such as &quot;text/plain&quot;, &quot;text/html&quot; etc you may invoke <code>req.buffer(false)</code>.</p> <p>When buffered the <code>res.buffered</code> flag is provided, you may use this to handle both buffered and unbuffered responses in the same callback.</p> <h2 id="cors">CORS</h2> <p>For security reasons, browsers will block cross-origin requests unless the server opts-in using CORS headers. Browsers will also make extra <strong>OPTIONS</strong> requests to check what HTTP headers and methods are allowed by the server. <a href="path_to_url">Read more about CORS</a>.</p> <p>The <code>.withCredentials()</code> method enables the ability to send cookies from the origin, however only when <code>Access-Control-Allow-Origin</code> is <em>not</em> a wildcard (&quot;*&quot;), and <code>Access-Control-Allow-Credentials</code> is &quot;true&quot;.</p> <pre><code>request .get(&#39;path_to_url#39;) .withCredentials() .then(res =&gt; { assert.equal(200, res.status); assert.equal(&#39;tobi&#39;, res.text); })</code></pre> <h2 id="error-handling">Error handling</h2> <p>Your callback function will always be passed two arguments: error and response. If no error occurred, the first argument will be null:</p> <pre><code>request .post(&#39;/upload&#39;) .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;) .then(res =&gt; { });</code></pre> <p>An &quot;error&quot; event is also emitted, with you can listen for:</p> <pre><code>request .post(&#39;/upload&#39;) .attach(&#39;image&#39;, &#39;path/to/tobi.png&#39;) .on(&#39;error&#39;, handle) .then(res =&gt; { });</code></pre> <p>Note that <strong>superagent considers 4xx and 5xx responses (as well as unhandled 3xx responses) errors by default</strong>. For example, if you get a <code>304 Not modified</code>, <code>403 Forbidden</code> or <code>500 Internal server error</code> response, this status information will be available via <code>err.status</code>. Errors from such responses also contain an <code>err.response</code> field with all of the properties mentioned in &quot;<a href="#response-properties">Response properties</a>&quot;. The library behaves in this way to handle the common case of wanting success responses and treating HTTP error status codes as errors while still allowing for custom logic around specific error conditions.</p> <p>Network failures, timeouts, and other errors that produce no response will contain no <code>err.status</code> or <code>err.response</code> fields.</p> <p>If you wish to handle 404 or other HTTP error responses, you can query the <code>err.status</code> property. When an HTTP error occurs (4xx or 5xx response) the <code>res.error</code> property is an <code>Error</code> object, this allows you to perform checks such as:</p> <pre><code>if (err &amp;&amp; err.status === 404) { alert(&#39;oh no &#39; + res.body.message); } else if (err) { // all other error types we handle generically }</code></pre> <p>Alternatively, you can use the <code>.ok(callback)</code> method to decide whether a response is an error or not. The callback to the <code>ok</code> function gets a response and returns <code>true</code> if the response should be interpreted as success.</p> <pre><code>request.get(&#39;/404&#39;) .ok(res =&gt; res.status &lt; 500) .then(response =&gt; { // reads 404 page as a successful response })</code></pre> <h2 id="progress-tracking">Progress tracking</h2> <p>SuperAgent fires <code>progress</code> events on upload and download of large files.</p> <pre><code>request.post(url) .attach(&#39;field_name&#39;, file) .on(&#39;progress&#39;, event =&gt; { /* the event is: { direction: &quot;upload&quot; or &quot;download&quot; percent: 0 to 100 // may be missing if file size is unknown total: // total file size, may be missing loaded: // bytes downloaded or uploaded so far } */ }) .then()</code></pre> <h2 id="testing-on-localhost">Testing on localhost</h2> <h3 id="forcing-specific-connection-ip-address">Forcing specific connection IP address</h3> <p>In Node.js it&#39;s possible to ignore DNS resolution and direct all requests to a specific IP address using <code>.connect()</code> method. For example, this request will go to localhost instead of <code>example.com</code>:</p> <pre><code>const res = await request.get(&quot;path_to_url <p>Because the request may be redirected, it&#39;s possible to specify multiple hostnames and multiple IPs, as well as a special <code>*</code> as the fallback (note: other wildcards are not supported). The requests will keep their <code>Host</code> header with the original value. <code>.connect(undefined)</code> turns off the feature.</p> <pre><code>const res = await request.get(&quot;path_to_url .connect({ &quot;redir.example.com&quot;: &quot;127.0.0.1&quot;, // redir.example.com:555 will use 127.0.0.1:555 &quot;www.example.com&quot;: false, // don&#39;t override this one; use DNS as normal &quot;mapped.example.com&quot;: { host: &quot;127.0.0.1&quot;, port: 8080}, // mapped.example.com:* will use 127.0.0.1:8080 &quot;*&quot;: &quot;proxy.example.com&quot;, // all other requests will go to this host });</code></pre> <h3 id="ignoring-brokeninsecure-https-on-localhost">Ignoring broken/insecure HTTPS on localhost</h3> <p>In Node.js, when HTTPS is misconfigured and insecure (e.g. using self-signed certificate <em>without</em> specifying own <code>.ca()</code>), it&#39;s still possible to permit requests to <code>localhost</code> by calling <code>.trustLocalhost()</code>:</p> <pre><code>const res = await request.get(&quot;path_to_url <p>Together with <code>.connect(&quot;127.0.0.1&quot;)</code> this may be used to force HTTPS requests to any domain to be re-routed to <code>localhost</code> instead.</p> <p>It&#39;s generally safe to ignore broken HTTPS on <code>localhost</code>, because the loopback interface is not exposed to untrusted networks. Trusting <code>localhost</code> may become the default in the future. Use <code>.trustLocalhost(false)</code> to force check of <code>127.0.0.1</code>&#39;s authenticity.</p> <p>We intentionally don&#39;t support disabling of HTTPS security when making requests to any other IP, because such options end up abused as a quick &quot;fix&quot; for HTTPS problems. You can get free HTTPS certificates from <a href="path_to_url">Let&#39;s Encrypt</a> or set your own CA (<code>.ca(ca_public_pem)</code>) to make your self-signed certificates trusted.</p> <h2 id="promise-and-generator-support">Promise and Generator support</h2> <p>SuperAgent&#39;s request is a &quot;thenable&quot; object that&#39;s compatible with JavaScript promises and the <code>async</code>/<code>await</code> syntax.</p> <pre><code>const res = await request.get(url);</code></pre> <p>If you&#39;re using promises, <strong>do not</strong> call <code>.end()</code> or <code>.pipe()</code>. Any use of <code>.then()</code> or <code>await</code> disables all other ways of using the request.</p> <p>Libraries like <a href="path_to_url">co</a> or a web framework like <a href="path_to_url">koa</a> can <code>yield</code> on any SuperAgent method:</p> <pre><code>const req = request .get(&#39;path_to_url#39;) .auth(&#39;tobi&#39;, &#39;learnboost&#39;); const res = yield req;</code></pre> <p>Note that SuperAgent expects the global <code>Promise</code> object to be present. You&#39;ll need a polyfill to use promises in Internet Explorer or Node.js 0.10.</p> <h2 id="browser-and-node-versions">Browser and node versions</h2> <p>SuperAgent has two implementations: one for web browsers (using XHR) and one for Node.JS (using core http module). By default Browserify and WebPack will pick the browser version.</p> <p>If want to use WebPack to compile code for Node.JS, you <em>must</em> specify <a href="path_to_url#target">node target</a> in its configuration.</p> <h3 id="using-browser-version-in-electron">Using browser version in electron</h3> <p><a href="path_to_url">Electron</a> developers report if you would prefer to use the browser version of SuperAgent instead of the Node version, you can <code>require(&#39;superagent/superagent&#39;)</code>. Your requests will now show up in the Chrome developer tools Network tab. Note this environment is not covered by automated test suite and not officially supported.</p> </div> <a href="path_to_url"><img style="position: absolute; top: 0; right: 0; border: 0;" src="path_to_url" alt="Fork me on GitHub"></a> <script src="path_to_url"></script> <script> $('code').each(function(){ $(this).html(highlight($(this).text())); }); function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>') } </script> <script src="path_to_url"></script> <script> // Only use tocbot for main docs, not test docs if (document.querySelector('#superagent')) { tocbot.init({ // Where to render the table of contents. tocSelector: '#menu', // Where to grab the headings to build the table of contents. contentSelector: '#content', // Which headings to grab inside of the contentSelector element. headingSelector: 'h2', smoothScroll: false }); } </script> </body> </html> ```
/content/code_sandbox/node_modules/superagent/index.html
html
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
11,130
```javascript "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return obj !== null && _typeof(obj) === 'object'; } module.exports = isObject; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashPSBpc09iamVjdDtcbiJdfQ== ```
/content/code_sandbox/node_modules/superagent/lib/is-object.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
220
```javascript "use strict"; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Agent() { this._defaults = []; } ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) { // Default setting for all requests from this agent Agent.prototype[fn] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } this._defaults.push({ fn: fn, args: args }); return this; }; }); Agent.prototype._setDefaults = function (req) { this._defaults.forEach(function (def) { req[def.fn].apply(req, _toConsumableArray(def.args)); }); }; module.exports = Agent; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZHVsZS5leHBvcnRzID0gQWdlbnQ7XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/agent-base.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
733
```javascript "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { // Browser window root = window; } else if (typeof self === 'undefined') { // Other environments console.warn('Using browser-only version of superagent in non-browser environment'); root = void 0; } else { // Web Worker root = self; } var Emitter = require('component-emitter'); var safeStringify = require('fast-safe-stringify'); var qs = require('qs'); var RequestBase = require('./request-base'); var isObject = require('./is-object'); var ResponseBase = require('./response-base'); var Agent = require('./agent-base'); /** * Noop. */ function noop() {} /** * Expose `request`. */ module.exports = function (method, url) { // callback if (typeof url === 'function') { return new exports.Request('GET', method).end(url); } // url first if (arguments.length === 1) { return new exports.Request('GET', method); } return new exports.Request(method, url); }; exports = module.exports; var request = exports; exports.Request = Request; /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) { return new XMLHttpRequest(); } try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (_unused) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (_unused2) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (_unused3) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (_unused4) {} throw new Error('Browser-only version of superagent could not find XHR'); }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function (s) { return s.trim(); } : function (s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]); } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (val === undefined) return; if (val === null) { pairs.push(encodeURI(key)); return; } if (Array.isArray(val)) { val.forEach(function (v) { pushEncodedKeyValuePair(pairs, key, v); }); } else if (isObject(val)) { for (var subkey in val) { if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]); } } else { pairs.push(encodeURI(key) + '=' + encodeURIComponent(val)); } } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var pair; var pos; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; pos = pair.indexOf('='); if (pos === -1) { obj[decodeURIComponent(pair)] = ''; } else { obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); } } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'text/xml', urlencoded: 'application/x-www-form-urlencoded', form: 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': qs.stringify, 'application/json': safeStringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); if (index === -1) { // could be empty line, just skip it continue; } field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { // should match /json or +json // but not /json-seq return /[/+]json($|[^-\w])/i.test(mime); } /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req) { this.req = req; this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; var status = this.xhr.status; // handle IE9 bug: path_to_url if (status === 1223) { status = 204; } this._setStatusProperties(status); this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this._setHeaderProperties(this.header); if (this.text === null && req._responseType) { this.body = this.xhr.response; } else { this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); } } // eslint-disable-next-line new-cap ResponseBase(Response.prototype); /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype._parseBody = function (str) { var parse = request.parse[this.type]; if (this.req._parser) { return this.req._parser(this, str); } if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function () { var req = this.req; var method = req.method; var url = req.url; var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")"); var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; // preserves header name case this._header = {}; // coerces header names to lowercase this.on('end', function () { var err = null; var res = null; try { res = new Response(self); } catch (err_) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = err_; // issue #675: return the raw response if the response parsing fails if (self.xhr) { // ie9 doesn't have 'response' property err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails err.status = self.xhr.status ? self.xhr.status : null; err.statusCode = err.status; // backwards-compat only } else { err.rawResponse = null; err.status = null; } return self.callback(err); } self.emit('response', res); var new_err; try { if (!self._isResponseOK(res)) { new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); } } catch (err_) { new_err = err_; // ok() callback can throw } // #1000 don't catch errors from the callback to avoid double calling it if (new_err) { new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); } else { self.callback(null, res); } }); } /** * Mixin `Emitter` and `RequestBase`. */ // eslint-disable-next-line new-cap Emitter(Request.prototype); // eslint-disable-next-line new-cap RequestBase(Request.prototype); /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function (type) { this.set('Content-Type', request.types[type] || type); return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function (type) { this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} [pass] optional in case of using 'bearer' as type * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function (user, pass, options) { if (arguments.length === 1) pass = ''; if (_typeof(pass) === 'object' && pass !== null) { // pass is optional and can be replaced with options options = pass; pass = ''; } if (!options) { options = { type: typeof btoa === 'function' ? 'basic' : 'auto' }; } var encoder = function encoder(string) { if (typeof btoa === 'function') { return btoa(string); } throw new Error('Cannot use basic auth, btoa is not a function'); }; return this._auth(user, pass, options, encoder); }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function (val) { if (typeof val !== 'string') val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). * * ``` js * request.post('/upload') * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String|Object} options * @return {Request} for chaining * @api public */ Request.prototype.attach = function (field, file, options) { if (file) { if (this._data) { throw new Error("superagent can't mix .send() and .attach()"); } this._getFormData().append(field, file, options || file.name); } return this; }; Request.prototype._getFormData = function () { if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function (err, res) { if (this._shouldRetry(err, res)) { return this._retry(); } var fn = this._callback; this.clearTimeout(); if (err) { if (this._maxRetries) err.retries = this._retries - 1; this.emit('error', err); } fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function () { var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; // This only warns, because the request is still likely to work Request.prototype.agent = function () { console.warn('This is not supported in browser version of superagent'); return this; }; Request.prototype.ca = Request.prototype.agent; Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected Request.prototype.write = function () { throw new Error('Streaming is not supported in browser version of superagent'); }; Request.prototype.pipe = Request.prototype.write; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * @param {Object} obj host object * @return {Boolean} is a host object * @api private */ Request.prototype._isHost = function (obj) { // Native objects stringify to [object File], [object Blob], [object FormData], etc. return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function (fn) { if (this._endCalled) { console.warn('Warning: .end() was called twice. This is not supported in superagent'); } this._endCalled = true; // store callback this._callback = fn || noop; // querystring this._finalizeQueryString(); this._end(); }; Request.prototype._setUploadTimeout = function () { var self = this; // upload timeout it's wokrs only if deadline timeout is off if (this._uploadTimeout && !this._uploadTimeoutTimer) { this._uploadTimeoutTimer = setTimeout(function () { self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); }, this._uploadTimeout); } }; // eslint-disable-next-line complexity Request.prototype._end = function () { if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); var self = this; this.xhr = request.getXHR(); var xhr = this.xhr; var data = this._formData || this._data; this._setTimeouts(); // state change xhr.onreadystatechange = function () { var readyState = xhr.readyState; if (readyState >= 2 && self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer); } if (readyState !== 4) { return; } // In IE9, reads to any property (e.g. status) off of an aborted XHR will // result in the error "Could not complete the operation due to error c00c023f" var status; try { status = xhr.status; } catch (_unused5) { status = 0; } if (!status) { if (self.timedout || self._aborted) return; return self.crossDomainError(); } self.emit('end'); }; // progress var handleProgress = function handleProgress(direction, e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100; if (e.percent === 100) { clearTimeout(self._uploadTimeoutTimer); } } e.direction = direction; self.emit('progress', e); }; if (this.hasListeners('progress')) { try { xhr.addEventListener('progress', handleProgress.bind(null, 'download')); if (xhr.upload) { xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); } } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // path_to_url } } if (xhr.upload) { this._setUploadTimeout(); } // initiate request try { if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } } catch (err) { // see #1149 return this.callback(err); } // CORS if (this._withCredentials) xhr.withCredentials = true; // body if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { // serialize stuff var contentType = this._header['content-type']; var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!_serialize && isJSON(contentType)) { _serialize = request.serialize['application/json']; } if (_serialize) data = _serialize(data); } // set header fields for (var field in this.header) { if (this.header[field] === null) continue; if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } // send stuff this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) // We need null here if data is undefined xhr.send(typeof data === 'undefined' ? null : data); }; request.agent = function () { return new Agent(); }; ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) { Agent.prototype[method.toLowerCase()] = function (url, fn) { var req = new request.Request(method, url); this._setDefaults(req); if (fn) { req.end(fn); } return req; }; }); Agent.prototype.del = Agent.prototype.delete; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.get = function (url, data, fn) { var req = request('GET', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.head = function (url, data, fn) { var req = request('HEAD', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * OPTIONS query to `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.options = function (url, data, fn) { var req = request('OPTIONS', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ function del(url, data, fn) { var req = request('DELETE', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; } request.del = del; request.delete = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.patch = function (url, data, fn) { var req = request('PATCH', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.post = function (url, data, fn) { var req = request('POST', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.put = function (url, data, fn) { var req = request('PUT', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcGkgcHJpdmF0ZVxuICovXG5cbmNvbnN0IHRyaW0gPSAnJy50cmltID8gKHMpID0+IHMudHJpbSgpIDogKHMpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashICB9XG5cbiAgcmV0dXJuIHBhcnNlICYmIHN0ciAmJiAoc3RyLmxlbmd0aCA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashci5yZXNwb25zZVR5cGUgPT09ICd1bmRlZmluZWQnXG4gICAgICAgICAgICA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashPVwiYVwiPjxiIGlkPVwiYlwiPmhleSE8L2I+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZXRUaW1lb3V0KCgpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashIHB1YmxpY1xuICovXG5cbnJlcXVlc3QuZ2V0ID0gKHVybCwgZGF0YSwgZm4pID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashKi9cblxucmVxdWVzdC5vcHRpb25zID0gKHVybCwgZGF0YSwgZm4pID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbiAgaWYgKGZuKSByZXEuZW5kKGZuKTtcbiAgcmV0dXJuIHJlcTtcbn07XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/client.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,191
```javascript "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Module of mixed-in functions shared between node and client code */ var isObject = require('./is-object'); /** * Expose `RequestBase`. */ module.exports = RequestBase; /** * Initialize a new `RequestBase`. * * @api public */ function RequestBase(object) { if (object) return mixin(object); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(object) { for (var key in RequestBase.prototype) { if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) object[key] = RequestBase.prototype[key]; } return object; } /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ RequestBase.prototype.clearTimeout = function () { clearTimeout(this._timer); clearTimeout(this._responseTimeoutTimer); clearTimeout(this._uploadTimeoutTimer); delete this._timer; delete this._responseTimeoutTimer; delete this._uploadTimeoutTimer; return this; }; /** * Override default response body parser * * This function will be called to convert incoming data into request.body * * @param {Function} * @api public */ RequestBase.prototype.parse = function (fn) { this._parser = fn; return this; }; /** * Set format of binary response body. * In browser valid formats are 'blob' and 'arraybuffer', * which return Blob and ArrayBuffer, respectively. * * In Node all values result in Buffer. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.responseType = function (value) { this._responseType = value; return this; }; /** * Override default request body serializer * * This function will be called to convert data set via .send or .attach into payload to send * * @param {Function} * @api public */ RequestBase.prototype.serialize = function (fn) { this._serializer = fn; return this; }; /** * Set timeouts. * * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off * * Value of 0 or false means no timeout. * * @param {Number|Object} ms or {response, deadline} * @return {Request} for chaining * @api public */ RequestBase.prototype.timeout = function (options) { if (!options || _typeof(options) !== 'object') { this._timeout = options; this._responseTimeout = 0; this._uploadTimeout = 0; return this; } for (var option in options) { if (Object.prototype.hasOwnProperty.call(options, option)) { switch (option) { case 'deadline': this._timeout = options.deadline; break; case 'response': this._responseTimeout = options.response; break; case 'upload': this._uploadTimeout = options.upload; break; default: console.warn('Unknown timeout option', option); } } } return this; }; /** * Set number of retry attempts on error. * * Failed requests will be retried 'count' times if timeout or err.code >= 500. * * @param {Number} count * @param {Function} [fn] * @return {Request} for chaining * @api public */ RequestBase.prototype.retry = function (count, fn) { // Default to 1 if no count passed or true if (arguments.length === 0 || count === true) count = 1; if (count <= 0) count = 0; this._maxRetries = count; this._retries = 0; this._retryCallback = fn; return this; }; // // NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package // <path_to_url // // NOTE: we do not include EADDRINFO because it was removed from libuv in 2014 // <path_to_url // <path_to_url // // // TODO: expose these as configurable defaults // var ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); var STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) // const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); /** * Determine if a request should be retried. * (Inspired by path_to_url#retry) * * @param {Error} err an error * @param {Response} [res] response * @returns {Boolean} if segment should be retried */ RequestBase.prototype._shouldRetry = function (err, res) { if (!this._maxRetries || this._retries++ >= this._maxRetries) { return false; } if (this._retryCallback) { try { var override = this._retryCallback(err, res); if (override === true) return true; if (override === false) return false; // undefined falls back to defaults } catch (err_) { console.error(err_); } } // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) /* if ( this.req && this.req.method && !METHODS.has(this.req.method.toUpperCase()) ) return false; */ if (res && res.status && STATUS_CODES.has(res.status)) return true; if (err) { if (err.code && ERROR_CODES.has(err.code)) return true; // Superagent timeout if (err.timeout && err.code === 'ECONNABORTED') return true; if (err.crossDomain) return true; } return false; }; /** * Retry request * * @return {Request} for chaining * @api private */ RequestBase.prototype._retry = function () { this.clearTimeout(); // node if (this.req) { this.req = null; this.req = this.request(); } this._aborted = false; this.timedout = false; this.timedoutError = null; return this._end(); }; /** * Promise support * * @param {Function} resolve * @param {Function} [reject] * @return {Request} */ RequestBase.prototype.then = function (resolve, reject) { var _this = this; if (!this._fullfilledPromise) { var self = this; if (this._endCalled) { console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); } this._fullfilledPromise = new Promise(function (resolve, reject) { self.on('abort', function () { if (_this._maxRetries && _this._maxRetries > _this._retries) { return; } if (_this.timedout && _this.timedoutError) { reject(_this.timedoutError); return; } var err = new Error('Aborted'); err.code = 'ABORTED'; err.status = _this.status; err.method = _this.method; err.url = _this.url; reject(err); }); self.end(function (err, res) { if (err) reject(err);else resolve(res); }); }); } return this._fullfilledPromise.then(resolve, reject); }; RequestBase.prototype.catch = function (cb) { return this.then(undefined, cb); }; /** * Allow for extension */ RequestBase.prototype.use = function (fn) { fn(this); return this; }; RequestBase.prototype.ok = function (cb) { if (typeof cb !== 'function') throw new Error('Callback required'); this._okCallback = cb; return this; }; RequestBase.prototype._isResponseOK = function (res) { if (!res) { return false; } if (this._okCallback) { return this._okCallback(res); } return res.status >= 200 && res.status < 300; }; /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ RequestBase.prototype.get = function (field) { return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ RequestBase.prototype.getHeader = RequestBase.prototype.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.set = function (field, value) { if (isObject(field)) { for (var key in field) { if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = value; this.header[field] = value; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field field name */ RequestBase.prototype.unset = function (field) { delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val`, or multiple fields with one object * for "multipart/form-data" request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * * request.post('/upload') * .field({ foo: 'bar', baz: 'qux' }) * .end(callback); * ``` * * @param {String|Object} name name of field * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field * @return {Request} for chaining * @api public */ RequestBase.prototype.field = function (name, value) { // name should be either a string or an object. if (name === null || undefined === name) { throw new Error('.field(name, val) name can not be empty'); } if (this._data) { throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); } if (isObject(name)) { for (var key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]); } return this; } if (Array.isArray(value)) { for (var i in value) { if (Object.prototype.hasOwnProperty.call(value, i)) this.field(name, value[i]); } return this; } // val should be defined now if (value === null || undefined === value) { throw new Error('.field(name, val) val can not be empty'); } if (typeof value === 'boolean') { value = String(value); } this._getFormData().append(name, value); return this; }; /** * Abort the request, and clear potential timeout. * * @return {Request} request * @api public */ RequestBase.prototype.abort = function () { if (this._aborted) { return this; } this._aborted = true; if (this.xhr) this.xhr.abort(); // browser if (this.req) this.req.abort(); // node this.clearTimeout(); this.emit('abort'); return this; }; RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { switch (options.type) { case 'basic': this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass)))); break; case 'auto': this.username = user; this.password = pass; break; case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) this.set('Authorization', "Bearer ".concat(user)); break; default: break; } return this; }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ RequestBase.prototype.withCredentials = function (on) { // This is browser-only functionality. Node side is no-op. if (on === undefined) on = true; this._withCredentials = on; return this; }; /** * Set the max redirects to `n`. Does nothing in browser XHR implementation. * * @param {Number} n * @return {Request} for chaining * @api public */ RequestBase.prototype.redirects = function (n) { this._maxRedirects = n; return this; }; /** * Maximum size of buffered response body, in bytes. Counts uncompressed size. * Default 200MB. * * @param {Number} n number of bytes * @return {Request} for chaining */ RequestBase.prototype.maxResponseSize = function (n) { if (typeof n !== 'number') { throw new TypeError('Invalid argument'); } this._maxResponseSize = n; return this; }; /** * Convert to a plain javascript object (not JSON string) of scalar properties. * Note as this method is designed to return a useful non-this value, * it cannot be chained. * * @return {Object} describing method, url, and data of this request * @api public */ RequestBase.prototype.toJSON = function () { return { method: this.method, url: this.url, data: this._data, headers: this._header }; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * // manual json * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * // auto json * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * // manual x-www-form-urlencoded * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * // auto x-www-form-urlencoded * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * // defaults to x-www-form-urlencoded * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ // eslint-disable-next-line complexity RequestBase.prototype.send = function (data) { var isObject_ = isObject(data); var type = this._header['content-type']; if (this._formData) { throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); } if (isObject_ && !this._data) { if (Array.isArray(data)) { this._data = []; } else if (!this._isHost(data)) { this._data = {}; } } else if (data && this._data && this._isHost(this._data)) { throw new Error("Can't merge these send calls"); } // merge if (isObject_ && isObject(this._data)) { for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key]; } } else if (typeof data === 'string') { // default to x-www-form-urlencoded if (!type) this.type('form'); type = this._header['content-type']; if (type) type = type.toLowerCase().trim(); if (type === 'application/x-www-form-urlencoded') { this._data = this._data ? "".concat(this._data, "&").concat(data) : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!isObject_ || this._isHost(data)) { return this; } // default to json if (!type) this.type('json'); return this; }; /** * Sort `querystring` by the sort function * * * Examples: * * // default order * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery() * .end(callback) * * // customized sort function * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery(function(a, b){ * return a.length - b.length; * }) * .end(callback) * * * @param {Function} sort * @return {Request} for chaining * @api public */ RequestBase.prototype.sortQuery = function (sort) { // _sort default to true but otherwise can be a function or boolean this._sort = typeof sort === 'undefined' ? true : sort; return this; }; /** * Compose querystring to append to req.url * * @api private */ RequestBase.prototype._finalizeQueryString = function () { var query = this._query.join('&'); if (query) { this.url += (this.url.includes('?') ? '&' : '?') + query; } this._query.length = 0; // Makes the call idempotent if (this._sort) { var index = this.url.indexOf('?'); if (index >= 0) { var queryArray = this.url.slice(index + 1).split('&'); if (typeof this._sort === 'function') { queryArray.sort(this._sort); } else { queryArray.sort(); } this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); } } }; // For backwards compat only RequestBase.prototype._appendQueryString = function () { console.warn('Unsupported'); }; /** * Invoke callback with timeout error. * * @api private */ RequestBase.prototype._timeoutError = function (reason, timeout, errno) { if (this._aborted) { return; } var err = new Error("".concat(reason + timeout, "ms exceeded")); err.timeout = timeout; err.code = 'ECONNABORTED'; err.errno = errno; this.timedout = true; this.timedoutError = err; this.abort(); this.callback(err); }; RequestBase.prototype._setTimeouts = function () { var self = this; // deadline if (this._timeout && !this._timer) { this._timer = setTimeout(function () { self._timeoutError('Timeout of ', self._timeout, 'ETIME'); }, this._timeout); } // response timeout if (this._responseTimeout && !this._responseTimeoutTimer) { this._responseTimeoutTimer = setTimeout(function () { self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); }, this._responseTimeout); } }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbmRyZXNvcmh1cy9nb3QvcHVsbC81Mzc+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashX3JldHJpZXMrKyA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcy5fc29ydCA9IHR5cGVvZiBzb3J0ID09PSAndW5kZWZpbmVkJyA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbCArPSAodGhpcy51cmwuaW5jbHVkZXMoJz8nKSA/ICcmJyA6ICc/your_sha256_hashyour_sha256_hashyour_sha256_hashIGlmIChpbmRleCA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashaWNlKDAsIGluZGV4KSArICc/your_sha256_hashyour_sha256_hashLl9hcHBlbmRRdWVyeVN0cmluZyA9ICgpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashb3V0KCgpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashb25zZVRpbWVvdXQpO1xuICB9XG59O1xuIl19 ```
/content/code_sandbox/node_modules/superagent/lib/request-base.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
7,682
```javascript "use strict"; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var Stream = require('stream'); var util = require('util'); var net = require('net'); var tls = require('tls'); // eslint-disable-next-line node/no-deprecated-api var _require = require('url'), parse = _require.parse; var semver = require('semver'); var http2; // eslint-disable-next-line node/no-unsupported-features/node-builtins if (semver.gte(process.version, 'v10.10.0')) http2 = require('http2');else throw new Error('superagent: this version of Node.js does not support http2'); var _http2$constants = http2.constants, HTTP2_HEADER_PATH = _http2$constants.HTTP2_HEADER_PATH, HTTP2_HEADER_STATUS = _http2$constants.HTTP2_HEADER_STATUS, HTTP2_HEADER_METHOD = _http2$constants.HTTP2_HEADER_METHOD, HTTP2_HEADER_AUTHORITY = _http2$constants.HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_HOST = _http2$constants.HTTP2_HEADER_HOST, HTTP2_HEADER_SET_COOKIE = _http2$constants.HTTP2_HEADER_SET_COOKIE, NGHTTP2_CANCEL = _http2$constants.NGHTTP2_CANCEL; function setProtocol(protocol) { return { request: function request(options) { return new Request(protocol, options); } }; } function Request(protocol, options) { var _this = this; Stream.call(this); var defaultPort = protocol === 'https:' ? 443 : 80; var defaultHost = 'localhost'; var port = options.port || defaultPort; var host = options.host || defaultHost; delete options.port; delete options.host; this.method = options.method; this.path = options.path; this.protocol = protocol; this.host = host; delete options.method; delete options.path; var sessionOptions = _objectSpread({}, options); if (options.socketPath) { sessionOptions.socketPath = options.socketPath; sessionOptions.createConnection = this.createUnixConnection.bind(this); } this._headers = {}; var session = http2.connect("".concat(protocol, "//").concat(host, ":").concat(port), sessionOptions); this.setHeader('host', "".concat(host, ":").concat(port)); session.on('error', function (err) { return _this.emit('error', err); }); this.session = session; } /** * Inherit from `Stream` (which inherits from `EventEmitter`). */ util.inherits(Request, Stream); Request.prototype.createUnixConnection = function (authority, options) { switch (this.protocol) { case 'http:': return net.connect(options.socketPath); case 'https:': options.ALPNProtocols = ['h2']; options.servername = this.host; options.allowHalfOpen = true; return tls.connect(options.socketPath, options); default: throw new Error('Unsupported protocol', this.protocol); } }; // eslint-disable-next-line no-unused-vars Request.prototype.setNoDelay = function (bool) {// We can not use setNoDelay with HTTP/2. // Node 10 limits http2session.socket methods to ones safe to use with HTTP/2. // See also path_to_url#http2_http2session_socket }; Request.prototype.getFrame = function () { var _method, _this2 = this; if (this.frame) { return this.frame; } var method = (_method = {}, _defineProperty(_method, HTTP2_HEADER_PATH, this.path), _defineProperty(_method, HTTP2_HEADER_METHOD, this.method), _method); var headers = this.mapToHttp2Header(this._headers); headers = Object.assign(headers, method); var frame = this.session.request(headers); // eslint-disable-next-line no-unused-vars frame.once('response', function (headers, flags) { headers = _this2.mapToHttpHeader(headers); frame.headers = headers; frame.statusCode = headers[HTTP2_HEADER_STATUS]; frame.status = frame.statusCode; _this2.emit('response', frame); }); this._headerSent = true; frame.once('drain', function () { return _this2.emit('drain'); }); frame.on('error', function (err) { return _this2.emit('error', err); }); frame.on('close', function () { return _this2.session.close(); }); this.frame = frame; return frame; }; Request.prototype.mapToHttpHeader = function (headers) { var keys = Object.keys(headers); var http2Headers = {}; for (var _i = 0, _keys = keys; _i < _keys.length; _i++) { var key = _keys[_i]; var value = headers[key]; key = key.toLowerCase(); switch (key) { case HTTP2_HEADER_SET_COOKIE: value = Array.isArray(value) ? value : [value]; break; default: break; } http2Headers[key] = value; } return http2Headers; }; Request.prototype.mapToHttp2Header = function (headers) { var keys = Object.keys(headers); var http2Headers = {}; for (var _i2 = 0, _keys2 = keys; _i2 < _keys2.length; _i2++) { var key = _keys2[_i2]; var value = headers[key]; key = key.toLowerCase(); switch (key) { case HTTP2_HEADER_HOST: key = HTTP2_HEADER_AUTHORITY; value = /^http:\/\/|^https:\/\//.test(value) ? parse(value).host : value; break; default: break; } http2Headers[key] = value; } return http2Headers; }; Request.prototype.setHeader = function (name, value) { this._headers[name.toLowerCase()] = value; }; Request.prototype.getHeader = function (name) { return this._headers[name.toLowerCase()]; }; Request.prototype.write = function (data, encoding) { var frame = this.getFrame(); return frame.write(data, encoding); }; Request.prototype.pipe = function (stream, options) { var frame = this.getFrame(); return frame.pipe(stream, options); }; Request.prototype.end = function (data) { var frame = this.getFrame(); frame.end(data); }; // eslint-disable-next-line no-unused-vars Request.prototype.abort = function (data) { var frame = this.getFrame(); frame.close(NGHTTP2_CANCEL); this.session.destroy(); }; exports.setProtocol = setProtocol; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashdWUgPSBBcnJheS5pc0FycmF5KHZhbHVlKSA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashfQ== ```
/content/code_sandbox/node_modules/superagent/lib/node/http2wrapper.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,705
```javascript "use strict"; /** * Module dependencies. */ var util = require('util'); var Stream = require('stream'); var ResponseBase = require('../response-base'); /** * Expose `Response`. */ module.exports = Response; /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * @param {Request} req * @param {Object} options * @constructor * @extends {Stream} * @implements {ReadableStream} * @api private */ function Response(req) { Stream.call(this); this.res = req.res; var res = this.res; this.request = req; this.req = req.req; this.text = res.text; this.body = res.body === undefined ? {} : res.body; this.files = res.files || {}; this.buffered = req._resBuffered; this.headers = res.headers; this.header = this.headers; this._setStatusProperties(res.statusCode); this._setHeaderProperties(this.header); this.setEncoding = res.setEncoding.bind(res); res.on('data', this.emit.bind(this, 'data')); res.on('end', this.emit.bind(this, 'end')); res.on('close', this.emit.bind(this, 'close')); res.on('error', this.emit.bind(this, 'error')); } /** * Inherit from `Stream`. */ util.inherits(Response, Stream); // eslint-disable-next-line new-cap ResponseBase(Response.prototype); /** * Implements methods of a `ReadableStream` */ Response.prototype.destroy = function (err) { this.res.destroy(err); }; /** * Pause. */ Response.prototype.pause = function () { this.res.pause(); }; /** * Resume. */ Response.prototype.resume = function () { this.res.resume(); }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function () { var req = this.req; var method = req.method; var path = req.path; var msg = "cannot ".concat(method, " ").concat(path, " (").concat(this.status, ")"); var err = new Error(msg); err.status = this.status; err.text = this.text; err.method = method; err.path = path; return err; }; Response.prototype.setStatusProperties = function (status) { console.warn('In superagent 2.x setStatusProperties is a private method'); return this._setStatusProperties(status); }; /** * To json. * * @return {Object} * @api public */ Response.prototype.toJSON = function () { return { req: this.request.toJSON(), header: this.header, status: this.status, text: this.text }; }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashICB0ZXh0OiB0aGlzLnRleHRcbiAgfTtcbn07XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/node/response.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,105
```javascript "use strict"; /** * Module dependencies. */ var _require = require('string_decoder'), StringDecoder = _require.StringDecoder; var Stream = require('stream'); var zlib = require('zlib'); /** * Buffers response data events and re-emits when they're unzipped. * * @param {Request} req * @param {Response} res * @api private */ exports.unzip = function (req, res) { var unzip = zlib.createUnzip(); var stream = new Stream(); var decoder; // make node responseOnEnd() happy stream.req = req; unzip.on('error', function (err) { if (err && err.code === 'Z_BUF_ERROR') { // unexpected end of file is ignored by browsers and curl stream.emit('end'); return; } stream.emit('error', err); }); // pipe to unzip res.pipe(unzip); // override `setEncoding` to capture encoding res.setEncoding = function (type) { decoder = new StringDecoder(type); }; // decode upon decompressing with captured encoding unzip.on('data', function (buf) { if (decoder) { var str = decoder.write(buf); if (str.length > 0) stream.emit('data', str); } else { stream.emit('data', buf); } }); unzip.on('end', function () { stream.emit('end'); }); // override `on` to capture data listeners var _on = res.on; res.on = function (type, fn) { if (type === 'data' || type === 'end') { stream.on(type, fn.bind(res)); } else if (type === 'error') { stream.on(type, fn.bind(res)); _on.call(res, type, fn); } else { _on.call(res, type, fn); } return this; }; }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYScsIChidWYpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashO1xuICAgIH1cblxuICAgIHJldHVybiB0aGlzO1xuICB9O1xufTtcbiJdfQ== ```
/content/code_sandbox/node_modules/superagent/lib/node/unzip.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
789
```javascript "use strict"; /** * Module dependencies. */ // eslint-disable-next-line node/no-deprecated-api var _require = require('url'), parse = _require.parse; var _require2 = require('cookiejar'), CookieJar = _require2.CookieJar; var _require3 = require('cookiejar'), CookieAccessInfo = _require3.CookieAccessInfo; var methods = require('methods'); var request = require('../..'); var AgentBase = require('../agent-base'); /** * Expose `Agent`. */ module.exports = Agent; /** * Initialize a new `Agent`. * * @api public */ function Agent(options) { if (!(this instanceof Agent)) { return new Agent(options); } AgentBase.call(this); this.jar = new CookieJar(); if (options) { if (options.ca) { this.ca(options.ca); } if (options.key) { this.key(options.key); } if (options.pfx) { this.pfx(options.pfx); } if (options.cert) { this.cert(options.cert); } if (options.rejectUnauthorized === false) { this.disableTLSCerts(); } } } Agent.prototype = Object.create(AgentBase.prototype); /** * Save the cookies in the given `res` to * the agent's cookie jar for persistence. * * @param {Response} res * @api private */ Agent.prototype._saveCookies = function (res) { var cookies = res.headers['set-cookie']; if (cookies) this.jar.setCookies(cookies); }; /** * Attach cookies when available to the given `req`. * * @param {Request} req * @api private */ Agent.prototype._attachCookies = function (req) { var url = parse(req.url); var access = new CookieAccessInfo(url.hostname, url.pathname, url.protocol === 'https:'); var cookies = this.jar.getCookies(access).toValueString(); req.cookies = cookies; }; methods.forEach(function (name) { var method = name.toUpperCase(); Agent.prototype[name] = function (url, fn) { var req = new request.Request(method, url); req.on('response', this._saveCookies.bind(this)); req.on('redirect', this._saveCookies.bind(this)); req.on('redirect', this._attachCookies.bind(this, req)); this._setDefaults(req); this._attachCookies(req); if (fn) { req.end(fn); } return req; }; }); Agent.prototype.del = Agent.prototype.delete; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLmZvckVhY2goKG5hbWUpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcm90b3R5cGUuZGVsZXRlO1xuIl19 ```
/content/code_sandbox/node_modules/superagent/lib/node/agent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,024
```javascript "use strict"; exports['application/x-www-form-urlencoded'] = require('./urlencoded'); exports['application/json'] = require('./json'); exports.text = require('./text'); var binary = require('./image'); exports['application/octet-stream'] = binary; exports['application/pdf'] = binary; exports.image = binary; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYmluYXJ5O1xuIl19 ```
/content/code_sandbox/node_modules/superagent/lib/node/parsers/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
154
```javascript "use strict"; module.exports = function (res, fn) { res.text = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { res.text += chunk; }); res.on('end', function () { var body; var err; try { body = res.text && JSON.parse(res.text); } catch (err_) { err = err_; // issue #675: return the raw response if the response parsing fails err.rawResponse = res.text || null; // issue #876: return the http status code if the response parsing fails err.statusCode = res.statusCode; } finally { fn(err, body); } }); }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcmVzLnRleHQgKz0gY2h1bms7XG4gIH0pO1xuICByZXMub24oJ2VuZCcsICgpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hash ```
/content/code_sandbox/node_modules/superagent/lib/node/parsers/json.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
337
```javascript "use strict"; module.exports = function (res, fn) { var data = []; // Binary data needs binary storage res.on('data', function (chunk) { data.push(chunk); }); res.on('end', function () { fn(null, Buffer.concat(data)); }); }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashJ2RhdGEnLCAoY2h1bmspID0+your_sha256_hashyour_sha256_hashIH0pO1xufTtcbiJdfQ== ```
/content/code_sandbox/node_modules/superagent/lib/node/parsers/image.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
170
```javascript "use strict"; module.exports = function (res, fn) { res.text = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { res.text += chunk; }); res.on('end', fn); }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZCcsIGZuKTtcbn07XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/node/parsers/text.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
138
```javascript "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Module dependencies. */ // eslint-disable-next-line node/no-deprecated-api var _require = require('url'), parse = _require.parse, format = _require.format, resolve = _require.resolve; var Stream = require('stream'); var https = require('https'); var http = require('http'); var fs = require('fs'); var zlib = require('zlib'); var util = require('util'); var qs = require('qs'); var mime = require('mime'); var methods = require('methods'); var FormData = require('form-data'); var formidable = require('formidable'); var debug = require('debug')('superagent'); var CookieJar = require('cookiejar'); var semver = require('semver'); var safeStringify = require('fast-safe-stringify'); var utils = require('../utils'); var RequestBase = require('../request-base'); var _require2 = require('./unzip'), unzip = _require2.unzip; var Response = require('./response'); var http2; if (semver.gte(process.version, 'v10.10.0')) http2 = require('./http2wrapper'); function request(method, url) { // callback if (typeof url === 'function') { return new exports.Request('GET', method).end(url); } // url first if (arguments.length === 1) { return new exports.Request('GET', method); } return new exports.Request(method, url); } module.exports = request; exports = module.exports; /** * Expose `Request`. */ exports.Request = Request; /** * Expose the agent function */ exports.agent = require('./agent'); /** * Noop. */ function noop() {} /** * Expose `Response`. */ exports.Response = Response; /** * Define "form" mime type. */ mime.define({ 'application/x-www-form-urlencoded': ['form', 'urlencoded', 'form-data'] }, true); /** * Protocol map. */ exports.protocols = { 'http:': http, 'https:': https, 'http2:': http2 }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ exports.serialize = { 'application/x-www-form-urlencoded': qs.stringify, 'application/json': safeStringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(res, fn){ * fn(null, res); * }; * */ exports.parse = require('./parsers'); /** * Default buffering map. Can be used to set certain * response types to buffer/not buffer. * * superagent.buffer['application/xml'] = true; */ exports.buffer = {}; /** * Initialize internal header tracking properties on a request instance. * * @param {Object} req the instance * @api private */ function _initHeaders(req) { req._header = {// coerces header names to lowercase }; req.header = {// preserves header name case }; } /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String|Object} url * @api public */ function Request(method, url) { Stream.call(this); if (typeof url !== 'string') url = format(url); this._enableHttp2 = Boolean(process.env.HTTP2_TEST); // internal only this._agent = false; this._formData = null; this.method = method; this.url = url; _initHeaders(this); this.writable = true; this._redirects = 0; this.redirects(method === 'HEAD' ? 0 : 5); this.cookies = ''; this.qs = {}; this._query = []; this.qsRaw = this._query; // Unused, for backwards compatibility only this._redirectList = []; this._streamRequest = false; this.once('end', this.clearTimeout.bind(this)); } /** * Inherit from `Stream` (which inherits from `EventEmitter`). * Mixin `RequestBase`. */ util.inherits(Request, Stream); // eslint-disable-next-line new-cap RequestBase(Request.prototype); /** * Enable or Disable http2. * * Enable http2. * * ``` js * request.get('path_to_url * .http2() * .end(callback); * * request.get('path_to_url * .http2(true) * .end(callback); * ``` * * Disable http2. * * ``` js * request = request.http2(); * request.get('path_to_url * .http2(false) * .end(callback); * ``` * * @param {Boolean} enable * @return {Request} for chaining * @api public */ Request.prototype.http2 = function (bool) { if (exports.protocols['http2:'] === undefined) { throw new Error('superagent: this version of Node.js does not support http2'); } this._enableHttp2 = bool === undefined ? true : bool; return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). * * ``` js * request.post('path_to_url * .attach('field', Buffer.from('<b>Hello world</b>'), 'hello.html') * .end(callback); * ``` * * A filename may also be used: * * ``` js * request.post('path_to_url * .attach('files', 'image.jpg') * .end(callback); * ``` * * @param {String} field * @param {String|fs.ReadStream|Buffer} file * @param {String|Object} options * @return {Request} for chaining * @api public */ Request.prototype.attach = function (field, file, options) { if (file) { if (this._data) { throw new Error("superagent can't mix .send() and .attach()"); } var o = options || {}; if (typeof options === 'string') { o = { filename: options }; } if (typeof file === 'string') { if (!o.filename) o.filename = file; debug('creating `fs.ReadStream` instance for file: %s', file); file = fs.createReadStream(file); } else if (!o.filename && file.path) { o.filename = file.path; } this._getFormData().append(field, file, o); } return this; }; Request.prototype._getFormData = function () { var _this = this; if (!this._formData) { this._formData = new FormData(); this._formData.on('error', function (err) { debug('FormData error', err); if (_this.called) { // The request has already finished and the callback was called. // Silently ignore the error. return; } _this.callback(err); _this.abort(); }); } return this._formData; }; /** * Gets/sets the `Agent` to use for this HTTP request. The default (if this * function is not called) is to opt out of connection pooling (`agent: false`). * * @param {http.Agent} agent * @return {http.Agent} * @api public */ Request.prototype.agent = function (agent) { if (arguments.length === 0) return this._agent; this._agent = agent; return this; }; /** * Set _Content-Type_ response header passed through `mime.getType()`. * * Examples: * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('json') * .send(jsonstring) * .end(callback); * * request.post('/') * .type('application/json') * .send(jsonstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function (type) { return this.set('Content-Type', type.includes('/') ? type : mime.getType(type)); }; /** * Set _Accept_ response header passed through `mime.getType()`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function (type) { return this.set('Accept', type.includes('/') ? type : mime.getType(type)); }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function (val) { if (typeof val === 'string') { this._query.push(val); } else { Object.assign(this.qs, val); } return this; }; /** * Write raw `data` / `encoding` to the socket. * * @param {Buffer|String} data * @param {String} encoding * @return {Boolean} * @api public */ Request.prototype.write = function (data, encoding) { var req = this.request(); if (!this._streamRequest) { this._streamRequest = true; } return req.write(data, encoding); }; /** * Pipe the request body to `stream`. * * @param {Stream} stream * @param {Object} options * @return {Stream} * @api public */ Request.prototype.pipe = function (stream, options) { this.piped = true; // HACK... this.buffer(false); this.end(); return this._pipeContinue(stream, options); }; Request.prototype._pipeContinue = function (stream, options) { var _this2 = this; this.req.once('response', function (res) { // redirect if (isRedirect(res.statusCode) && _this2._redirects++ !== _this2._maxRedirects) { return _this2._redirect(res) === _this2 ? _this2._pipeContinue(stream, options) : undefined; } _this2.res = res; _this2._emitResponse(); if (_this2._aborted) return; if (_this2._shouldUnzip(res)) { var unzipObj = zlib.createUnzip(); unzipObj.on('error', function (err) { if (err && err.code === 'Z_BUF_ERROR') { // unexpected end of file is ignored by browsers and curl stream.emit('end'); return; } stream.emit('error', err); }); res.pipe(unzipObj).pipe(stream, options); } else { res.pipe(stream, options); } res.once('end', function () { _this2.emit('end'); }); }); return stream; }; /** * Enable / disable buffering. * * @return {Boolean} [val] * @return {Request} for chaining * @api public */ Request.prototype.buffer = function (val) { this._buffer = val !== false; return this; }; /** * Redirect to `url * * @param {IncomingMessage} res * @return {Request} for chaining * @api private */ Request.prototype._redirect = function (res) { var url = res.headers.location; if (!url) { return this.callback(new Error('No location header for redirect'), res); } debug('redirect %s -> %s', this.url, url); // location url = resolve(this.url, url); // ensure the response is being consumed // this is required for Node v0.10+ res.resume(); var headers = this.req.getHeaders ? this.req.getHeaders() : this.req._headers; var changesOrigin = parse(url).host !== parse(this.url).host; // implementation of 302 following defacto standard if (res.statusCode === 301 || res.statusCode === 302) { // strip Content-* related fields // in case of POST etc headers = utils.cleanHeader(headers, changesOrigin); // force GET this.method = this.method === 'HEAD' ? 'HEAD' : 'GET'; // clear data this._data = null; } // 303 is always GET if (res.statusCode === 303) { // strip Content-* related fields // in case of POST etc headers = utils.cleanHeader(headers, changesOrigin); // force method this.method = 'GET'; // clear data this._data = null; } // 307 preserves method // 308 preserves method delete headers.host; delete this.req; delete this._formData; // remove all add header except User-Agent _initHeaders(this); // redirect this._endCalled = false; this.url = url; this.qs = {}; this._query.length = 0; this.set(headers); this.emit('redirect', res); this._redirectList.push(this.url); this.end(this._callback); return this; }; /** * Set Authorization field value with `user` and `pass`. * * Examples: * * .auth('tobi', 'learnboost') * .auth('tobi:learnboost') * .auth('tobi') * .auth(accessToken, { type: 'bearer' }) * * @param {String} user * @param {String} [pass] * @param {Object} [options] options with authorization type 'basic' or 'bearer' ('basic' is default) * @return {Request} for chaining * @api public */ Request.prototype.auth = function (user, pass, options) { if (arguments.length === 1) pass = ''; if (_typeof(pass) === 'object' && pass !== null) { // pass is optional and can be replaced with options options = pass; pass = ''; } if (!options) { options = { type: 'basic' }; } var encoder = function encoder(string) { return Buffer.from(string).toString('base64'); }; return this._auth(user, pass, options, encoder); }; /** * Set the certificate authority option for https request. * * @param {Buffer | Array} cert * @return {Request} for chaining * @api public */ Request.prototype.ca = function (cert) { this._ca = cert; return this; }; /** * Set the client certificate key option for https request. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.key = function (cert) { this._key = cert; return this; }; /** * Set the key, certificate, and CA certs of the client in PFX or PKCS12 format. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.pfx = function (cert) { if (_typeof(cert) === 'object' && !Buffer.isBuffer(cert)) { this._pfx = cert.pfx; this._passphrase = cert.passphrase; } else { this._pfx = cert; } return this; }; /** * Set the client certificate option for https request. * * @param {Buffer | String} cert * @return {Request} for chaining * @api public */ Request.prototype.cert = function (cert) { this._cert = cert; return this; }; /** * Do not reject expired or invalid TLS certs. * sets `rejectUnauthorized=true`. Be warned that this allows MITM attacks. * * @return {Request} for chaining * @api public */ Request.prototype.disableTLSCerts = function () { this._disableTLSCerts = true; return this; }; /** * Return an http[s] request. * * @return {OutgoingMessage} * @api private */ // eslint-disable-next-line complexity Request.prototype.request = function () { var _this3 = this; if (this.req) return this.req; var options = {}; try { var query = qs.stringify(this.qs, { indices: false, strictNullHandling: true }); if (query) { this.qs = {}; this._query.push(query); } this._finalizeQueryString(); } catch (err) { return this.emit('error', err); } var url = this.url; var retries = this._retries; // Capture backticks as-is from the final query string built above. // Note: this'll only find backticks entered in req.query(String) // calls, because qs.stringify unconditionally encodes backticks. var queryStringBackticks; if (url.includes('`')) { var queryStartIndex = url.indexOf('?'); if (queryStartIndex !== -1) { var queryString = url.slice(queryStartIndex + 1); queryStringBackticks = queryString.match(/`|%60/g); } } // default to http:// if (url.indexOf('http') !== 0) url = "http://".concat(url); url = parse(url); // See path_to_url if (queryStringBackticks) { var i = 0; url.query = url.query.replace(/%60/g, function () { return queryStringBackticks[i++]; }); url.search = "?".concat(url.query); url.path = url.pathname + url.search; } // support unix sockets if (/^https?\+unix:/.test(url.protocol) === true) { // get the protocol url.protocol = "".concat(url.protocol.split('+')[0], ":"); // get the socket, path var unixParts = url.path.match(/^([^/]+)(.+)$/); options.socketPath = unixParts[1].replace(/%2F/g, '/'); url.path = unixParts[2]; } // Override IP address of a hostname if (this._connectOverride) { var _url = url, hostname = _url.hostname; var match = hostname in this._connectOverride ? this._connectOverride[hostname] : this._connectOverride['*']; if (match) { // backup the real host if (!this._header.host) { this.set('host', url.host); } var newHost; var newPort; if (_typeof(match) === 'object') { newHost = match.host; newPort = match.port; } else { newHost = match; newPort = url.port; } // wrap [ipv6] url.host = /:/.test(newHost) ? "[".concat(newHost, "]") : newHost; if (newPort) { url.host += ":".concat(newPort); url.port = newPort; } url.hostname = newHost; } } // options options.method = this.method; options.port = url.port; options.path = url.path; options.host = url.hostname; options.ca = this._ca; options.key = this._key; options.pfx = this._pfx; options.cert = this._cert; options.passphrase = this._passphrase; options.agent = this._agent; options.rejectUnauthorized = typeof this._disableTLSCerts === 'boolean' ? !this._disableTLSCerts : process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; // Allows request.get('path_to_url 'example.com') if (this._header.host) { options.servername = this._header.host.replace(/:\d+$/, ''); } if (this._trustLocalhost && /^(?:localhost|127\.0\.0\.\d+|(0*:)+:0*1)$/.test(url.hostname)) { options.rejectUnauthorized = false; } // initiate request var mod = this._enableHttp2 ? exports.protocols['http2:'].setProtocol(url.protocol) : exports.protocols[url.protocol]; // request this.req = mod.request(options); var req = this.req; // set tcp no delay req.setNoDelay(true); if (options.method !== 'HEAD') { req.setHeader('Accept-Encoding', 'gzip, deflate'); } this.protocol = url.protocol; this.host = url.host; // expose events req.once('drain', function () { _this3.emit('drain'); }); req.on('error', function (err) { // flag abortion here for out timeouts // because node will emit a faux-error "socket hang up" // when request is aborted before a connection is made if (_this3._aborted) return; // if not the same, we are in the **old** (cancelled) request, // so need to continue (same as for above) if (_this3._retries !== retries) return; // if we've received a response then we don't want to let // an error in the request blow up the response if (_this3.response) return; _this3.callback(err); }); // auth if (url.auth) { var auth = url.auth.split(':'); this.auth(auth[0], auth[1]); } if (this.username && this.password) { this.auth(this.username, this.password); } for (var key in this.header) { if (Object.prototype.hasOwnProperty.call(this.header, key)) req.setHeader(key, this.header[key]); } // add cookies if (this.cookies) { if (Object.prototype.hasOwnProperty.call(this._header, 'cookie')) { // merge var tmpJar = new CookieJar.CookieJar(); tmpJar.setCookies(this._header.cookie.split(';')); tmpJar.setCookies(this.cookies.split(';')); req.setHeader('Cookie', tmpJar.getCookies(CookieJar.CookieAccessInfo.All).toValueString()); } else { req.setHeader('Cookie', this.cookies); } } return req; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function (err, res) { if (this._shouldRetry(err, res)) { return this._retry(); } // Avoid the error which is emitted from 'socket hang up' to cause the fn undefined error on JS runtime. var fn = this._callback || noop; this.clearTimeout(); if (this.called) return console.warn('superagent: double callback bug'); this.called = true; if (!err) { try { if (!this._isResponseOK(res)) { var msg = 'Unsuccessful HTTP response'; if (res) { msg = http.STATUS_CODES[res.status] || msg; } err = new Error(msg); err.status = res ? res.status : undefined; } } catch (err_) { err = err_; } } // It's important that the callback is called outside try/catch // to avoid double callback if (!err) { return fn(null, res); } err.response = res; if (this._maxRetries) err.retries = this._retries - 1; // only emit error event if there is a listener // otherwise we assume the callback to `.end()` will get the error if (err && this.listeners('error').length > 0) { this.emit('error', err); } fn(err, res); }; /** * Check if `obj` is a host object, * * @param {Object} obj host object * @return {Boolean} is a host object * @api private */ Request.prototype._isHost = function (obj) { return Buffer.isBuffer(obj) || obj instanceof Stream || obj instanceof FormData; }; /** * Initiate request, invoking callback `fn(err, res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype._emitResponse = function (body, files) { var response = new Response(this); this.response = response; response.redirects = this._redirectList; if (undefined !== body) { response.body = body; } response.files = files; if (this._endCalled) { response.pipe = function () { throw new Error("end() has already been called, so it's too late to start piping"); }; } this.emit('response', response); return response; }; Request.prototype.end = function (fn) { this.request(); debug('%s %s', this.method, this.url); if (this._endCalled) { throw new Error('.end() was called twice. This is not supported in superagent'); } this._endCalled = true; // store callback this._callback = fn || noop; this._end(); }; Request.prototype._end = function () { var _this4 = this; if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); var data = this._data; var req = this.req; var method = this.method; this._setTimeouts(); // body if (method !== 'HEAD' && !req._headerSent) { // serialize stuff if (typeof data !== 'string') { var contentType = req.getHeader('Content-Type'); // Parse out just the content type from the header (ignore the charset) if (contentType) contentType = contentType.split(';')[0]; var serialize = this._serializer || exports.serialize[contentType]; if (!serialize && isJSON(contentType)) { serialize = exports.serialize['application/json']; } if (serialize) data = serialize(data); } // content-length if (data && !req.getHeader('Content-Length')) { req.setHeader('Content-Length', Buffer.isBuffer(data) ? data.length : Buffer.byteLength(data)); } } // response // eslint-disable-next-line complexity req.once('response', function (res) { debug('%s %s -> %s', _this4.method, _this4.url, res.statusCode); if (_this4._responseTimeoutTimer) { clearTimeout(_this4._responseTimeoutTimer); } if (_this4.piped) { return; } var max = _this4._maxRedirects; var mime = utils.type(res.headers['content-type'] || '') || 'text/plain'; var type = mime.split('/')[0]; if (type) type = type.toLowerCase().trim(); var multipart = type === 'multipart'; var redirect = isRedirect(res.statusCode); var responseType = _this4._responseType; _this4.res = res; // redirect if (redirect && _this4._redirects++ !== max) { return _this4._redirect(res); } if (_this4.method === 'HEAD') { _this4.emit('end'); _this4.callback(null, _this4._emitResponse()); return; } // zlib support if (_this4._shouldUnzip(res)) { unzip(req, res); } var buffer = _this4._buffer; if (buffer === undefined && mime in exports.buffer) { buffer = Boolean(exports.buffer[mime]); } var parser = _this4._parser; if (undefined === buffer) { if (parser) { console.warn("A custom superagent parser has been set, but buffering strategy for the parser hasn't been configured. Call `req.buffer(true or false)` or set `superagent.buffer[mime] = true or false`"); buffer = true; } } if (!parser) { if (responseType) { parser = exports.parse.image; // It's actually a generic Buffer buffer = true; } else if (multipart) { var form = new formidable.IncomingForm(); parser = form.parse.bind(form); buffer = true; } else if (isImageOrVideo(mime)) { parser = exports.parse.image; buffer = true; // For backwards-compatibility buffering default is ad-hoc MIME-dependent } else if (exports.parse[mime]) { parser = exports.parse[mime]; } else if (type === 'text') { parser = exports.parse.text; buffer = buffer !== false; // everyone wants their own white-labeled json } else if (isJSON(mime)) { parser = exports.parse['application/json']; buffer = buffer !== false; } else if (buffer) { parser = exports.parse.text; } else if (undefined === buffer) { parser = exports.parse.image; // It's actually a generic Buffer buffer = true; } } // by default only buffer text/*, json and messed up thing from hell if (undefined === buffer && isText(mime) || isJSON(mime)) { buffer = true; } _this4._resBuffered = buffer; var parserHandlesEnd = false; if (buffer) { // Protectiona against zip bombs and other nuisance var responseBytesLeft = _this4._maxResponseSize || 200000000; res.on('data', function (buf) { responseBytesLeft -= buf.byteLength || buf.length; if (responseBytesLeft < 0) { // This will propagate through error event var err = new Error('Maximum response size reached'); err.code = 'ETOOLARGE'; // Parsers aren't required to observe error event, // so would incorrectly report success parserHandlesEnd = false; // Will emit error event res.destroy(err); } }); } if (parser) { try { // Unbuffered parsers are supposed to emit response early, // which is weird BTW, because response.body won't be there. parserHandlesEnd = buffer; parser(res, function (err, obj, files) { if (_this4.timedout) { // Timeout has already handled all callbacks return; } // Intentional (non-timeout) abort is supposed to preserve partial response, // even if it doesn't parse. if (err && !_this4._aborted) { return _this4.callback(err); } if (parserHandlesEnd) { _this4.emit('end'); _this4.callback(null, _this4._emitResponse(obj, files)); } }); } catch (err) { _this4.callback(err); return; } } _this4.res = res; // unbuffered if (!buffer) { debug('unbuffered %s %s', _this4.method, _this4.url); _this4.callback(null, _this4._emitResponse()); if (multipart) return; // allow multipart to handle end event res.once('end', function () { debug('end %s %s', _this4.method, _this4.url); _this4.emit('end'); }); return; } // terminating events res.once('error', function (err) { parserHandlesEnd = false; _this4.callback(err, null); }); if (!parserHandlesEnd) res.once('end', function () { debug('end %s %s', _this4.method, _this4.url); // TODO: unless buffering emit earlier to stream _this4.emit('end'); _this4.callback(null, _this4._emitResponse()); }); }); this.emit('request', this); var getProgressMonitor = function getProgressMonitor() { var lengthComputable = true; var total = req.getHeader('Content-Length'); var loaded = 0; var progress = new Stream.Transform(); progress._transform = function (chunk, encoding, cb) { loaded += chunk.length; _this4.emit('progress', { direction: 'upload', lengthComputable: lengthComputable, loaded: loaded, total: total }); cb(null, chunk); }; return progress; }; var bufferToChunks = function bufferToChunks(buffer) { var chunkSize = 16 * 1024; // default highWaterMark value var chunking = new Stream.Readable(); var totalLength = buffer.length; var remainder = totalLength % chunkSize; var cutoff = totalLength - remainder; for (var i = 0; i < cutoff; i += chunkSize) { var chunk = buffer.slice(i, i + chunkSize); chunking.push(chunk); } if (remainder > 0) { var remainderBuffer = buffer.slice(-remainder); chunking.push(remainderBuffer); } chunking.push(null); // no more data return chunking; }; // if a FormData instance got created, then we send that as the request body var formData = this._formData; if (formData) { // set headers var headers = formData.getHeaders(); for (var i in headers) { if (Object.prototype.hasOwnProperty.call(headers, i)) { debug('setting FormData header: "%s: %s"', i, headers[i]); req.setHeader(i, headers[i]); } } // attempt to get "Content-Length" header formData.getLength(function (err, length) { // TODO: Add chunked encoding when no length (if err) if (err) debug('formData.getLength had error', err, length); debug('got FormData Content-Length: %s', length); if (typeof length === 'number') { req.setHeader('Content-Length', length); } formData.pipe(getProgressMonitor()).pipe(req); }); } else if (Buffer.isBuffer(data)) { bufferToChunks(data).pipe(getProgressMonitor()).pipe(req); } else { req.end(data); } }; // Check whether response has a non-0-sized gzip-encoded body Request.prototype._shouldUnzip = function (res) { if (res.statusCode === 204 || res.statusCode === 304) { // These aren't supposed to have any body return false; } // header content is a string, and distinction between 0 and no information is crucial if (res.headers['content-length'] === '0') { // We know that the body is empty (unfortunately, this check does not cover chunked encoding) return false; } // console.log(res); return /^\s*(?:deflate|gzip)\s*$/.test(res.headers['content-encoding']); }; /** * Overrides DNS for selected hostnames. Takes object mapping hostnames to IP addresses. * * When making a request to a URL with a hostname exactly matching a key in the object, * use the given IP address to connect, instead of using DNS to resolve the hostname. * * A special host `*` matches every hostname (keep redirects in mind!) * * request.connect({ * 'test.example.com': '127.0.0.1', * 'ipv6.example.com': '::1', * }) */ Request.prototype.connect = function (connectOverride) { if (typeof connectOverride === 'string') { this._connectOverride = { '*': connectOverride }; } else if (_typeof(connectOverride) === 'object') { this._connectOverride = connectOverride; } else { this._connectOverride = undefined; } return this; }; Request.prototype.trustLocalhost = function (toggle) { this._trustLocalhost = toggle === undefined ? true : toggle; return this; }; // generate HTTP verb methods if (!methods.includes('del')) { // create a copy so we don't cause conflicts with // other packages using the methods package and // npm 3.x methods = methods.slice(0); methods.push('del'); } methods.forEach(function (method) { var name = method; method = method === 'del' ? 'delete' : method; method = method.toUpperCase(); request[name] = function (url, data, fn) { var req = request(method, url); if (typeof data === 'function') { fn = data; data = null; } if (data) { if (method === 'GET' || method === 'HEAD') { req.query(data); } else { req.send(data); } } if (fn) req.end(fn); return req; }; }); /** * Check if `mime` is text and should be buffered. * * @param {String} mime * @return {Boolean} * @api public */ function isText(mime) { var parts = mime.split('/'); var type = parts[0]; if (type) type = type.toLowerCase().trim(); var subtype = parts[1]; if (subtype) subtype = subtype.toLowerCase().trim(); return type === 'text' || subtype === 'x-www-form-urlencoded'; } function isImageOrVideo(mime) { var type = mime.split('/')[0]; if (type) type = type.toLowerCase().trim(); return type === 'image' || type === 'video'; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { // should match /json or +json // but not /json-seq return /[/+]json($|[^-\w])/i.test(mime); } /** * Check if we should follow the redirect `code`. * * @param {Number} code * @return {Boolean} * @api private */ function isRedirect(code) { return [301, 302, 303, 305, 307, 308].includes(code); } //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashcmVjdHMgPSAwO1xuICB0aGlzLnJlZGlyZWN0cyhtZXRob2QgPT09ICdIRUFEJyA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLl9lbmFibGVIdHRwMiA9IGJvb2wgPT09IHVuZGVmaW5lZCA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZXIuZnJvbSgnPGI+SGVsbG8gd29ybGQ8L2I+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYXRhLm9uKCdlcnJvcicsIChlcnIpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZScsIChyZXMpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashcmVkaXJlY3QocmVzKSA9PT0gdGhpc1xuICAgICAgICA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZXJzID0gdGhpcy5yZXEuZ2V0SGVhZGVycyA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbWV0aG9kID0gdGhpcy5tZXRob2QgPT09ICdIRUFEJyA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashPSAvOi8udGVzdChuZXdIb3N0KSA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashICA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashKCdlcnJvcicsIChlcnIpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashYXR1cyA9IHJlcyA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbmd0aCA+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashc2UnLCAocmVzKSA9PiB7XG4gICAgZGVidWcoJyVzICVzIC0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashdW5rLCBlbmNvZGluZywgY2IpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLmdldExlbmd0aCgoZXJyLCBsZW5ndGgpID0+your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashLy8gY29uc29sZS5sb2cocmVzKTtcbiAgcmV0dXJuIC9eXFxzKig/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashbGhvc3QgPSB0b2dnbGUgPT09IHVuZGVmaW5lZCA/your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashY29kZSk7XG59XG4iXX0= ```
/content/code_sandbox/node_modules/superagent/lib/node/index.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
14,368
```javascript "use strict"; /** * Module dependencies. */ var qs = require('qs'); module.exports = function (res, fn) { res.text = ''; res.setEncoding('ascii'); res.on('data', function (chunk) { res.text += chunk; }); res.on('end', function () { try { fn(null, qs.parse(res.text)); } catch (err) { fn(err); } }); }; //# sourceMappingURL=data:application/json;charset=utf-8;base64,your_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashyour_sha256_hashZm4pID0+your_sha256_hashO1xuICByZXMub24oJ2RhdGEnLCAoY2h1bmspID0+your_sha256_hashyour_sha256_hashyour_sha256_hashbiAgICB9XG4gIH0pO1xufTtcbiJdfQ== ```
/content/code_sandbox/node_modules/superagent/lib/node/parsers/urlencoded.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
252
```javascript !function(t){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).superagent=t()}}((function(){var t={exports:{}};function e(t){if(t)return function(t){for(var r in e.prototype)t[r]=e.prototype[r];return t}(t)}t.exports=e,e.prototype.on=e.prototype.addEventListener=function(t,e){return this._callbacks=this._callbacks||{},(this._callbacks["$"+t]=this._callbacks["$"+t]||[]).push(e),this},e.prototype.once=function(t,e){function r(){this.off(t,r),e.apply(this,arguments)}return r.fn=e,this.on(t,r),this},e.prototype.off=e.prototype.removeListener=e.prototype.removeAllListeners=e.prototype.removeEventListener=function(t,e){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,o=this._callbacks["$"+t];if(!o)return this;if(1==arguments.length)return delete this._callbacks["$"+t],this;for(var n=0;n<o.length;n++)if((r=o[n])===e||r.fn===e){o.splice(n,1);break}return 0===o.length&&delete this._callbacks["$"+t],this},e.prototype.emit=function(t){this._callbacks=this._callbacks||{};for(var e=new Array(arguments.length-1),r=this._callbacks["$"+t],o=1;o<arguments.length;o++)e[o-1]=arguments[o];if(r){o=0;for(var n=(r=r.slice(0)).length;o<n;++o)r[o].apply(this,e)}return this},e.prototype.listeners=function(t){return this._callbacks=this._callbacks||{},this._callbacks["$"+t]||[]},e.prototype.hasListeners=function(t){return!!this.listeners(t).length},t=t.exports;var r;function o(t){return(o="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}r=s,s.default=s,s.stable=u,s.stableStringify=u;var n=[],i=[];function s(t,e,r){var s;for(function t(e,r,s,a){var u;if("object"==o(e)&&null!==e){for(u=0;u<s.length;u++)if(s[u]===e){var c=Object.getOwnPropertyDescriptor(a,r);return void(void 0!==c.get?c.configurable?(Object.defineProperty(a,r,{value:"[Circular]"}),n.push([a,r,e,c])):i.push([e,r]):(a[r]="[Circular]",n.push([a,r,e])))}if(s.push(e),Array.isArray(e))for(u=0;u<e.length;u++)t(e[u],u,s,e);else{var l=Object.keys(e);for(u=0;u<l.length;u++){var p=l[u];t(e[p],p,s,e)}}s.pop()}}(t,"",[],void 0),s=0===i.length?JSON.stringify(t,e,r):JSON.stringify(t,c(e),r);0!==n.length;){var a=n.pop();4===a.length?Object.defineProperty(a[0],a[1],a[3]):a[0][a[1]]=a[2]}return s}function a(t,e){return t<e?-1:t>e?1:0}function u(t,e,r){var s,u=function t(e,r,s,u){var c;if("object"==o(e)&&null!==e){for(c=0;c<s.length;c++)if(s[c]===e){var l=Object.getOwnPropertyDescriptor(u,r);return void(void 0!==l.get?l.configurable?(Object.defineProperty(u,r,{value:"[Circular]"}),n.push([u,r,e,l])):i.push([e,r]):(u[r]="[Circular]",n.push([u,r,e])))}if("function"==typeof e.toJSON)return;if(s.push(e),Array.isArray(e))for(c=0;c<e.length;c++)t(e[c],c,s,e);else{var p={},f=Object.keys(e).sort(a);for(c=0;c<f.length;c++){var h=f[c];t(e[h],h,s,e),p[h]=e[h]}if(void 0===u)return p;n.push([u,r,e]),u[r]=p}s.pop()}}(t,"",[],void 0)||t;for(s=0===i.length?JSON.stringify(u,e,r):JSON.stringify(u,c(e),r);0!==n.length;){var l=n.pop();4===l.length?Object.defineProperty(l[0],l[1],l[3]):l[0][l[1]]=l[2]}return s}function c(t){return t=void 0!==t?t:function(t,e){return e},function(e,r){if(i.length>0)for(var o=0;o<i.length;o++){var n=i[o];if(n[1]===e&&n[0]===r){r="[Circular]",i.splice(o,1);break}}return t.call(this,e,r)}}function l(t){return(l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var p=Object.prototype.hasOwnProperty,f=Array.isArray,h=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),y={assign:function(t,e){return Object.keys(e).reduce((function(t,r){return t[r]=e[r],t}),t)},combine:function(t,e){return[].concat(t,e)},compact:function(t){for(var e=[{obj:{o:t},prop:"o"}],r=[],o=0;o<e.length;++o)for(var n=e[o],i=n.obj[n.prop],s=Object.keys(i),a=0;a<s.length;++a){var u=s[a],c=i[u];"object"==l(c)&&null!==c&&-1===r.indexOf(c)&&(e.push({obj:i,prop:u}),r.push(c))}return function(t){for(;t.length>1;){var e=t.pop(),r=e.obj[e.prop];if(f(r)){for(var o=[],n=0;n<r.length;++n)void 0!==r[n]&&o.push(r[n]);e.obj[e.prop]=o}}}(e),t},decode:function(t,e,r){var o=t.replace(/\+/g," ");if("iso-8859-1"===r)return o.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(o)}catch(n){return o}},encode:function(t,e,r){if(0===t.length)return t;var o=t;if("symbol"==l(t)?o=Symbol.prototype.toString.call(t):"string"!=typeof t&&(o=String(t)),"iso-8859-1"===r)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(t){return"%26%23"+parseInt(t.slice(2),16)+"%3B"}));for(var n="",i=0;i<o.length;++i){var s=o.charCodeAt(i);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122?n+=o.charAt(i):s<128?n+=h[s]:s<2048?n+=h[192|s>>6]+h[128|63&s]:s<55296||s>=57344?n+=h[224|s>>12]+h[128|s>>6&63]+h[128|63&s]:(i+=1,s=65536+((1023&s)<<10|1023&o.charCodeAt(i)),n+=h[240|s>>18]+h[128|s>>12&63]+h[128|s>>6&63]+h[128|63&s])}return n},isBuffer:function(t){return!(!t||"object"!=l(t)||!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t)))},isRegExp:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},maybeMap:function(t,e){if(f(t)){for(var r=[],o=0;o<t.length;o+=1)r.push(e(t[o]));return r}return e(t)},merge:function t(e,r,o){if(!r)return e;if("object"!=l(r)){if(f(e))e.push(r);else{if(!e||"object"!=l(e))return[e,r];(o&&(o.plainObjects||o.allowPrototypes)||!p.call(Object.prototype,r))&&(e[r]=!0)}return e}if(!e||"object"!=l(e))return[e].concat(r);var n=e;return f(e)&&!f(r)&&(n=function(t,e){for(var r=e&&e.plainObjects?Object.create(null):{},o=0;o<t.length;++o)void 0!==t[o]&&(r[o]=t[o]);return r}(e,o)),f(e)&&f(r)?(r.forEach((function(r,n){if(p.call(e,n)){var i=e[n];i&&"object"==l(i)&&r&&"object"==l(r)?e[n]=t(i,r,o):e.push(r)}else e[n]=r})),e):Object.keys(r).reduce((function(e,n){var i=r[n];return p.call(e,n)?e[n]=t(e[n],i,o):e[n]=i,e}),n)}},d=String.prototype.replace,m=/%20/g,b={RFC1738:"RFC1738",RFC3986:"RFC3986"},v=y.assign({default:b.RFC3986,formatters:{RFC1738:function(t){return d.call(t,m,"+")},RFC3986:function(t){return String(t)}}},b);function _(t){return(_="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var w=Object.prototype.hasOwnProperty,g={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},T=Array.isArray,O=Array.prototype.push,E=function(t,e){O.apply(t,T(e)?e:[e])},S=Date.prototype.toISOString,j=v.default,x={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:y.encode,encodeValuesOnly:!1,format:j,formatter:v.formatters[j],indices:!1,serializeDate:function(t){return S.call(t)},skipNulls:!1,strictNullHandling:!1},k=function t(e,r,o,n,i,s,a,u,c,l,p,f,h){var d,m=e;if("function"==typeof a?m=a(r,m):m instanceof Date?m=l(m):"comma"===o&&T(m)&&(m=y.maybeMap(m,(function(t){return t instanceof Date?l(t):t})).join(",")),null===m){if(n)return s&&!f?s(r,x.encoder,h,"key"):r;m=""}if("string"==typeof(d=m)||"number"==typeof d||"boolean"==typeof d||"symbol"==_(d)||"bigint"==typeof d||y.isBuffer(m))return s?[p(f?r:s(r,x.encoder,h,"key"))+"="+p(s(m,x.encoder,h,"value"))]:[p(r)+"="+p(String(m))];var b,v=[];if(void 0===m)return v;if(T(a))b=a;else{var w=Object.keys(m);b=u?w.sort(u):w}for(var g=0;g<b.length;++g){var O=b[g],S=m[O];if(!i||null!==S){var j=T(m)?"function"==typeof o?o(r,O):r:r+(c?"."+O:"["+O+"]");E(v,t(S,j,o,n,i,s,a,u,c,l,p,f,h))}}return v},A=(Object.prototype.hasOwnProperty,Array.isArray,{stringify:function(t,e){var r,o=t,n=function(t){if(!t)return x;if(null!==t.encoder&&void 0!==t.encoder&&"function"!=typeof t.encoder)throw new TypeError("Encoder has to be a function.");var e=t.charset||x.charset;if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var r=v.default;if(void 0!==t.format){if(!w.call(v.formatters,t.format))throw new TypeError("Unknown format option provided.");r=t.format}var o=v.formatters[r],n=x.filter;return("function"==typeof t.filter||T(t.filter))&&(n=t.filter),{addQueryPrefix:"boolean"==typeof t.addQueryPrefix?t.addQueryPrefix:x.addQueryPrefix,allowDots:void 0===t.allowDots?x.allowDots:!!t.allowDots,charset:e,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:x.charsetSentinel,delimiter:void 0===t.delimiter?x.delimiter:t.delimiter,encode:"boolean"==typeof t.encode?t.encode:x.encode,encoder:"function"==typeof t.encoder?t.encoder:x.encoder,encodeValuesOnly:"boolean"==typeof t.encodeValuesOnly?t.encodeValuesOnly:x.encodeValuesOnly,filter:n,formatter:o,serializeDate:"function"==typeof t.serializeDate?t.serializeDate:x.serializeDate,skipNulls:"boolean"==typeof t.skipNulls?t.skipNulls:x.skipNulls,sort:"function"==typeof t.sort?t.sort:null,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:x.strictNullHandling}}(e);"function"==typeof n.filter?o=(0,n.filter)("",o):T(n.filter)&&(r=n.filter);var i,s=[];if("object"!=_(o)||null===o)return"";i=e&&e.arrayFormat in g?e.arrayFormat:e&&"indices"in e?e.indices?"indices":"repeat":"indices";var a=g[i];r||(r=Object.keys(o)),n.sort&&r.sort(n.sort);for(var u=0;u<r.length;++u){var c=r[u];n.skipNulls&&null===o[c]||E(s,k(o[c],c,a,n.strictNullHandling,n.skipNulls,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.formatter,n.encodeValuesOnly,n.charset))}var l=s.join(n.delimiter),p=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?p+="utf8=%26%2310003%3B&":p+="utf8=%E2%9C%93&"),l.length>0?p+l:""}});function C(t){return(C="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}var R=function(t){return null!==t&&"object"==C(t)},P={};function D(t){return(D="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function q(t){if(t)return function(t){for(var e in q.prototype)Object.prototype.hasOwnProperty.call(q.prototype,e)&&(t[e]=q.prototype[e]);return t}(t)}P=q,q.prototype.clearTimeout=function(){return clearTimeout(this._timer),clearTimeout(this._responseTimeoutTimer),clearTimeout(this._uploadTimeoutTimer),delete this._timer,delete this._responseTimeoutTimer,delete this._uploadTimeoutTimer,this},q.prototype.parse=function(t){return this._parser=t,this},q.prototype.responseType=function(t){return this._responseType=t,this},q.prototype.serialize=function(t){return this._serializer=t,this},q.prototype.timeout=function(t){if(!t||"object"!=D(t))return this._timeout=t,this._responseTimeout=0,this._uploadTimeout=0,this;for(var e in t)if(Object.prototype.hasOwnProperty.call(t,e))switch(e){case"deadline":this._timeout=t.deadline;break;case"response":this._responseTimeout=t.response;break;case"upload":this._uploadTimeout=t.upload;break;default:console.warn("Unknown timeout option",e)}return this},q.prototype.retry=function(t,e){return 0!==arguments.length&&!0!==t||(t=1),t<=0&&(t=0),this._maxRetries=t,this._retries=0,this._retryCallback=e,this};var N=new Set(["ETIMEDOUT","ECONNRESET","EADDRINUSE","ECONNREFUSED","EPIPE","ENOTFOUND","ENETUNREACH","EAI_AGAIN"]),H=new Set([408,413,429,500,502,503,504,521,522,524]);q.prototype._shouldRetry=function(t,e){if(!this._maxRetries||this._retries++>=this._maxRetries)return!1;if(this._retryCallback)try{var r=this._retryCallback(t,e);if(!0===r)return!0;if(!1===r)return!1}catch(o){console.error(o)}if(e&&e.status&&H.has(e.status))return!0;if(t){if(t.code&&N.has(t.code))return!0;if(t.timeout&&"ECONNABORTED"===t.code)return!0;if(t.crossDomain)return!0}return!1},q.prototype._retry=function(){return this.clearTimeout(),this.req&&(this.req=null,this.req=this.request()),this._aborted=!1,this.timedout=!1,this.timedoutError=null,this._end()},q.prototype.then=function(t,e){var r=this;if(!this._fullfilledPromise){var o=this;this._endCalled&&console.warn("Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises"),this._fullfilledPromise=new Promise((function(t,e){o.on("abort",(function(){if(!(r._maxRetries&&r._maxRetries>r._retries))if(r.timedout&&r.timedoutError)e(r.timedoutError);else{var t=new Error("Aborted");t.code="ABORTED",t.status=r.status,t.method=r.method,t.url=r.url,e(t)}})),o.end((function(r,o){r?e(r):t(o)}))}))}return this._fullfilledPromise.then(t,e)},q.prototype.catch=function(t){return this.then(void 0,t)},q.prototype.use=function(t){return t(this),this},q.prototype.ok=function(t){if("function"!=typeof t)throw new Error("Callback required");return this._okCallback=t,this},q.prototype._isResponseOK=function(t){return!!t&&(this._okCallback?this._okCallback(t):t.status>=200&&t.status<300)},q.prototype.get=function(t){return this._header[t.toLowerCase()]},q.prototype.getHeader=q.prototype.get,q.prototype.set=function(t,e){if(R(t)){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&this.set(r,t[r]);return this}return this._header[t.toLowerCase()]=e,this.header[t]=e,this},q.prototype.unset=function(t){return delete this._header[t.toLowerCase()],delete this.header[t],this},q.prototype.field=function(t,e){if(null==t)throw new Error(".field(name, val) name can not be empty");if(this._data)throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()");if(R(t)){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&this.field(r,t[r]);return this}if(Array.isArray(e)){for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&this.field(t,e[o]);return this}if(null==e)throw new Error(".field(name, val) val can not be empty");return"boolean"==typeof e&&(e=String(e)),this._getFormData().append(t,e),this},q.prototype.abort=function(){return this._aborted||(this._aborted=!0,this.xhr&&this.xhr.abort(),this.req&&this.req.abort(),this.clearTimeout(),this.emit("abort")),this},q.prototype._auth=function(t,e,r,o){switch(r.type){case"basic":this.set("Authorization","Basic ".concat(o("".concat(t,":").concat(e))));break;case"auto":this.username=t,this.password=e;break;case"bearer":this.set("Authorization","Bearer ".concat(t))}return this},q.prototype.withCredentials=function(t){return void 0===t&&(t=!0),this._withCredentials=t,this},q.prototype.redirects=function(t){return this._maxRedirects=t,this},q.prototype.maxResponseSize=function(t){if("number"!=typeof t)throw new TypeError("Invalid argument");return this._maxResponseSize=t,this},q.prototype.toJSON=function(){return{method:this.method,url:this.url,data:this._data,headers:this._header}},q.prototype.send=function(t){var e=R(t),r=this._header["content-type"];if(this._formData)throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()");if(e&&!this._data)Array.isArray(t)?this._data=[]:this._isHost(t)||(this._data={});else if(t&&this._data&&this._isHost(this._data))throw new Error("Can't merge these send calls");if(e&&R(this._data))for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&(this._data[o]=t[o]);else"string"==typeof t?(r||this.type("form"),(r=this._header["content-type"])&&(r=r.toLowerCase().trim()),this._data="application/x-www-form-urlencoded"===r?this._data?"".concat(this._data,"&").concat(t):t:(this._data||"")+t):this._data=t;return!e||this._isHost(t)||r||this.type("json"),this},q.prototype.sortQuery=function(t){return this._sort=void 0===t||t,this},q.prototype._finalizeQueryString=function(){var t=this._query.join("&");if(t&&(this.url+=(this.url.includes("?")?"&":"?")+t),this._query.length=0,this._sort){var e=this.url.indexOf("?");if(e>=0){var r=this.url.slice(e+1).split("&");"function"==typeof this._sort?r.sort(this._sort):r.sort(),this.url=this.url.slice(0,e)+"?"+r.join("&")}}},q.prototype._appendQueryString=function(){console.warn("Unsupported")},q.prototype._timeoutError=function(t,e,r){if(!this._aborted){var o=new Error("".concat(t+e,"ms exceeded"));o.timeout=e,o.code="ECONNABORTED",o.errno=r,this.timedout=!0,this.timedoutError=o,this.abort(),this.callback(o)}},q.prototype._setTimeouts=function(){var t=this;this._timeout&&!this._timer&&(this._timer=setTimeout((function(){t._timeoutError("Timeout of ",t._timeout,"ETIME")}),this._timeout)),this._responseTimeout&&!this._responseTimeoutTimer&&(this._responseTimeoutTimer=setTimeout((function(){t._timeoutError("Response timeout of ",t._responseTimeout,"ETIMEDOUT")}),this._responseTimeout))};var U={};function I(t,e){var r;if("undefined"==typeof Symbol||null==t[Symbol.iterator]){if(Array.isArray(t)||(r=function(t,e){if(!t)return;if("string"==typeof t)return L(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return L(t,e)}(t))||e&&t&&"number"==typeof t.length){r&&(t=r);var o=0,n=function(){};return{s:n,n:function(){return o>=t.length?{done:!0}:{done:!1,value:t[o++]}},e:function(t){throw t},f:n}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var i,s=!0,a=!1;return{s:function(){r=t[Symbol.iterator]()},n:function(){var t=r.next();return s=t.done,t},e:function(t){a=!0,i=t},f:function(){try{s||null==r.return||r.return()}finally{if(a)throw i}}}}function L(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,o=new Array(e);r<e;r++)o[r]=t[r];return o}U.type=function(t){return t.split(/ *; */).shift()},U.params=function(t){var e,r={},o=I(t.split(/ *; */));try{for(o.s();!(e=o.n()).done;){var n=e.value.split(/ *= */),i=n.shift(),s=n.shift();i&&s&&(r[i]=s)}}catch(a){o.e(a)}finally{o.f()}return r},U.parseLinks=function(t){var e,r={},o=I(t.split(/ *, */));try{for(o.s();!(e=o.n()).done;){var n=e.value.split(/ *; */),i=n[0].slice(1,-1);r[n[1].split(/ *= */)[1].slice(1,-1)]=i}}catch(s){o.e(s)}finally{o.f()}return r};var z={};function M(t){if(t)return function(t){for(var e in M.prototype)Object.prototype.hasOwnProperty.call(M.prototype,e)&&(t[e]=M.prototype[e]);return t}(t)}z=M,M.prototype.get=function(t){return this.header[t.toLowerCase()]},M.prototype._setHeaderProperties=function(t){var e=t["content-type"]||"";this.type=U.type(e);var r=U.params(e);for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(this[o]=r[o]);this.links={};try{t.link&&(this.links=U.parseLinks(t.link))}catch(n){}},M.prototype._setStatusProperties=function(t){var e=t/100|0;this.statusCode=t,this.status=this.statusCode,this.statusType=e,this.info=1===e,this.ok=2===e,this.redirect=3===e,this.clientError=4===e,this.serverError=5===e,this.error=(4===e||5===e)&&this.toError(),this.created=201===t,this.accepted=202===t,this.noContent=204===t,this.badRequest=400===t,this.unauthorized=401===t,this.notAcceptable=406===t,this.forbidden=403===t,this.notFound=404===t,this.unprocessableEntity=422===t};var F={};function B(t){return function(t){if(Array.isArray(t))return X(t)}(t)||function(t){if("undefined"!=typeof Symbol&&Symbol.iterator in Object(t))return Array.from(t)}(t)||function(t,e){if(!t)return;if("string"==typeof t)return X(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);"Object"===r&&t.constructor&&(r=t.constructor.name);if("Map"===r||"Set"===r)return Array.from(t);if("Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return X(t,e)}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function X(t,e){(null==e||e>t.length)&&(e=t.length);for(var r=0,o=new Array(e);r<e;r++)o[r]=t[r];return o}function Q(){this._defaults=[]}["use","on","once","set","query","type","accept","auth","withCredentials","sortQuery","retry","ok","redirects","timeout","buffer","serialize","parse","ca","key","pfx","cert","disableTLSCerts"].forEach((function(t){Q.prototype[t]=function(){for(var e=arguments.length,r=new Array(e),o=0;o<e;o++)r[o]=arguments[o];return this._defaults.push({fn:t,args:r}),this}})),Q.prototype._setDefaults=function(t){this._defaults.forEach((function(e){t[e.fn].apply(t,B(e.args))}))},F=Q;var $,J={};function G(t){return(G="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t})(t)}function V(){}"undefined"!=typeof window?$=window:"undefined"==typeof self?(console.warn("Using browser-only version of superagent in non-browser environment"),$=void 0):$=self;var K=J=J=function(t,e){return"function"==typeof e?new J.Request("GET",t).end(e):1===arguments.length?new J.Request("GET",t):new J.Request(t,e)};J.Request=ot,K.getXHR=function(){if($.XMLHttpRequest&&(!$.location||"file:"!==$.location.protocol||!$.ActiveXObject))return new XMLHttpRequest;try{return new ActiveXObject("Microsoft.XMLHTTP")}catch(t){}try{return new ActiveXObject("Msxml2.XMLHTTP.6.0")}catch(e){}try{return new ActiveXObject("Msxml2.XMLHTTP.3.0")}catch(r){}try{return new ActiveXObject("Msxml2.XMLHTTP")}catch(o){}throw new Error("Browser-only version of superagent could not find XHR")};var W="".trim?function(t){return t.trim()}:function(t){return t.replace(/(^\s*|\s*$)/g,"")};function Y(t){if(!R(t))return t;var e=[];for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&Z(e,r,t[r]);return e.join("&")}function Z(t,e,r){if(void 0!==r)if(null!==r)if(Array.isArray(r))r.forEach((function(r){Z(t,e,r)}));else if(R(r))for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&Z(t,"".concat(e,"[").concat(o,"]"),r[o]);else t.push(encodeURI(e)+"="+encodeURIComponent(r));else t.push(encodeURI(e))}function tt(t){for(var e,r,o={},n=t.split("&"),i=0,s=n.length;i<s;++i)-1===(r=(e=n[i]).indexOf("="))?o[decodeURIComponent(e)]="":o[decodeURIComponent(e.slice(0,r))]=decodeURIComponent(e.slice(r+1));return o}function et(t){return/[/+]json($|[^-\w])/i.test(t)}function rt(t){this.req=t,this.xhr=this.req.xhr,this.text="HEAD"!==this.req.method&&(""===this.xhr.responseType||"text"===this.xhr.responseType)||void 0===this.xhr.responseType?this.xhr.responseText:null,this.statusText=this.req.xhr.statusText;var e=this.xhr.status;1223===e&&(e=204),this._setStatusProperties(e),this.headers=function(t){for(var e,r,o,n,i=t.split(/\r?\n/),s={},a=0,u=i.length;a<u;++a)-1!==(e=(r=i[a]).indexOf(":"))&&(o=r.slice(0,e).toLowerCase(),n=W(r.slice(e+1)),s[o]=n);return s}(this.xhr.getAllResponseHeaders()),this.header=this.headers,this.header["content-type"]=this.xhr.getResponseHeader("content-type"),this._setHeaderProperties(this.header),null===this.text&&t._responseType?this.body=this.xhr.response:this.body="HEAD"===this.req.method?null:this._parseBody(this.text?this.text:this.xhr.response)}function ot(t,e){var r=this;this._query=this._query||[],this.method=t,this.url=e,this.header={},this._header={},this.on("end",(function(){var t,e=null,o=null;try{o=new rt(r)}catch(n){return(e=new Error("Parser is unable to parse the response")).parse=!0,e.original=n,r.xhr?(e.rawResponse=void 0===r.xhr.responseType?r.xhr.responseText:r.xhr.response,e.status=r.xhr.status?r.xhr.status:null,e.statusCode=e.status):(e.rawResponse=null,e.status=null),r.callback(e)}r.emit("response",o);try{r._isResponseOK(o)||(t=new Error(o.statusText||o.text||"Unsuccessful HTTP response"))}catch(n){t=n}t?(t.original=e,t.response=o,t.status=o.status,r.callback(t,o)):r.callback(null,o)}))}function nt(t,e,r){var o=K("DELETE",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o}return K.serializeObject=Y,K.parseString=tt,K.types={html:"text/html",json:"application/json",xml:"text/xml",urlencoded:"application/x-www-form-urlencoded",form:"application/x-www-form-urlencoded","form-data":"application/x-www-form-urlencoded"},K.serialize={"application/x-www-form-urlencoded":A.stringify,"application/json":r},K.parse={"application/x-www-form-urlencoded":tt,"application/json":JSON.parse},z(rt.prototype),rt.prototype._parseBody=function(t){var e=K.parse[this.type];return this.req._parser?this.req._parser(this,t):(!e&&et(this.type)&&(e=K.parse["application/json"]),e&&t&&(t.length>0||t instanceof Object)?e(t):null)},rt.prototype.toError=function(){var t=this.req,e=t.method,r=t.url,o="cannot ".concat(e," ").concat(r," (").concat(this.status,")"),n=new Error(o);return n.status=this.status,n.method=e,n.url=r,n},K.Response=rt,t(ot.prototype),P(ot.prototype),ot.prototype.type=function(t){return this.set("Content-Type",K.types[t]||t),this},ot.prototype.accept=function(t){return this.set("Accept",K.types[t]||t),this},ot.prototype.auth=function(t,e,r){return 1===arguments.length&&(e=""),"object"==G(e)&&null!==e&&(r=e,e=""),r||(r={type:"function"==typeof btoa?"basic":"auto"}),this._auth(t,e,r,(function(t){if("function"==typeof btoa)return btoa(t);throw new Error("Cannot use basic auth, btoa is not a function")}))},ot.prototype.query=function(t){return"string"!=typeof t&&(t=Y(t)),t&&this._query.push(t),this},ot.prototype.attach=function(t,e,r){if(e){if(this._data)throw new Error("superagent can't mix .send() and .attach()");this._getFormData().append(t,e,r||e.name)}return this},ot.prototype._getFormData=function(){return this._formData||(this._formData=new $.FormData),this._formData},ot.prototype.callback=function(t,e){if(this._shouldRetry(t,e))return this._retry();var r=this._callback;this.clearTimeout(),t&&(this._maxRetries&&(t.retries=this._retries-1),this.emit("error",t)),r(t,e)},ot.prototype.crossDomainError=function(){var t=new Error("Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.");t.crossDomain=!0,t.status=this.status,t.method=this.method,t.url=this.url,this.callback(t)},ot.prototype.agent=function(){return console.warn("This is not supported in browser version of superagent"),this},ot.prototype.ca=ot.prototype.agent,ot.prototype.buffer=ot.prototype.ca,ot.prototype.write=function(){throw new Error("Streaming is not supported in browser version of superagent")},ot.prototype.pipe=ot.prototype.write,ot.prototype._isHost=function(t){return t&&"object"==G(t)&&!Array.isArray(t)&&"[object Object]"!==Object.prototype.toString.call(t)},ot.prototype.end=function(t){this._endCalled&&console.warn("Warning: .end() was called twice. This is not supported in superagent"),this._endCalled=!0,this._callback=t||V,this._finalizeQueryString(),this._end()},ot.prototype._setUploadTimeout=function(){var t=this;this._uploadTimeout&&!this._uploadTimeoutTimer&&(this._uploadTimeoutTimer=setTimeout((function(){t._timeoutError("Upload timeout of ",t._uploadTimeout,"ETIMEDOUT")}),this._uploadTimeout))},ot.prototype._end=function(){if(this._aborted)return this.callback(new Error("The request has been aborted even before .end() was called"));var t=this;this.xhr=K.getXHR();var e=this.xhr,r=this._formData||this._data;this._setTimeouts(),e.onreadystatechange=function(){var r=e.readyState;if(r>=2&&t._responseTimeoutTimer&&clearTimeout(t._responseTimeoutTimer),4===r){var o;try{o=e.status}catch(n){o=0}if(!o){if(t.timedout||t._aborted)return;return t.crossDomainError()}t.emit("end")}};var o=function(e,r){r.total>0&&(r.percent=r.loaded/r.total*100,100===r.percent&&clearTimeout(t._uploadTimeoutTimer)),r.direction=e,t.emit("progress",r)};if(this.hasListeners("progress"))try{e.addEventListener("progress",o.bind(null,"download")),e.upload&&e.upload.addEventListener("progress",o.bind(null,"upload"))}catch(a){}e.upload&&this._setUploadTimeout();try{this.username&&this.password?e.open(this.method,this.url,!0,this.username,this.password):e.open(this.method,this.url,!0)}catch(u){return this.callback(u)}if(this._withCredentials&&(e.withCredentials=!0),!this._formData&&"GET"!==this.method&&"HEAD"!==this.method&&"string"!=typeof r&&!this._isHost(r)){var n=this._header["content-type"],i=this._serializer||K.serialize[n?n.split(";")[0]:""];!i&&et(n)&&(i=K.serialize["application/json"]),i&&(r=i(r))}for(var s in this.header)null!==this.header[s]&&Object.prototype.hasOwnProperty.call(this.header,s)&&e.setRequestHeader(s,this.header[s]);this._responseType&&(e.responseType=this._responseType),this.emit("request",this),e.send(void 0===r?null:r)},K.agent=function(){return new F},["GET","POST","OPTIONS","PATCH","PUT","DELETE"].forEach((function(t){F.prototype[t.toLowerCase()]=function(e,r){var o=new K.Request(t,e);return this._setDefaults(o),r&&o.end(r),o}})),F.prototype.del=F.prototype.delete,K.get=function(t,e,r){var o=K("GET",t);return"function"==typeof e&&(r=e,e=null),e&&o.query(e),r&&o.end(r),o},K.head=function(t,e,r){var o=K("HEAD",t);return"function"==typeof e&&(r=e,e=null),e&&o.query(e),r&&o.end(r),o},K.options=function(t,e,r){var o=K("OPTIONS",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},K.del=nt,K.delete=nt,K.patch=function(t,e,r){var o=K("PATCH",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},K.post=function(t,e,r){var o=K("POST",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},K.put=function(t,e,r){var o=K("PUT",t);return"function"==typeof e&&(r=e,e=null),e&&o.send(e),r&&o.end(r),o},J})); ```
/content/code_sandbox/node_modules/superagent/dist/superagent.min.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
8,989
```html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>SuperAgent elegant API for AJAX in Node and browsers</title> <link rel="stylesheet" href="path_to_url"> <link rel="stylesheet" href="docs/style.css"> </head> <body> <ul id="menu"></ul> <div id="content"> ```
/content/code_sandbox/node_modules/superagent/docs/head.html
html
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
87
```html </div> <a href="path_to_url"><img style="position: absolute; top: 0; right: 0; border: 0;" src="path_to_url" alt="Fork me on GitHub"></a> <script src="path_to_url"></script> <script> $('code').each(function(){ $(this).html(highlight($(this).text())); }); function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>') } </script> <script src="path_to_url"></script> <script> // Only use tocbot for main docs, not test docs if (document.querySelector('#superagent')) { tocbot.init({ // Where to render the table of contents. tocSelector: '#menu', // Where to grab the headings to build the table of contents. contentSelector: '#content', // Which headings to grab inside of the contentSelector element. headingSelector: 'h2', smoothScroll: false }); } </script> </body> </html> ```
/content/code_sandbox/node_modules/superagent/docs/tail.html
html
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
378
```javascript (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.superagent = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ "use strict"; /** * Expose `Emitter`. */ if (typeof module !== 'undefined') { module.exports = Emitter; } /** * Initialize a new `Emitter`. * * @api public */ function Emitter(obj) { if (obj) return mixin(obj); } ; /** * Mixin the emitter properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in Emitter.prototype) { obj[key] = Emitter.prototype[key]; } return obj; } /** * Listen on the given `event` with `fn`. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.on = Emitter.prototype.addEventListener = function (event, fn) { this._callbacks = this._callbacks || {}; (this._callbacks['$' + event] = this._callbacks['$' + event] || []).push(fn); return this; }; /** * Adds an `event` listener that will be invoked a single * time then automatically removed. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.once = function (event, fn) { function on() { this.off(event, on); fn.apply(this, arguments); } on.fn = fn; this.on(event, on); return this; }; /** * Remove the given callback for `event` or all * registered callbacks. * * @param {String} event * @param {Function} fn * @return {Emitter} * @api public */ Emitter.prototype.off = Emitter.prototype.removeListener = Emitter.prototype.removeAllListeners = Emitter.prototype.removeEventListener = function (event, fn) { this._callbacks = this._callbacks || {}; // all if (0 == arguments.length) { this._callbacks = {}; return this; } // specific event var callbacks = this._callbacks['$' + event]; if (!callbacks) return this; // remove all handlers if (1 == arguments.length) { delete this._callbacks['$' + event]; return this; } // remove specific handler var cb; for (var i = 0; i < callbacks.length; i++) { cb = callbacks[i]; if (cb === fn || cb.fn === fn) { callbacks.splice(i, 1); break; } } // Remove event specific arrays for event types that no // one is subscribed for to avoid memory leak. if (callbacks.length === 0) { delete this._callbacks['$' + event]; } return this; }; /** * Emit `event` with the given args. * * @param {String} event * @param {Mixed} ... * @return {Emitter} */ Emitter.prototype.emit = function (event) { this._callbacks = this._callbacks || {}; var args = new Array(arguments.length - 1), callbacks = this._callbacks['$' + event]; for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } if (callbacks) { callbacks = callbacks.slice(0); for (var i = 0, len = callbacks.length; i < len; ++i) { callbacks[i].apply(this, args); } } return this; }; /** * Return array of callbacks for `event`. * * @param {String} event * @return {Array} * @api public */ Emitter.prototype.listeners = function (event) { this._callbacks = this._callbacks || {}; return this._callbacks['$' + event] || []; }; /** * Check if this emitter has `event` handlers. * * @param {String} event * @return {Boolean} * @api public */ Emitter.prototype.hasListeners = function (event) { return !!this.listeners(event).length; }; },{}],2:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } module.exports = stringify; stringify.default = stringify; stringify.stable = deterministicStringify; stringify.stableStringify = deterministicStringify; var arr = []; var replacerStack = []; // Regular stringify function stringify(obj, replacer, spacer) { decirc(obj, '', [], undefined); var res; if (replacerStack.length === 0) { res = JSON.stringify(obj, replacer, spacer); } else { res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); } while (arr.length !== 0) { var part = arr.pop(); if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]); } else { part[0][part[1]] = part[2]; } } return res; } function decirc(val, k, stack, parent) { var i; if (_typeof(val) === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); if (propertyDescriptor.get !== undefined) { if (propertyDescriptor.configurable) { Object.defineProperty(parent, k, { value: '[Circular]' }); arr.push([parent, k, val, propertyDescriptor]); } else { replacerStack.push([val, k]); } } else { parent[k] = '[Circular]'; arr.push([parent, k, val]); } return; } } stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { decirc(val[i], i, stack, val); } } else { var keys = Object.keys(val); for (i = 0; i < keys.length; i++) { var key = keys[i]; decirc(val[key], key, stack, val); } } stack.pop(); } } // Stable-stringify function compareFunction(a, b) { if (a < b) { return -1; } if (a > b) { return 1; } return 0; } function deterministicStringify(obj, replacer, spacer) { var tmp = deterministicDecirc(obj, '', [], undefined) || obj; var res; if (replacerStack.length === 0) { res = JSON.stringify(tmp, replacer, spacer); } else { res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); } while (arr.length !== 0) { var part = arr.pop(); if (part.length === 4) { Object.defineProperty(part[0], part[1], part[3]); } else { part[0][part[1]] = part[2]; } } return res; } function deterministicDecirc(val, k, stack, parent) { var i; if (_typeof(val) === 'object' && val !== null) { for (i = 0; i < stack.length; i++) { if (stack[i] === val) { var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); if (propertyDescriptor.get !== undefined) { if (propertyDescriptor.configurable) { Object.defineProperty(parent, k, { value: '[Circular]' }); arr.push([parent, k, val, propertyDescriptor]); } else { replacerStack.push([val, k]); } } else { parent[k] = '[Circular]'; arr.push([parent, k, val]); } return; } } if (typeof val.toJSON === 'function') { return; } stack.push(val); // Optimize for Arrays. Big arrays could kill the performance otherwise! if (Array.isArray(val)) { for (i = 0; i < val.length; i++) { deterministicDecirc(val[i], i, stack, val); } } else { // Create a temporary object in the required way var tmp = {}; var keys = Object.keys(val).sort(compareFunction); for (i = 0; i < keys.length; i++) { var key = keys[i]; deterministicDecirc(val[key], key, stack, val); tmp[key] = val[key]; } if (parent !== undefined) { arr.push([parent, k, val]); parent[k] = tmp; } else { return tmp; } } stack.pop(); } } // wraps replacer function to handle values we couldn't replace // and mark them as [Circular] function replaceGetterValues(replacer) { replacer = replacer !== undefined ? replacer : function (k, v) { return v; }; return function (key, val) { if (replacerStack.length > 0) { for (var i = 0; i < replacerStack.length; i++) { var part = replacerStack[i]; if (part[1] === key && part[0] === val) { val = '[Circular]'; replacerStack.splice(i, 1); break; } } } return replacer.call(this, key, val); }; } },{}],3:[function(require,module,exports){ 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; var util = require('./utils'); var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = util.assign({ 'default': Format.RFC3986, formatters: { RFC1738: function RFC1738(value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function RFC3986(value) { return String(value); } } }, Format); },{"./utils":7}],4:[function(require,module,exports){ 'use strict'; var stringify = require('./stringify'); var parse = require('./parse'); var formats = require('./formats'); module.exports = { formats: formats, parse: parse, stringify: stringify }; },{"./formats":3,"./parse":5,"./stringify":6}],5:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function interpretNumericEntities(str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function parseArrayValue(val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; // This is what browsers will submit when the character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = utils.maybeMap(parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); }); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function parseObject(chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if (!isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && options.parseArrays && index <= options.arrayLimit) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; // eslint-disable-line no-param-reassign } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: typeof opts.depth === 'number' || opts.depth === false ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; },{"./utils":7}],6:[function(require,module,exports){ 'use strict'; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var utils = require('./utils'); var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var push = Array.prototype.push; var pushToArray = function pushToArray(arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || _typeof(v) === 'symbol' || typeof v === 'bigint'; }; var stringify = function stringify(object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }).join(','); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key') : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key'); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value'))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; var value = obj[key]; if (skipNulls && value === null) { continue; } var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(prefix, key) : prefix : prefix + (allowDots ? '.' + key : '[' + key + ']'); pushToArray(values, stringify(value, keyPrefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly, charset)); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && opts.encoder !== undefined && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (_typeof(obj) !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify(obj[key], key, generateArrayPrefix, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.formatter, options.encodeValuesOnly, options.charset)); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; },{"./formats":3,"./utils":7}],7:[function(require,module,exports){ 'use strict'; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }(); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (_typeof(source) !== 'object') { if (isArray(target)) { target.push(source); } else if (target && _typeof(target) === 'object') { if (options && (options.plainObjects || options.allowPrototypes) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || _typeof(target) !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && _typeof(targetItem) === 'object' && item && _typeof(item) === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function decode(str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (_typeof(str) === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if (c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || c >= 0x30 && c <= 0x39 // 0-9 || c >= 0x41 && c <= 0x5A // a-z || c >= 0x61 && c <= 0x7A // A-Z ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | c >> 6] + hexTable[0x80 | c & 0x3F]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | c >> 12] + hexTable[0x80 | c >> 6 & 0x3F] + hexTable[0x80 | c & 0x3F]); continue; } i += 1; c = 0x10000 + ((c & 0x3FF) << 10 | string.charCodeAt(i) & 0x3FF); out += hexTable[0xF0 | c >> 18] + hexTable[0x80 | c >> 12 & 0x3F] + hexTable[0x80 | c >> 6 & 0x3F] + hexTable[0x80 | c & 0x3F]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (_typeof(val) === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || _typeof(obj) !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, merge: merge }; },{}],8:[function(require,module,exports){ "use strict"; function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function Agent() { this._defaults = []; } ['use', 'on', 'once', 'set', 'query', 'type', 'accept', 'auth', 'withCredentials', 'sortQuery', 'retry', 'ok', 'redirects', 'timeout', 'buffer', 'serialize', 'parse', 'ca', 'key', 'pfx', 'cert', 'disableTLSCerts'].forEach(function (fn) { // Default setting for all requests from this agent Agent.prototype[fn] = function () { for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } this._defaults.push({ fn: fn, args: args }); return this; }; }); Agent.prototype._setDefaults = function (req) { this._defaults.forEach(function (def) { req[def.fn].apply(req, _toConsumableArray(def.args)); }); }; module.exports = Agent; },{}],9:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Check if `obj` is an object. * * @param {Object} obj * @return {Boolean} * @api private */ function isObject(obj) { return obj !== null && _typeof(obj) === 'object'; } module.exports = isObject; },{}],10:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Root reference for iframes. */ var root; if (typeof window !== 'undefined') { // Browser window root = window; } else if (typeof self === 'undefined') { // Other environments console.warn('Using browser-only version of superagent in non-browser environment'); root = void 0; } else { // Web Worker root = self; } var Emitter = require('component-emitter'); var safeStringify = require('fast-safe-stringify'); var qs = require('qs'); var RequestBase = require('./request-base'); var isObject = require('./is-object'); var ResponseBase = require('./response-base'); var Agent = require('./agent-base'); /** * Noop. */ function noop() {} /** * Expose `request`. */ module.exports = function (method, url) { // callback if (typeof url === 'function') { return new exports.Request('GET', method).end(url); } // url first if (arguments.length === 1) { return new exports.Request('GET', method); } return new exports.Request(method, url); }; exports = module.exports; var request = exports; exports.Request = Request; /** * Determine XHR. */ request.getXHR = function () { if (root.XMLHttpRequest && (!root.location || root.location.protocol !== 'file:' || !root.ActiveXObject)) { return new XMLHttpRequest(); } try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (_unused) {} try { return new ActiveXObject('Msxml2.XMLHTTP.6.0'); } catch (_unused2) {} try { return new ActiveXObject('Msxml2.XMLHTTP.3.0'); } catch (_unused3) {} try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (_unused4) {} throw new Error('Browser-only version of superagent could not find XHR'); }; /** * Removes leading and trailing whitespace, added to support IE. * * @param {String} s * @return {String} * @api private */ var trim = ''.trim ? function (s) { return s.trim(); } : function (s) { return s.replace(/(^\s*|\s*$)/g, ''); }; /** * Serialize the given `obj`. * * @param {Object} obj * @return {String} * @api private */ function serialize(obj) { if (!isObject(obj)) return obj; var pairs = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) pushEncodedKeyValuePair(pairs, key, obj[key]); } return pairs.join('&'); } /** * Helps 'serialize' with serializing arrays. * Mutates the pairs array. * * @param {Array} pairs * @param {String} key * @param {Mixed} val */ function pushEncodedKeyValuePair(pairs, key, val) { if (val === undefined) return; if (val === null) { pairs.push(encodeURI(key)); return; } if (Array.isArray(val)) { val.forEach(function (v) { pushEncodedKeyValuePair(pairs, key, v); }); } else if (isObject(val)) { for (var subkey in val) { if (Object.prototype.hasOwnProperty.call(val, subkey)) pushEncodedKeyValuePair(pairs, "".concat(key, "[").concat(subkey, "]"), val[subkey]); } } else { pairs.push(encodeURI(key) + '=' + encodeURIComponent(val)); } } /** * Expose serialization method. */ request.serializeObject = serialize; /** * Parse the given x-www-form-urlencoded `str`. * * @param {String} str * @return {Object} * @api private */ function parseString(str) { var obj = {}; var pairs = str.split('&'); var pair; var pos; for (var i = 0, len = pairs.length; i < len; ++i) { pair = pairs[i]; pos = pair.indexOf('='); if (pos === -1) { obj[decodeURIComponent(pair)] = ''; } else { obj[decodeURIComponent(pair.slice(0, pos))] = decodeURIComponent(pair.slice(pos + 1)); } } return obj; } /** * Expose parser. */ request.parseString = parseString; /** * Default MIME type map. * * superagent.types.xml = 'application/xml'; * */ request.types = { html: 'text/html', json: 'application/json', xml: 'text/xml', urlencoded: 'application/x-www-form-urlencoded', form: 'application/x-www-form-urlencoded', 'form-data': 'application/x-www-form-urlencoded' }; /** * Default serialization map. * * superagent.serialize['application/xml'] = function(obj){ * return 'generated xml here'; * }; * */ request.serialize = { 'application/x-www-form-urlencoded': qs.stringify, 'application/json': safeStringify }; /** * Default parsers. * * superagent.parse['application/xml'] = function(str){ * return { object parsed from str }; * }; * */ request.parse = { 'application/x-www-form-urlencoded': parseString, 'application/json': JSON.parse }; /** * Parse the given header `str` into * an object containing the mapped fields. * * @param {String} str * @return {Object} * @api private */ function parseHeader(str) { var lines = str.split(/\r?\n/); var fields = {}; var index; var line; var field; var val; for (var i = 0, len = lines.length; i < len; ++i) { line = lines[i]; index = line.indexOf(':'); if (index === -1) { // could be empty line, just skip it continue; } field = line.slice(0, index).toLowerCase(); val = trim(line.slice(index + 1)); fields[field] = val; } return fields; } /** * Check if `mime` is json or has +json structured syntax suffix. * * @param {String} mime * @return {Boolean} * @api private */ function isJSON(mime) { // should match /json or +json // but not /json-seq return /[/+]json($|[^-\w])/i.test(mime); } /** * Initialize a new `Response` with the given `xhr`. * * - set flags (.ok, .error, etc) * - parse header * * Examples: * * Aliasing `superagent` as `request` is nice: * * request = superagent; * * We can use the promise-like API, or pass callbacks: * * request.get('/').end(function(res){}); * request.get('/', function(res){}); * * Sending data can be chained: * * request * .post('/user') * .send({ name: 'tj' }) * .end(function(res){}); * * Or passed to `.send()`: * * request * .post('/user') * .send({ name: 'tj' }, function(res){}); * * Or passed to `.post()`: * * request * .post('/user', { name: 'tj' }) * .end(function(res){}); * * Or further reduced to a single call for simple cases: * * request * .post('/user', { name: 'tj' }, function(res){}); * * @param {XMLHTTPRequest} xhr * @param {Object} options * @api private */ function Response(req) { this.req = req; this.xhr = this.req.xhr; // responseText is accessible only if responseType is '' or 'text' and on older browsers this.text = this.req.method !== 'HEAD' && (this.xhr.responseType === '' || this.xhr.responseType === 'text') || typeof this.xhr.responseType === 'undefined' ? this.xhr.responseText : null; this.statusText = this.req.xhr.statusText; var status = this.xhr.status; // handle IE9 bug: path_to_url if (status === 1223) { status = 204; } this._setStatusProperties(status); this.headers = parseHeader(this.xhr.getAllResponseHeaders()); this.header = this.headers; // getAllResponseHeaders sometimes falsely returns "" for CORS requests, but // getResponseHeader still works. so we get content-type even if getting // other headers fails. this.header['content-type'] = this.xhr.getResponseHeader('content-type'); this._setHeaderProperties(this.header); if (this.text === null && req._responseType) { this.body = this.xhr.response; } else { this.body = this.req.method === 'HEAD' ? null : this._parseBody(this.text ? this.text : this.xhr.response); } } // eslint-disable-next-line new-cap ResponseBase(Response.prototype); /** * Parse the given body `str`. * * Used for auto-parsing of bodies. Parsers * are defined on the `superagent.parse` object. * * @param {String} str * @return {Mixed} * @api private */ Response.prototype._parseBody = function (str) { var parse = request.parse[this.type]; if (this.req._parser) { return this.req._parser(this, str); } if (!parse && isJSON(this.type)) { parse = request.parse['application/json']; } return parse && str && (str.length > 0 || str instanceof Object) ? parse(str) : null; }; /** * Return an `Error` representative of this response. * * @return {Error} * @api public */ Response.prototype.toError = function () { var req = this.req; var method = req.method; var url = req.url; var msg = "cannot ".concat(method, " ").concat(url, " (").concat(this.status, ")"); var err = new Error(msg); err.status = this.status; err.method = method; err.url = url; return err; }; /** * Expose `Response`. */ request.Response = Response; /** * Initialize a new `Request` with the given `method` and `url`. * * @param {String} method * @param {String} url * @api public */ function Request(method, url) { var self = this; this._query = this._query || []; this.method = method; this.url = url; this.header = {}; // preserves header name case this._header = {}; // coerces header names to lowercase this.on('end', function () { var err = null; var res = null; try { res = new Response(self); } catch (err_) { err = new Error('Parser is unable to parse the response'); err.parse = true; err.original = err_; // issue #675: return the raw response if the response parsing fails if (self.xhr) { // ie9 doesn't have 'response' property err.rawResponse = typeof self.xhr.responseType === 'undefined' ? self.xhr.responseText : self.xhr.response; // issue #876: return the http status code if the response parsing fails err.status = self.xhr.status ? self.xhr.status : null; err.statusCode = err.status; // backwards-compat only } else { err.rawResponse = null; err.status = null; } return self.callback(err); } self.emit('response', res); var new_err; try { if (!self._isResponseOK(res)) { new_err = new Error(res.statusText || res.text || 'Unsuccessful HTTP response'); } } catch (err_) { new_err = err_; // ok() callback can throw } // #1000 don't catch errors from the callback to avoid double calling it if (new_err) { new_err.original = err; new_err.response = res; new_err.status = res.status; self.callback(new_err, res); } else { self.callback(null, res); } }); } /** * Mixin `Emitter` and `RequestBase`. */ // eslint-disable-next-line new-cap Emitter(Request.prototype); // eslint-disable-next-line new-cap RequestBase(Request.prototype); /** * Set Content-Type to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.xml = 'application/xml'; * * request.post('/') * .type('xml') * .send(xmlstring) * .end(callback); * * request.post('/') * .type('application/xml') * .send(xmlstring) * .end(callback); * * @param {String} type * @return {Request} for chaining * @api public */ Request.prototype.type = function (type) { this.set('Content-Type', request.types[type] || type); return this; }; /** * Set Accept to `type`, mapping values from `request.types`. * * Examples: * * superagent.types.json = 'application/json'; * * request.get('/agent') * .accept('json') * .end(callback); * * request.get('/agent') * .accept('application/json') * .end(callback); * * @param {String} accept * @return {Request} for chaining * @api public */ Request.prototype.accept = function (type) { this.set('Accept', request.types[type] || type); return this; }; /** * Set Authorization field value with `user` and `pass`. * * @param {String} user * @param {String} [pass] optional in case of using 'bearer' as type * @param {Object} options with 'type' property 'auto', 'basic' or 'bearer' (default 'basic') * @return {Request} for chaining * @api public */ Request.prototype.auth = function (user, pass, options) { if (arguments.length === 1) pass = ''; if (_typeof(pass) === 'object' && pass !== null) { // pass is optional and can be replaced with options options = pass; pass = ''; } if (!options) { options = { type: typeof btoa === 'function' ? 'basic' : 'auto' }; } var encoder = function encoder(string) { if (typeof btoa === 'function') { return btoa(string); } throw new Error('Cannot use basic auth, btoa is not a function'); }; return this._auth(user, pass, options, encoder); }; /** * Add query-string `val`. * * Examples: * * request.get('/shoes') * .query('size=10') * .query({ color: 'blue' }) * * @param {Object|String} val * @return {Request} for chaining * @api public */ Request.prototype.query = function (val) { if (typeof val !== 'string') val = serialize(val); if (val) this._query.push(val); return this; }; /** * Queue the given `file` as an attachment to the specified `field`, * with optional `options` (or filename). * * ``` js * request.post('/upload') * .attach('content', new Blob(['<a id="a"><b id="b">hey!</b></a>'], { type: "text/html"})) * .end(callback); * ``` * * @param {String} field * @param {Blob|File} file * @param {String|Object} options * @return {Request} for chaining * @api public */ Request.prototype.attach = function (field, file, options) { if (file) { if (this._data) { throw new Error("superagent can't mix .send() and .attach()"); } this._getFormData().append(field, file, options || file.name); } return this; }; Request.prototype._getFormData = function () { if (!this._formData) { this._formData = new root.FormData(); } return this._formData; }; /** * Invoke the callback with `err` and `res` * and handle arity check. * * @param {Error} err * @param {Response} res * @api private */ Request.prototype.callback = function (err, res) { if (this._shouldRetry(err, res)) { return this._retry(); } var fn = this._callback; this.clearTimeout(); if (err) { if (this._maxRetries) err.retries = this._retries - 1; this.emit('error', err); } fn(err, res); }; /** * Invoke callback with x-domain error. * * @api private */ Request.prototype.crossDomainError = function () { var err = new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.'); err.crossDomain = true; err.status = this.status; err.method = this.method; err.url = this.url; this.callback(err); }; // This only warns, because the request is still likely to work Request.prototype.agent = function () { console.warn('This is not supported in browser version of superagent'); return this; }; Request.prototype.ca = Request.prototype.agent; Request.prototype.buffer = Request.prototype.ca; // This throws, because it can't send/receive data as expected Request.prototype.write = function () { throw new Error('Streaming is not supported in browser version of superagent'); }; Request.prototype.pipe = Request.prototype.write; /** * Check if `obj` is a host object, * we don't want to serialize these :) * * @param {Object} obj host object * @return {Boolean} is a host object * @api private */ Request.prototype._isHost = function (obj) { // Native objects stringify to [object File], [object Blob], [object FormData], etc. return obj && _typeof(obj) === 'object' && !Array.isArray(obj) && Object.prototype.toString.call(obj) !== '[object Object]'; }; /** * Initiate request, invoking callback `fn(res)` * with an instanceof `Response`. * * @param {Function} fn * @return {Request} for chaining * @api public */ Request.prototype.end = function (fn) { if (this._endCalled) { console.warn('Warning: .end() was called twice. This is not supported in superagent'); } this._endCalled = true; // store callback this._callback = fn || noop; // querystring this._finalizeQueryString(); this._end(); }; Request.prototype._setUploadTimeout = function () { var self = this; // upload timeout it's wokrs only if deadline timeout is off if (this._uploadTimeout && !this._uploadTimeoutTimer) { this._uploadTimeoutTimer = setTimeout(function () { self._timeoutError('Upload timeout of ', self._uploadTimeout, 'ETIMEDOUT'); }, this._uploadTimeout); } }; // eslint-disable-next-line complexity Request.prototype._end = function () { if (this._aborted) return this.callback(new Error('The request has been aborted even before .end() was called')); var self = this; this.xhr = request.getXHR(); var xhr = this.xhr; var data = this._formData || this._data; this._setTimeouts(); // state change xhr.onreadystatechange = function () { var readyState = xhr.readyState; if (readyState >= 2 && self._responseTimeoutTimer) { clearTimeout(self._responseTimeoutTimer); } if (readyState !== 4) { return; } // In IE9, reads to any property (e.g. status) off of an aborted XHR will // result in the error "Could not complete the operation due to error c00c023f" var status; try { status = xhr.status; } catch (_unused5) { status = 0; } if (!status) { if (self.timedout || self._aborted) return; return self.crossDomainError(); } self.emit('end'); }; // progress var handleProgress = function handleProgress(direction, e) { if (e.total > 0) { e.percent = e.loaded / e.total * 100; if (e.percent === 100) { clearTimeout(self._uploadTimeoutTimer); } } e.direction = direction; self.emit('progress', e); }; if (this.hasListeners('progress')) { try { xhr.addEventListener('progress', handleProgress.bind(null, 'download')); if (xhr.upload) { xhr.upload.addEventListener('progress', handleProgress.bind(null, 'upload')); } } catch (_unused6) {// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. // Reported here: // path_to_url } } if (xhr.upload) { this._setUploadTimeout(); } // initiate request try { if (this.username && this.password) { xhr.open(this.method, this.url, true, this.username, this.password); } else { xhr.open(this.method, this.url, true); } } catch (err) { // see #1149 return this.callback(err); } // CORS if (this._withCredentials) xhr.withCredentials = true; // body if (!this._formData && this.method !== 'GET' && this.method !== 'HEAD' && typeof data !== 'string' && !this._isHost(data)) { // serialize stuff var contentType = this._header['content-type']; var _serialize = this._serializer || request.serialize[contentType ? contentType.split(';')[0] : '']; if (!_serialize && isJSON(contentType)) { _serialize = request.serialize['application/json']; } if (_serialize) data = _serialize(data); } // set header fields for (var field in this.header) { if (this.header[field] === null) continue; if (Object.prototype.hasOwnProperty.call(this.header, field)) xhr.setRequestHeader(field, this.header[field]); } if (this._responseType) { xhr.responseType = this._responseType; } // send stuff this.emit('request', this); // IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) // We need null here if data is undefined xhr.send(typeof data === 'undefined' ? null : data); }; request.agent = function () { return new Agent(); }; ['GET', 'POST', 'OPTIONS', 'PATCH', 'PUT', 'DELETE'].forEach(function (method) { Agent.prototype[method.toLowerCase()] = function (url, fn) { var req = new request.Request(method, url); this._setDefaults(req); if (fn) { req.end(fn); } return req; }; }); Agent.prototype.del = Agent.prototype.delete; /** * GET `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.get = function (url, data, fn) { var req = request('GET', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * HEAD `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.head = function (url, data, fn) { var req = request('HEAD', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.query(data); if (fn) req.end(fn); return req; }; /** * OPTIONS query to `url` with optional callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.options = function (url, data, fn) { var req = request('OPTIONS', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * DELETE `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ function del(url, data, fn) { var req = request('DELETE', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; } request.del = del; request.delete = del; /** * PATCH `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.patch = function (url, data, fn) { var req = request('PATCH', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * POST `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed} [data] * @param {Function} [fn] * @return {Request} * @api public */ request.post = function (url, data, fn) { var req = request('POST', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; /** * PUT `url` with optional `data` and callback `fn(res)`. * * @param {String} url * @param {Mixed|Function} [data] or fn * @param {Function} [fn] * @return {Request} * @api public */ request.put = function (url, data, fn) { var req = request('PUT', url); if (typeof data === 'function') { fn = data; data = null; } if (data) req.send(data); if (fn) req.end(fn); return req; }; },{"./agent-base":8,"./is-object":9,"./request-base":11,"./response-base":12,"component-emitter":1,"fast-safe-stringify":2,"qs":4}],11:[function(require,module,exports){ "use strict"; function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } /** * Module of mixed-in functions shared between node and client code */ var isObject = require('./is-object'); /** * Expose `RequestBase`. */ module.exports = RequestBase; /** * Initialize a new `RequestBase`. * * @api public */ function RequestBase(object) { if (object) return mixin(object); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(object) { for (var key in RequestBase.prototype) { if (Object.prototype.hasOwnProperty.call(RequestBase.prototype, key)) object[key] = RequestBase.prototype[key]; } return object; } /** * Clear previous timeout. * * @return {Request} for chaining * @api public */ RequestBase.prototype.clearTimeout = function () { clearTimeout(this._timer); clearTimeout(this._responseTimeoutTimer); clearTimeout(this._uploadTimeoutTimer); delete this._timer; delete this._responseTimeoutTimer; delete this._uploadTimeoutTimer; return this; }; /** * Override default response body parser * * This function will be called to convert incoming data into request.body * * @param {Function} * @api public */ RequestBase.prototype.parse = function (fn) { this._parser = fn; return this; }; /** * Set format of binary response body. * In browser valid formats are 'blob' and 'arraybuffer', * which return Blob and ArrayBuffer, respectively. * * In Node all values result in Buffer. * * Examples: * * req.get('/') * .responseType('blob') * .end(callback); * * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.responseType = function (value) { this._responseType = value; return this; }; /** * Override default request body serializer * * This function will be called to convert data set via .send or .attach into payload to send * * @param {Function} * @api public */ RequestBase.prototype.serialize = function (fn) { this._serializer = fn; return this; }; /** * Set timeouts. * * - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time. * - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections. * - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off * * Value of 0 or false means no timeout. * * @param {Number|Object} ms or {response, deadline} * @return {Request} for chaining * @api public */ RequestBase.prototype.timeout = function (options) { if (!options || _typeof(options) !== 'object') { this._timeout = options; this._responseTimeout = 0; this._uploadTimeout = 0; return this; } for (var option in options) { if (Object.prototype.hasOwnProperty.call(options, option)) { switch (option) { case 'deadline': this._timeout = options.deadline; break; case 'response': this._responseTimeout = options.response; break; case 'upload': this._uploadTimeout = options.upload; break; default: console.warn('Unknown timeout option', option); } } } return this; }; /** * Set number of retry attempts on error. * * Failed requests will be retried 'count' times if timeout or err.code >= 500. * * @param {Number} count * @param {Function} [fn] * @return {Request} for chaining * @api public */ RequestBase.prototype.retry = function (count, fn) { // Default to 1 if no count passed or true if (arguments.length === 0 || count === true) count = 1; if (count <= 0) count = 0; this._maxRetries = count; this._retries = 0; this._retryCallback = fn; return this; }; // // NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package // <path_to_url // // NOTE: we do not include EADDRINFO because it was removed from libuv in 2014 // <path_to_url // <path_to_url // // // TODO: expose these as configurable defaults // var ERROR_CODES = new Set(['ETIMEDOUT', 'ECONNRESET', 'EADDRINUSE', 'ECONNREFUSED', 'EPIPE', 'ENOTFOUND', 'ENETUNREACH', 'EAI_AGAIN']); var STATUS_CODES = new Set([408, 413, 429, 500, 502, 503, 504, 521, 522, 524]); // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) // const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']); /** * Determine if a request should be retried. * (Inspired by path_to_url#retry) * * @param {Error} err an error * @param {Response} [res] response * @returns {Boolean} if segment should be retried */ RequestBase.prototype._shouldRetry = function (err, res) { if (!this._maxRetries || this._retries++ >= this._maxRetries) { return false; } if (this._retryCallback) { try { var override = this._retryCallback(err, res); if (override === true) return true; if (override === false) return false; // undefined falls back to defaults } catch (err_) { console.error(err_); } } // TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST) /* if ( this.req && this.req.method && !METHODS.has(this.req.method.toUpperCase()) ) return false; */ if (res && res.status && STATUS_CODES.has(res.status)) return true; if (err) { if (err.code && ERROR_CODES.has(err.code)) return true; // Superagent timeout if (err.timeout && err.code === 'ECONNABORTED') return true; if (err.crossDomain) return true; } return false; }; /** * Retry request * * @return {Request} for chaining * @api private */ RequestBase.prototype._retry = function () { this.clearTimeout(); // node if (this.req) { this.req = null; this.req = this.request(); } this._aborted = false; this.timedout = false; this.timedoutError = null; return this._end(); }; /** * Promise support * * @param {Function} resolve * @param {Function} [reject] * @return {Request} */ RequestBase.prototype.then = function (resolve, reject) { var _this = this; if (!this._fullfilledPromise) { var self = this; if (this._endCalled) { console.warn('Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'); } this._fullfilledPromise = new Promise(function (resolve, reject) { self.on('abort', function () { if (_this._maxRetries && _this._maxRetries > _this._retries) { return; } if (_this.timedout && _this.timedoutError) { reject(_this.timedoutError); return; } var err = new Error('Aborted'); err.code = 'ABORTED'; err.status = _this.status; err.method = _this.method; err.url = _this.url; reject(err); }); self.end(function (err, res) { if (err) reject(err);else resolve(res); }); }); } return this._fullfilledPromise.then(resolve, reject); }; RequestBase.prototype.catch = function (cb) { return this.then(undefined, cb); }; /** * Allow for extension */ RequestBase.prototype.use = function (fn) { fn(this); return this; }; RequestBase.prototype.ok = function (cb) { if (typeof cb !== 'function') throw new Error('Callback required'); this._okCallback = cb; return this; }; RequestBase.prototype._isResponseOK = function (res) { if (!res) { return false; } if (this._okCallback) { return this._okCallback(res); } return res.status >= 200 && res.status < 300; }; /** * Get request header `field`. * Case-insensitive. * * @param {String} field * @return {String} * @api public */ RequestBase.prototype.get = function (field) { return this._header[field.toLowerCase()]; }; /** * Get case-insensitive header `field` value. * This is a deprecated internal API. Use `.get(field)` instead. * * (getHeader is no longer used internally by the superagent code base) * * @param {String} field * @return {String} * @api private * @deprecated */ RequestBase.prototype.getHeader = RequestBase.prototype.get; /** * Set header `field` to `val`, or multiple fields with one object. * Case-insensitive. * * Examples: * * req.get('/') * .set('Accept', 'application/json') * .set('X-API-Key', 'foobar') * .end(callback); * * req.get('/') * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) * .end(callback); * * @param {String|Object} field * @param {String} val * @return {Request} for chaining * @api public */ RequestBase.prototype.set = function (field, value) { if (isObject(field)) { for (var key in field) { if (Object.prototype.hasOwnProperty.call(field, key)) this.set(key, field[key]); } return this; } this._header[field.toLowerCase()] = value; this.header[field] = value; return this; }; /** * Remove header `field`. * Case-insensitive. * * Example: * * req.get('/') * .unset('User-Agent') * .end(callback); * * @param {String} field field name */ RequestBase.prototype.unset = function (field) { delete this._header[field.toLowerCase()]; delete this.header[field]; return this; }; /** * Write the field `name` and `val`, or multiple fields with one object * for "multipart/form-data" request bodies. * * ``` js * request.post('/upload') * .field('foo', 'bar') * .end(callback); * * request.post('/upload') * .field({ foo: 'bar', baz: 'qux' }) * .end(callback); * ``` * * @param {String|Object} name name of field * @param {String|Blob|File|Buffer|fs.ReadStream} val value of field * @return {Request} for chaining * @api public */ RequestBase.prototype.field = function (name, value) { // name should be either a string or an object. if (name === null || undefined === name) { throw new Error('.field(name, val) name can not be empty'); } if (this._data) { throw new Error(".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"); } if (isObject(name)) { for (var key in name) { if (Object.prototype.hasOwnProperty.call(name, key)) this.field(key, name[key]); } return this; } if (Array.isArray(value)) { for (var i in value) { if (Object.prototype.hasOwnProperty.call(value, i)) this.field(name, value[i]); } return this; } // val should be defined now if (value === null || undefined === value) { throw new Error('.field(name, val) val can not be empty'); } if (typeof value === 'boolean') { value = String(value); } this._getFormData().append(name, value); return this; }; /** * Abort the request, and clear potential timeout. * * @return {Request} request * @api public */ RequestBase.prototype.abort = function () { if (this._aborted) { return this; } this._aborted = true; if (this.xhr) this.xhr.abort(); // browser if (this.req) this.req.abort(); // node this.clearTimeout(); this.emit('abort'); return this; }; RequestBase.prototype._auth = function (user, pass, options, base64Encoder) { switch (options.type) { case 'basic': this.set('Authorization', "Basic ".concat(base64Encoder("".concat(user, ":").concat(pass)))); break; case 'auto': this.username = user; this.password = pass; break; case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' }) this.set('Authorization', "Bearer ".concat(user)); break; default: break; } return this; }; /** * Enable transmission of cookies with x-domain requests. * * Note that for this to work the origin must not be * using "Access-Control-Allow-Origin" with a wildcard, * and also must set "Access-Control-Allow-Credentials" * to "true". * * @api public */ RequestBase.prototype.withCredentials = function (on) { // This is browser-only functionality. Node side is no-op. if (on === undefined) on = true; this._withCredentials = on; return this; }; /** * Set the max redirects to `n`. Does nothing in browser XHR implementation. * * @param {Number} n * @return {Request} for chaining * @api public */ RequestBase.prototype.redirects = function (n) { this._maxRedirects = n; return this; }; /** * Maximum size of buffered response body, in bytes. Counts uncompressed size. * Default 200MB. * * @param {Number} n number of bytes * @return {Request} for chaining */ RequestBase.prototype.maxResponseSize = function (n) { if (typeof n !== 'number') { throw new TypeError('Invalid argument'); } this._maxResponseSize = n; return this; }; /** * Convert to a plain javascript object (not JSON string) of scalar properties. * Note as this method is designed to return a useful non-this value, * it cannot be chained. * * @return {Object} describing method, url, and data of this request * @api public */ RequestBase.prototype.toJSON = function () { return { method: this.method, url: this.url, data: this._data, headers: this._header }; }; /** * Send `data` as the request body, defaulting the `.type()` to "json" when * an object is given. * * Examples: * * // manual json * request.post('/user') * .type('json') * .send('{"name":"tj"}') * .end(callback) * * // auto json * request.post('/user') * .send({ name: 'tj' }) * .end(callback) * * // manual x-www-form-urlencoded * request.post('/user') * .type('form') * .send('name=tj') * .end(callback) * * // auto x-www-form-urlencoded * request.post('/user') * .type('form') * .send({ name: 'tj' }) * .end(callback) * * // defaults to x-www-form-urlencoded * request.post('/user') * .send('name=tobi') * .send('species=ferret') * .end(callback) * * @param {String|Object} data * @return {Request} for chaining * @api public */ // eslint-disable-next-line complexity RequestBase.prototype.send = function (data) { var isObject_ = isObject(data); var type = this._header['content-type']; if (this._formData) { throw new Error(".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"); } if (isObject_ && !this._data) { if (Array.isArray(data)) { this._data = []; } else if (!this._isHost(data)) { this._data = {}; } } else if (data && this._data && this._isHost(this._data)) { throw new Error("Can't merge these send calls"); } // merge if (isObject_ && isObject(this._data)) { for (var key in data) { if (Object.prototype.hasOwnProperty.call(data, key)) this._data[key] = data[key]; } } else if (typeof data === 'string') { // default to x-www-form-urlencoded if (!type) this.type('form'); type = this._header['content-type']; if (type) type = type.toLowerCase().trim(); if (type === 'application/x-www-form-urlencoded') { this._data = this._data ? "".concat(this._data, "&").concat(data) : data; } else { this._data = (this._data || '') + data; } } else { this._data = data; } if (!isObject_ || this._isHost(data)) { return this; } // default to json if (!type) this.type('json'); return this; }; /** * Sort `querystring` by the sort function * * * Examples: * * // default order * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery() * .end(callback) * * // customized sort function * request.get('/user') * .query('name=Nick') * .query('search=Manny') * .sortQuery(function(a, b){ * return a.length - b.length; * }) * .end(callback) * * * @param {Function} sort * @return {Request} for chaining * @api public */ RequestBase.prototype.sortQuery = function (sort) { // _sort default to true but otherwise can be a function or boolean this._sort = typeof sort === 'undefined' ? true : sort; return this; }; /** * Compose querystring to append to req.url * * @api private */ RequestBase.prototype._finalizeQueryString = function () { var query = this._query.join('&'); if (query) { this.url += (this.url.includes('?') ? '&' : '?') + query; } this._query.length = 0; // Makes the call idempotent if (this._sort) { var index = this.url.indexOf('?'); if (index >= 0) { var queryArray = this.url.slice(index + 1).split('&'); if (typeof this._sort === 'function') { queryArray.sort(this._sort); } else { queryArray.sort(); } this.url = this.url.slice(0, index) + '?' + queryArray.join('&'); } } }; // For backwards compat only RequestBase.prototype._appendQueryString = function () { console.warn('Unsupported'); }; /** * Invoke callback with timeout error. * * @api private */ RequestBase.prototype._timeoutError = function (reason, timeout, errno) { if (this._aborted) { return; } var err = new Error("".concat(reason + timeout, "ms exceeded")); err.timeout = timeout; err.code = 'ECONNABORTED'; err.errno = errno; this.timedout = true; this.timedoutError = err; this.abort(); this.callback(err); }; RequestBase.prototype._setTimeouts = function () { var self = this; // deadline if (this._timeout && !this._timer) { this._timer = setTimeout(function () { self._timeoutError('Timeout of ', self._timeout, 'ETIME'); }, this._timeout); } // response timeout if (this._responseTimeout && !this._responseTimeoutTimer) { this._responseTimeoutTimer = setTimeout(function () { self._timeoutError('Response timeout of ', self._responseTimeout, 'ETIMEDOUT'); }, this._responseTimeout); } }; },{"./is-object":9}],12:[function(require,module,exports){ "use strict"; /** * Module dependencies. */ var utils = require('./utils'); /** * Expose `ResponseBase`. */ module.exports = ResponseBase; /** * Initialize a new `ResponseBase`. * * @api public */ function ResponseBase(obj) { if (obj) return mixin(obj); } /** * Mixin the prototype properties. * * @param {Object} obj * @return {Object} * @api private */ function mixin(obj) { for (var key in ResponseBase.prototype) { if (Object.prototype.hasOwnProperty.call(ResponseBase.prototype, key)) obj[key] = ResponseBase.prototype[key]; } return obj; } /** * Get case-insensitive `field` value. * * @param {String} field * @return {String} * @api public */ ResponseBase.prototype.get = function (field) { return this.header[field.toLowerCase()]; }; /** * Set header related properties: * * - `.type` the content type without params * * A response of "Content-Type: text/plain; charset=utf-8" * will provide you with a `.type` of "text/plain". * * @param {Object} header * @api private */ ResponseBase.prototype._setHeaderProperties = function (header) { // TODO: moar! // TODO: make this a util // content-type var ct = header['content-type'] || ''; this.type = utils.type(ct); // params var params = utils.params(ct); for (var key in params) { if (Object.prototype.hasOwnProperty.call(params, key)) this[key] = params[key]; } this.links = {}; // links try { if (header.link) { this.links = utils.parseLinks(header.link); } } catch (_unused) {// ignore } }; /** * Set flags such as `.ok` based on `status`. * * For example a 2xx response will give you a `.ok` of __true__ * whereas 5xx will be __false__ and `.error` will be __true__. The * `.clientError` and `.serverError` are also available to be more * specific, and `.statusType` is the class of error ranging from 1..5 * sometimes useful for mapping respond colors etc. * * "sugar" properties are also defined for common cases. Currently providing: * * - .noContent * - .badRequest * - .unauthorized * - .notAcceptable * - .notFound * * @param {Number} status * @api private */ ResponseBase.prototype._setStatusProperties = function (status) { var type = status / 100 | 0; // status / class this.statusCode = status; this.status = this.statusCode; this.statusType = type; // basics this.info = type === 1; this.ok = type === 2; this.redirect = type === 3; this.clientError = type === 4; this.serverError = type === 5; this.error = type === 4 || type === 5 ? this.toError() : false; // sugar this.created = status === 201; this.accepted = status === 202; this.noContent = status === 204; this.badRequest = status === 400; this.unauthorized = status === 401; this.notAcceptable = status === 406; this.forbidden = status === 403; this.notFound = status === 404; this.unprocessableEntity = status === 422; }; },{"./utils":13}],13:[function(require,module,exports){ "use strict"; function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } /** * Return the mime type for the given `str`. * * @param {String} str * @return {String} * @api private */ exports.type = function (str) { return str.split(/ *; */).shift(); }; /** * Return header field parameters. * * @param {String} str * @return {Object} * @api private */ exports.params = function (val) { var obj = {}; var _iterator = _createForOfIteratorHelper(val.split(/ *; */)), _step; try { for (_iterator.s(); !(_step = _iterator.n()).done;) { var str = _step.value; var parts = str.split(/ *= */); var key = parts.shift(); var _val = parts.shift(); if (key && _val) obj[key] = _val; } } catch (err) { _iterator.e(err); } finally { _iterator.f(); } return obj; }; /** * Parse Link header fields. * * @param {String} str * @return {Object} * @api private */ exports.parseLinks = function (val) { var obj = {}; var _iterator2 = _createForOfIteratorHelper(val.split(/ *, */)), _step2; try { for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { var str = _step2.value; var parts = str.split(/ *; */); var url = parts[0].slice(1, -1); var rel = parts[1].split(/ *= */)[1].slice(1, -1); obj[rel] = url; } } catch (err) { _iterator2.e(err); } finally { _iterator2.f(); } return obj; }; /** * Strip content related fields from `header`. * * @param {Object} header * @return {Object} header * @api private */ exports.cleanHeader = function (header, changesOrigin) { delete header['content-type']; delete header['content-length']; delete header['transfer-encoding']; delete header.host; // secuirty if (changesOrigin) { delete header.authorization; delete header.cookie; } return header; }; },{}]},{},[10])(10) }); ```
/content/code_sandbox/node_modules/superagent/dist/superagent.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
21,839
```css body { padding: 40px 80px; font: 14px/1.5 "Helvetica Neue", Helvetica, sans-serif; background: #181818 url(images/bg.png); text-align: center; } #content { margin: 0 auto; padding: 10px 40px; text-align: left; background: white; width: 50%; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; -webkit-box-shadow: 0 2px 5px 0 black; } #menu { font-size: 13px; margin: 0; padding: 0; text-align: left; position: fixed; top: 15px; left: 15px; } #menu ul { margin: 0; padding: 0; } #menu li { list-style: none; } #menu a { color: rgba(255,255,255,.5); text-decoration: none; } #menu a:hover { color: white; } #menu .active a { color: white; } pre { padding: 10px; } code { font-family: monaco, monospace, sans-serif; font-size: 0.85em; } p code { border: 1px solid #ECEA75; padding: 1px 3px; -webkit-border-radius: 2px; -moz-border-radius: 2px; border-radius: 2px; background: #FDFCD1; } pre { padding: 20px 25px; border: 1px solid #ddd; -webkit-box-shadow: inset 0 0 5px #eee; -moz-box-shadow: inset 0 0 5px #eee; box-shadow: inset 0 0 5px #eee; } code .comment { color: #ddd } code .init { color: #2F6FAD } code .string { color: #5890AD } code .keyword { color: #8A6343 } code .number { color: #2F6FAD } /* override tocbot style to avoid vertical white line in table of content */ .toc-link::before { content: initial; } ```
/content/code_sandbox/node_modules/superagent/docs/style.css
css
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
515
```javascript var CombinedStream = require('combined-stream'); var util = require('util'); var path = require('path'); var http = require('http'); var https = require('https'); var parseUrl = require('url').parse; var fs = require('fs'); var mime = require('mime-types'); var asynckit = require('asynckit'); var populate = require('./populate.js'); // Public API module.exports = FormData; // make it a Stream util.inherits(FormData, CombinedStream); /** * Create readable "multipart/form-data" streams. * Can be used to submit forms * and file uploads to other web applications. * * @constructor * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream */ function FormData(options) { if (!(this instanceof FormData)) { return new FormData(options); } this._overheadLength = 0; this._valueLength = 0; this._valuesToMeasure = []; CombinedStream.call(this); options = options || {}; for (var option in options) { this[option] = options[option]; } } FormData.LINE_BREAK = '\r\n'; FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; FormData.prototype.append = function(field, value, options) { options = options || {}; // allow filename as single option if (typeof options == 'string') { options = {filename: options}; } var append = CombinedStream.prototype.append.bind(this); // all that streamy business can't handle numbers if (typeof value == 'number') { value = '' + value; } // path_to_url if (util.isArray(value)) { // Please convert your array into string // the way web server expects it this._error(new Error('Arrays are not supported.')); return; } var header = this._multiPartHeader(field, value, options); var footer = this._multiPartFooter(); append(header); append(value); append(footer); // pass along options.knownLength this._trackLength(header, value, options); }; FormData.prototype._trackLength = function(header, value, options) { var valueLength = 0; // used w/ getLengthSync(), when length is known. // e.g. for streaming directly from a remote server, // w/ a known file a size, and not wanting to wait for // incoming file to finish to get its size. if (options.knownLength != null) { valueLength += +options.knownLength; } else if (Buffer.isBuffer(value)) { valueLength = value.length; } else if (typeof value === 'string') { valueLength = Buffer.byteLength(value); } this._valueLength += valueLength; // @check why add CRLF? does this account for custom/multiple CRLFs? this._overheadLength += Buffer.byteLength(header) + FormData.LINE_BREAK.length; // empty or either doesn't have path or not an http response if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) )) { return; } // no need to bother with the length if (!options.knownLength) { this._valuesToMeasure.push(value); } }; FormData.prototype._lengthRetriever = function(value, callback) { if (value.hasOwnProperty('fd')) { // take read range into a account // `end` = Infinity > read file till the end // // TODO: Looks like there is bug in Node fs.createReadStream // it doesn't respect `end` options without `start` options // Fix it when node fixes it. // path_to_url if (value.end != undefined && value.end != Infinity && value.start != undefined) { // when end specified // no need to calculate range // inclusive, starts with 0 callback(null, value.end + 1 - (value.start ? value.start : 0)); // not that fast snoopy } else { // still need to fetch file size from fs fs.stat(value.path, function(err, stat) { var fileSize; if (err) { callback(err); return; } // update final size based on the range options fileSize = stat.size - (value.start ? value.start : 0); callback(null, fileSize); }); } // or http response } else if (value.hasOwnProperty('httpVersion')) { callback(null, +value.headers['content-length']); // or request stream path_to_url } else if (value.hasOwnProperty('httpModule')) { // wait till response come back value.on('response', function(response) { value.pause(); callback(null, +response.headers['content-length']); }); value.resume(); // something else } else { callback('Unknown stream'); } }; FormData.prototype._multiPartHeader = function(field, value, options) { // custom header specified (as string)? // it becomes responsible for boundary // (e.g. to handle extra CRLFs on .NET servers) if (typeof options.header == 'string') { return options.header; } var contentDisposition = this._getContentDisposition(value, options); var contentType = this._getContentType(value, options); var contents = ''; var headers = { // add custom disposition as third element or keep it two elements if not 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), // if no content type. allow it to be empty array 'Content-Type': [].concat(contentType || []) }; // allow custom headers. if (typeof options.header == 'object') { populate(headers, options.header); } var header; for (var prop in headers) { if (!headers.hasOwnProperty(prop)) continue; header = headers[prop]; // skip nullish headers. if (header == null) { continue; } // convert all headers to arrays. if (!Array.isArray(header)) { header = [header]; } // add non-empty headers. if (header.length) { contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; } } return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; }; FormData.prototype._getContentDisposition = function(value, options) { var filename , contentDisposition ; if (typeof options.filepath === 'string') { // custom filepath for relative paths filename = path.normalize(options.filepath).replace(/\\/g, '/'); } else if (options.filename || value.name || value.path) { // custom filename take precedence // formidable and the browser add a name property // fs- and request- streams have path property filename = path.basename(options.filename || value.name || value.path); } else if (value.readable && value.hasOwnProperty('httpVersion')) { // or try http response filename = path.basename(value.client._httpMessage.path || ''); } if (filename) { contentDisposition = 'filename="' + filename + '"'; } return contentDisposition; }; FormData.prototype._getContentType = function(value, options) { // use custom content-type above all var contentType = options.contentType; // or try `name` from formidable, browser if (!contentType && value.name) { contentType = mime.lookup(value.name); } // or try `path` from fs-, request- streams if (!contentType && value.path) { contentType = mime.lookup(value.path); } // or if it's http-reponse if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { contentType = value.headers['content-type']; } // or guess it from the filepath or filename if (!contentType && (options.filepath || options.filename)) { contentType = mime.lookup(options.filepath || options.filename); } // fallback to the default content type if `value` is not simple value if (!contentType && typeof value == 'object') { contentType = FormData.DEFAULT_CONTENT_TYPE; } return contentType; }; FormData.prototype._multiPartFooter = function() { return function(next) { var footer = FormData.LINE_BREAK; var lastPart = (this._streams.length === 0); if (lastPart) { footer += this._lastBoundary(); } next(footer); }.bind(this); }; FormData.prototype._lastBoundary = function() { return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; }; FormData.prototype.getHeaders = function(userHeaders) { var header; var formHeaders = { 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() }; for (header in userHeaders) { if (userHeaders.hasOwnProperty(header)) { formHeaders[header.toLowerCase()] = userHeaders[header]; } } return formHeaders; }; FormData.prototype.setBoundary = function(boundary) { this._boundary = boundary; }; FormData.prototype.getBoundary = function() { if (!this._boundary) { this._generateBoundary(); } return this._boundary; }; FormData.prototype.getBuffer = function() { var dataBuffer = new Buffer.alloc( 0 ); var boundary = this.getBoundary(); // Create the form content. Add Line breaks to the end of data. for (var i = 0, len = this._streams.length; i < len; i++) { if (typeof this._streams[i] !== 'function') { // Add content to the buffer. if(Buffer.isBuffer(this._streams[i])) { dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); }else { dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); } // Add break after content. if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); } } } // Add the footer and return the Buffer object. return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); }; FormData.prototype._generateBoundary = function() { // This generates a 50 character boundary similar to those used by Firefox. // They are optimized for boyer-moore parsing. var boundary = '--------------------------'; for (var i = 0; i < 24; i++) { boundary += Math.floor(Math.random() * 10).toString(16); } this._boundary = boundary; }; // Note: getLengthSync DOESN'T calculate streams length // As workaround one can calculate file size manually // and add it as knownLength option FormData.prototype.getLengthSync = function() { var knownLength = this._overheadLength + this._valueLength; // Don't get confused, there are 3 "internal" streams for each keyval pair // so it basically checks if there is any value added to the form if (this._streams.length) { knownLength += this._lastBoundary().length; } // path_to_url if (!this.hasKnownLength()) { // Some async length retrievers are present // therefore synchronous length calculation is false. // Please use getLength(callback) to get proper length this._error(new Error('Cannot calculate proper length in synchronous way.')); } return knownLength; }; // Public API to check if length of added values is known // path_to_url // path_to_url FormData.prototype.hasKnownLength = function() { var hasKnownLength = true; if (this._valuesToMeasure.length) { hasKnownLength = false; } return hasKnownLength; }; FormData.prototype.getLength = function(cb) { var knownLength = this._overheadLength + this._valueLength; if (this._streams.length) { knownLength += this._lastBoundary().length; } if (!this._valuesToMeasure.length) { process.nextTick(cb.bind(this, null, knownLength)); return; } asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { if (err) { cb(err); return; } values.forEach(function(length) { knownLength += length; }); cb(null, knownLength); }); }; FormData.prototype.submit = function(params, cb) { var request , options , defaults = {method: 'post'} ; // parse provided url if it's string // or treat it as options object if (typeof params == 'string') { params = parseUrl(params); options = populate({ port: params.port, path: params.pathname, host: params.hostname, protocol: params.protocol }, defaults); // use custom params } else { options = populate(params, defaults); // if no port provided use default one if (!options.port) { options.port = options.protocol == 'https:' ? 443 : 80; } } // put that good code in getHeaders to some use options.headers = this.getHeaders(params.headers); // https if specified, fallback to http in any other case if (options.protocol == 'https:') { request = https.request(options); } else { request = http.request(options); } // get content length and fire away this.getLength(function(err, length) { if (err) { this._error(err); return; } // add content length request.setHeader('Content-Length', length); this.pipe(request); if (cb) { var onResponse; var callback = function (error, responce) { request.removeListener('error', callback); request.removeListener('response', onResponse); return cb.call(this, error, responce); }; onResponse = callback.bind(this, null); request.on('error', callback); request.on('response', onResponse); } }.bind(this)); return request; }; FormData.prototype._error = function(err) { if (!this.error) { this.error = err; this.pause(); this.emit('error', err); } }; FormData.prototype.toString = function () { return '[object FormData]'; }; ```
/content/code_sandbox/node_modules/superagent/node_modules/form-data/lib/form_data.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
3,146
```javascript 'use strict'; var utils = require('./utils'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, allowSparse: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; // This is what browsers will submit when the character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = utils.maybeMap( parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else if (cleanRoot !== '__proto__') { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } if (options.allowSparse === true) { return obj; } return utils.compact(obj); }; ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/lib/parse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,215
```javascript 'use strict'; var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset, kind, format) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); /* eslint operator-linebreak: [2, "before"] */ out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, merge: merge }; ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/lib/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,823
```javascript 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } }, RFC1738: Format.RFC1738, RFC3986: Format.RFC3986 }; ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/lib/formats.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
131
```javascript 'use strict'; var getSideChannel = require('side-channel'); var utils = require('./utils'); var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var split = String.prototype.split; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var sentinel = {}; var stringify = function stringify( object, prefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel ) { var obj = object; var tmpSc = sideChannel; var step = 0; var findFlag = false; while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { // Where object last appeared in the ref tree var pos = tmpSc.get(object); step += 1; if (typeof pos !== 'undefined') { if (pos === step) { throw new RangeError('Cyclic object value'); } else { findFlag = true; // Break while } } if (typeof tmpSc.get(sentinel) === 'undefined') { step = 0; } } if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); if (generateArrayPrefix === 'comma' && encodeValuesOnly) { var valuesArray = split.call(String(obj), ','); var valuesJoined = ''; for (var i = 0; i < valuesArray.length; ++i) { valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); } return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; } return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (generateArrayPrefix === 'comma' && isArray(obj)) { // we need to join elements in objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } else if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; if (skipNulls && value === null) { continue; } var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); valueSideChannel.set(sentinel, sideChannel); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel )); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, format: format, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); } var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } var sideChannel = getSideChannel(); for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, commaRoundTrip, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/lib/stringify.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
2,341
```javascript 'use strict'; var test = require('tape'); var qs = require('../'); var utils = require('../lib/utils'); var iconv = require('iconv-lite'); var SaferBuffer = require('safer-buffer').Buffer; test('parse()', function (t) { t.test('parses a simple string', function (st) { st.deepEqual(qs.parse('0=foo'), { 0: 'foo' }); st.deepEqual(qs.parse('foo=c++'), { foo: 'c ' }); st.deepEqual(qs.parse('a[>=]=23'), { a: { '>=': '23' } }); st.deepEqual(qs.parse('a[<=>]==23'), { a: { '<=>': '=23' } }); st.deepEqual(qs.parse('a[==]=23'), { a: { '==': '23' } }); st.deepEqual(qs.parse('foo', { strictNullHandling: true }), { foo: null }); st.deepEqual(qs.parse('foo'), { foo: '' }); st.deepEqual(qs.parse('foo='), { foo: '' }); st.deepEqual(qs.parse('foo=bar'), { foo: 'bar' }); st.deepEqual(qs.parse(' foo = bar = baz '), { ' foo ': ' bar = baz ' }); st.deepEqual(qs.parse('foo=bar=baz'), { foo: 'bar=baz' }); st.deepEqual(qs.parse('foo=bar&bar=baz'), { foo: 'bar', bar: 'baz' }); st.deepEqual(qs.parse('foo2=bar2&baz2='), { foo2: 'bar2', baz2: '' }); st.deepEqual(qs.parse('foo=bar&baz', { strictNullHandling: true }), { foo: 'bar', baz: null }); st.deepEqual(qs.parse('foo=bar&baz'), { foo: 'bar', baz: '' }); st.deepEqual(qs.parse('cht=p3&chd=t:60,40&chs=250x100&chl=Hello|World'), { cht: 'p3', chd: 't:60,40', chs: '250x100', chl: 'Hello|World' }); st.end(); }); t.test('arrayFormat: brackets allows only explicit arrays', function (st) { st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'brackets' }), { a: 'b,c' }); st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'brackets' }), { a: ['b', 'c'] }); st.end(); }); t.test('arrayFormat: indices allows only indexed arrays', function (st) { st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'indices' }), { a: 'b,c' }); st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'indices' }), { a: ['b', 'c'] }); st.end(); }); t.test('arrayFormat: comma allows only comma-separated arrays', function (st) { st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'comma' }), { a: 'b,c' }); st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'comma' }), { a: ['b', 'c'] }); st.end(); }); t.test('arrayFormat: repeat allows only repeated values', function (st) { st.deepEqual(qs.parse('a[]=b&a[]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b,c', { arrayFormat: 'repeat' }), { a: 'b,c' }); st.deepEqual(qs.parse('a=b&a=c', { arrayFormat: 'repeat' }), { a: ['b', 'c'] }); st.end(); }); t.test('allows enabling dot notation', function (st) { st.deepEqual(qs.parse('a.b=c'), { 'a.b': 'c' }); st.deepEqual(qs.parse('a.b=c', { allowDots: true }), { a: { b: 'c' } }); st.end(); }); t.deepEqual(qs.parse('a[b]=c'), { a: { b: 'c' } }, 'parses a single nested string'); t.deepEqual(qs.parse('a[b][c]=d'), { a: { b: { c: 'd' } } }, 'parses a double nested string'); t.deepEqual( qs.parse('a[b][c][d][e][f][g][h]=i'), { a: { b: { c: { d: { e: { f: { '[g][h]': 'i' } } } } } } }, 'defaults to a depth of 5' ); t.test('only parses one level when depth = 1', function (st) { st.deepEqual(qs.parse('a[b][c]=d', { depth: 1 }), { a: { b: { '[c]': 'd' } } }); st.deepEqual(qs.parse('a[b][c][d]=e', { depth: 1 }), { a: { b: { '[c][d]': 'e' } } }); st.end(); }); t.test('uses original key when depth = 0', function (st) { st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: 0 }), { 'a[0]': 'b', 'a[1]': 'c' }); st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: 0 }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); st.end(); }); t.test('uses original key when depth = false', function (st) { st.deepEqual(qs.parse('a[0]=b&a[1]=c', { depth: false }), { 'a[0]': 'b', 'a[1]': 'c' }); st.deepEqual(qs.parse('a[0][0]=b&a[0][1]=c&a[1]=d&e=2', { depth: false }), { 'a[0][0]': 'b', 'a[0][1]': 'c', 'a[1]': 'd', e: '2' }); st.end(); }); t.deepEqual(qs.parse('a=b&a=c'), { a: ['b', 'c'] }, 'parses a simple array'); t.test('parses an explicit array', function (st) { st.deepEqual(qs.parse('a[]=b'), { a: ['b'] }); st.deepEqual(qs.parse('a[]=b&a[]=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[]=b&a[]=c&a[]=d'), { a: ['b', 'c', 'd'] }); st.end(); }); t.test('parses a mix of simple and explicit arrays', function (st) { st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[0]=b&a=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b&a[0]=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[1]=b&a=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[]=b&a=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[]=b&a=c'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b&a[1]=c', { arrayLimit: 20 }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b&a[]=c', { arrayLimit: 0 }), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a=b&a[]=c'), { a: ['b', 'c'] }); st.end(); }); t.test('parses a nested array', function (st) { st.deepEqual(qs.parse('a[b][]=c&a[b][]=d'), { a: { b: ['c', 'd'] } }); st.deepEqual(qs.parse('a[>=]=25'), { a: { '>=': '25' } }); st.end(); }); t.test('allows to specify array indices', function (st) { st.deepEqual(qs.parse('a[1]=c&a[0]=b&a[2]=d'), { a: ['b', 'c', 'd'] }); st.deepEqual(qs.parse('a[1]=c&a[0]=b'), { a: ['b', 'c'] }); st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 20 }), { a: ['c'] }); st.deepEqual(qs.parse('a[1]=c', { arrayLimit: 0 }), { a: { 1: 'c' } }); st.deepEqual(qs.parse('a[1]=c'), { a: ['c'] }); st.end(); }); t.test('limits specific array indices to arrayLimit', function (st) { st.deepEqual(qs.parse('a[20]=a', { arrayLimit: 20 }), { a: ['a'] }); st.deepEqual(qs.parse('a[21]=a', { arrayLimit: 20 }), { a: { 21: 'a' } }); st.deepEqual(qs.parse('a[20]=a'), { a: ['a'] }); st.deepEqual(qs.parse('a[21]=a'), { a: { 21: 'a' } }); st.end(); }); t.deepEqual(qs.parse('a[12b]=c'), { a: { '12b': 'c' } }, 'supports keys that begin with a number'); t.test('supports encoded = signs', function (st) { st.deepEqual(qs.parse('he%3Dllo=th%3Dere'), { 'he=llo': 'th=ere' }); st.end(); }); t.test('is ok with url encoded strings', function (st) { st.deepEqual(qs.parse('a[b%20c]=d'), { a: { 'b c': 'd' } }); st.deepEqual(qs.parse('a[b]=c%20d'), { a: { b: 'c d' } }); st.end(); }); t.test('allows brackets in the value', function (st) { st.deepEqual(qs.parse('pets=["tobi"]'), { pets: '["tobi"]' }); st.deepEqual(qs.parse('operators=[">=", "<="]'), { operators: '[">=", "<="]' }); st.end(); }); t.test('allows empty values', function (st) { st.deepEqual(qs.parse(''), {}); st.deepEqual(qs.parse(null), {}); st.deepEqual(qs.parse(undefined), {}); st.end(); }); t.test('transforms arrays to objects', function (st) { st.deepEqual(qs.parse('foo[0]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); st.deepEqual(qs.parse('foo[bad]=baz&foo[0]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar'), { foo: { bad: 'baz', 0: 'bar' } }); st.deepEqual(qs.parse('foo[]=bar&foo[bad]=baz'), { foo: { 0: 'bar', bad: 'baz' } }); st.deepEqual(qs.parse('foo[bad]=baz&foo[]=bar&foo[]=foo'), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); st.deepEqual(qs.parse('foo[0][a]=a&foo[0][b]=b&foo[1][a]=aa&foo[1][b]=bb'), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: false }), { a: { 0: 'b', t: 'u' } }); st.deepEqual(qs.parse('a[]=b&a[t]=u&a[hasOwnProperty]=c', { allowPrototypes: true }), { a: { 0: 'b', t: 'u', hasOwnProperty: 'c' } }); st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: false }), { a: { 0: 'b', x: 'y' } }); st.deepEqual(qs.parse('a[]=b&a[hasOwnProperty]=c&a[x]=y', { allowPrototypes: true }), { a: { 0: 'b', hasOwnProperty: 'c', x: 'y' } }); st.end(); }); t.test('transforms arrays to objects (dot notation)', function (st) { st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: 'baz' } }); st.deepEqual(qs.parse('foo[0].baz=bar&fool.bad.boo=baz', { allowDots: true }), { foo: [{ baz: 'bar' }], fool: { bad: { boo: 'baz' } } }); st.deepEqual(qs.parse('foo[0][0].baz=bar&fool.bad=baz', { allowDots: true }), { foo: [[{ baz: 'bar' }]], fool: { bad: 'baz' } }); st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15'], bar: '2' }] }); st.deepEqual(qs.parse('foo[0].baz[0]=15&foo[0].baz[1]=16&foo[0].bar=2', { allowDots: true }), { foo: [{ baz: ['15', '16'], bar: '2' }] }); st.deepEqual(qs.parse('foo.bad=baz&foo[0]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar' } }); st.deepEqual(qs.parse('foo[]=bar&foo.bad=baz', { allowDots: true }), { foo: { 0: 'bar', bad: 'baz' } }); st.deepEqual(qs.parse('foo.bad=baz&foo[]=bar&foo[]=foo', { allowDots: true }), { foo: { bad: 'baz', 0: 'bar', 1: 'foo' } }); st.deepEqual(qs.parse('foo[0].a=a&foo[0].b=b&foo[1].a=aa&foo[1].b=bb', { allowDots: true }), { foo: [{ a: 'a', b: 'b' }, { a: 'aa', b: 'bb' }] }); st.end(); }); t.test('correctly prunes undefined values when converting an array to an object', function (st) { st.deepEqual(qs.parse('a[2]=b&a[99999999]=c'), { a: { 2: 'b', 99999999: 'c' } }); st.end(); }); t.test('supports malformed uri characters', function (st) { st.deepEqual(qs.parse('{%:%}', { strictNullHandling: true }), { '{%:%}': null }); st.deepEqual(qs.parse('{%:%}='), { '{%:%}': '' }); st.deepEqual(qs.parse('foo=%:%}'), { foo: '%:%}' }); st.end(); }); t.test('doesn\'t produce empty keys', function (st) { st.deepEqual(qs.parse('_r=1&'), { _r: '1' }); st.end(); }); t.test('cannot access Object prototype', function (st) { qs.parse('constructor[prototype][bad]=bad'); qs.parse('bad[constructor][prototype][bad]=bad'); st.equal(typeof Object.prototype.bad, 'undefined'); st.end(); }); t.test('parses arrays of objects', function (st) { st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); st.deepEqual(qs.parse('a[0][b]=c'), { a: [{ b: 'c' }] }); st.end(); }); t.test('allows for empty strings in arrays', function (st) { st.deepEqual(qs.parse('a[]=b&a[]=&a[]=c'), { a: ['b', '', 'c'] }); st.deepEqual( qs.parse('a[0]=b&a[1]&a[2]=c&a[19]=', { strictNullHandling: true, arrayLimit: 20 }), { a: ['b', null, 'c', ''] }, 'with arrayLimit 20 + array indices: null then empty string works' ); st.deepEqual( qs.parse('a[]=b&a[]&a[]=c&a[]=', { strictNullHandling: true, arrayLimit: 0 }), { a: ['b', null, 'c', ''] }, 'with arrayLimit 0 + array brackets: null then empty string works' ); st.deepEqual( qs.parse('a[0]=b&a[1]=&a[2]=c&a[19]', { strictNullHandling: true, arrayLimit: 20 }), { a: ['b', '', 'c', null] }, 'with arrayLimit 20 + array indices: empty string then null works' ); st.deepEqual( qs.parse('a[]=b&a[]=&a[]=c&a[]', { strictNullHandling: true, arrayLimit: 0 }), { a: ['b', '', 'c', null] }, 'with arrayLimit 0 + array brackets: empty string then null works' ); st.deepEqual( qs.parse('a[]=&a[]=b&a[]=c'), { a: ['', 'b', 'c'] }, 'array brackets: empty strings work' ); st.end(); }); t.test('compacts sparse arrays', function (st) { st.deepEqual(qs.parse('a[10]=1&a[2]=2', { arrayLimit: 20 }), { a: ['2', '1'] }); st.deepEqual(qs.parse('a[1][b][2][c]=1', { arrayLimit: 20 }), { a: [{ b: [{ c: '1' }] }] }); st.deepEqual(qs.parse('a[1][2][3][c]=1', { arrayLimit: 20 }), { a: [[[{ c: '1' }]]] }); st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { arrayLimit: 20 }), { a: [[[{ c: ['1'] }]]] }); st.end(); }); t.test('parses sparse arrays', function (st) { /* eslint no-sparse-arrays: 0 */ st.deepEqual(qs.parse('a[4]=1&a[1]=2', { allowSparse: true }), { a: [, '2', , , '1'] }); st.deepEqual(qs.parse('a[1][b][2][c]=1', { allowSparse: true }), { a: [, { b: [, , { c: '1' }] }] }); st.deepEqual(qs.parse('a[1][2][3][c]=1', { allowSparse: true }), { a: [, [, , [, , , { c: '1' }]]] }); st.deepEqual(qs.parse('a[1][2][3][c][1]=1', { allowSparse: true }), { a: [, [, , [, , , { c: [, '1'] }]]] }); st.end(); }); t.test('parses semi-parsed strings', function (st) { st.deepEqual(qs.parse({ 'a[b]': 'c' }), { a: { b: 'c' } }); st.deepEqual(qs.parse({ 'a[b]': 'c', 'a[d]': 'e' }), { a: { b: 'c', d: 'e' } }); st.end(); }); t.test('parses buffers correctly', function (st) { var b = SaferBuffer.from('test'); st.deepEqual(qs.parse({ a: b }), { a: b }); st.end(); }); t.test('parses jquery-param strings', function (st) { // readable = 'filter[0][]=int1&filter[0][]==&filter[0][]=77&filter[]=and&filter[2][]=int2&filter[2][]==&filter[2][]=8' var encoded = 'filter%5B0%5D%5B%5D=int1&filter%5B0%5D%5B%5D=%3D&filter%5B0%5D%5B%5D=77&filter%5B%5D=and&filter%5B2%5D%5B%5D=int2&filter%5B2%5D%5B%5D=%3D&filter%5B2%5D%5B%5D=8'; var expected = { filter: [['int1', '=', '77'], 'and', ['int2', '=', '8']] }; st.deepEqual(qs.parse(encoded), expected); st.end(); }); t.test('continues parsing when no parent is found', function (st) { st.deepEqual(qs.parse('[]=&a=b'), { 0: '', a: 'b' }); st.deepEqual(qs.parse('[]&a=b', { strictNullHandling: true }), { 0: null, a: 'b' }); st.deepEqual(qs.parse('[foo]=bar'), { foo: 'bar' }); st.end(); }); t.test('does not error when parsing a very long array', function (st) { var str = 'a[]=a'; while (Buffer.byteLength(str) < 128 * 1024) { str = str + '&' + str; } st.doesNotThrow(function () { qs.parse(str); }); st.end(); }); t.test('should not throw when a native prototype has an enumerable property', function (st) { Object.prototype.crash = ''; Array.prototype.crash = ''; st.doesNotThrow(qs.parse.bind(null, 'a=b')); st.deepEqual(qs.parse('a=b'), { a: 'b' }); st.doesNotThrow(qs.parse.bind(null, 'a[][b]=c')); st.deepEqual(qs.parse('a[][b]=c'), { a: [{ b: 'c' }] }); delete Object.prototype.crash; delete Array.prototype.crash; st.end(); }); t.test('parses a string with an alternative string delimiter', function (st) { st.deepEqual(qs.parse('a=b;c=d', { delimiter: ';' }), { a: 'b', c: 'd' }); st.end(); }); t.test('parses a string with an alternative RegExp delimiter', function (st) { st.deepEqual(qs.parse('a=b; c=d', { delimiter: /[;,] */ }), { a: 'b', c: 'd' }); st.end(); }); t.test('does not use non-splittable objects as delimiters', function (st) { st.deepEqual(qs.parse('a=b&c=d', { delimiter: true }), { a: 'b', c: 'd' }); st.end(); }); t.test('allows overriding parameter limit', function (st) { st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: 1 }), { a: 'b' }); st.end(); }); t.test('allows setting the parameter limit to Infinity', function (st) { st.deepEqual(qs.parse('a=b&c=d', { parameterLimit: Infinity }), { a: 'b', c: 'd' }); st.end(); }); t.test('allows overriding array limit', function (st) { st.deepEqual(qs.parse('a[0]=b', { arrayLimit: -1 }), { a: { 0: 'b' } }); st.deepEqual(qs.parse('a[-1]=b', { arrayLimit: -1 }), { a: { '-1': 'b' } }); st.deepEqual(qs.parse('a[0]=b&a[1]=c', { arrayLimit: 0 }), { a: { 0: 'b', 1: 'c' } }); st.end(); }); t.test('allows disabling array parsing', function (st) { var indices = qs.parse('a[0]=b&a[1]=c', { parseArrays: false }); st.deepEqual(indices, { a: { 0: 'b', 1: 'c' } }); st.equal(Array.isArray(indices.a), false, 'parseArrays:false, indices case is not an array'); var emptyBrackets = qs.parse('a[]=b', { parseArrays: false }); st.deepEqual(emptyBrackets, { a: { 0: 'b' } }); st.equal(Array.isArray(emptyBrackets.a), false, 'parseArrays:false, empty brackets case is not an array'); st.end(); }); t.test('allows for query string prefix', function (st) { st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); st.deepEqual(qs.parse('foo=bar', { ignoreQueryPrefix: true }), { foo: 'bar' }); st.deepEqual(qs.parse('?foo=bar', { ignoreQueryPrefix: false }), { '?foo': 'bar' }); st.end(); }); t.test('parses an object', function (st) { var input = { 'user[name]': { 'pop[bob]': 3 }, 'user[email]': null }; var expected = { user: { name: { 'pop[bob]': 3 }, email: null } }; var result = qs.parse(input); st.deepEqual(result, expected); st.end(); }); t.test('parses string with comma as array divider', function (st) { st.deepEqual(qs.parse('foo=bar,tee', { comma: true }), { foo: ['bar', 'tee'] }); st.deepEqual(qs.parse('foo[bar]=coffee,tee', { comma: true }), { foo: { bar: ['coffee', 'tee'] } }); st.deepEqual(qs.parse('foo=', { comma: true }), { foo: '' }); st.deepEqual(qs.parse('foo', { comma: true }), { foo: '' }); st.deepEqual(qs.parse('foo', { comma: true, strictNullHandling: true }), { foo: null }); // test cases inversed from from stringify tests st.deepEqual(qs.parse('a[0]=c'), { a: ['c'] }); st.deepEqual(qs.parse('a[]=c'), { a: ['c'] }); st.deepEqual(qs.parse('a[]=c', { comma: true }), { a: ['c'] }); st.deepEqual(qs.parse('a[0]=c&a[1]=d'), { a: ['c', 'd'] }); st.deepEqual(qs.parse('a[]=c&a[]=d'), { a: ['c', 'd'] }); st.deepEqual(qs.parse('a=c,d', { comma: true }), { a: ['c', 'd'] }); st.end(); }); t.test('parses values with comma as array divider', function (st) { st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: false }), { foo: 'bar,tee' }); st.deepEqual(qs.parse({ foo: 'bar,tee' }, { comma: true }), { foo: ['bar', 'tee'] }); st.end(); }); t.test('use number decoder, parses string that has one number with comma option enabled', function (st) { var decoder = function (str, defaultDecoder, charset, type) { if (!isNaN(Number(str))) { return parseFloat(str); } return defaultDecoder(str, defaultDecoder, charset, type); }; st.deepEqual(qs.parse('foo=1', { comma: true, decoder: decoder }), { foo: 1 }); st.deepEqual(qs.parse('foo=0', { comma: true, decoder: decoder }), { foo: 0 }); st.end(); }); t.test('parses brackets holds array of arrays when having two parts of strings with comma as array divider', function (st) { st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=4,5,6', { comma: true }), { foo: [['1', '2', '3'], ['4', '5', '6']] }); st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=', { comma: true }), { foo: [['1', '2', '3'], ''] }); st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=,', { comma: true }), { foo: [['1', '2', '3'], ['', '']] }); st.deepEqual(qs.parse('foo[]=1,2,3&foo[]=a', { comma: true }), { foo: [['1', '2', '3'], 'a'] }); st.end(); }); t.test('parses comma delimited array while having percent-encoded comma treated as normal text', function (st) { st.deepEqual(qs.parse('foo=a%2Cb', { comma: true }), { foo: 'a,b' }); st.deepEqual(qs.parse('foo=a%2C%20b,d', { comma: true }), { foo: ['a, b', 'd'] }); st.deepEqual(qs.parse('foo=a%2C%20b,c%2C%20d', { comma: true }), { foo: ['a, b', 'c, d'] }); st.end(); }); t.test('parses an object in dot notation', function (st) { var input = { 'user.name': { 'pop[bob]': 3 }, 'user.email.': null }; var expected = { user: { name: { 'pop[bob]': 3 }, email: null } }; var result = qs.parse(input, { allowDots: true }); st.deepEqual(result, expected); st.end(); }); t.test('parses an object and not child values', function (st) { var input = { 'user[name]': { 'pop[bob]': { test: 3 } }, 'user[email]': null }; var expected = { user: { name: { 'pop[bob]': { test: 3 } }, email: null } }; var result = qs.parse(input); st.deepEqual(result, expected); st.end(); }); t.test('does not blow up when Buffer global is missing', function (st) { var tempBuffer = global.Buffer; delete global.Buffer; var result = qs.parse('a=b&c=d'); global.Buffer = tempBuffer; st.deepEqual(result, { a: 'b', c: 'd' }); st.end(); }); t.test('does not crash when parsing circular references', function (st) { var a = {}; a.b = a; var parsed; st.doesNotThrow(function () { parsed = qs.parse({ 'foo[bar]': 'baz', 'foo[baz]': a }); }); st.equal('foo' in parsed, true, 'parsed has "foo" property'); st.equal('bar' in parsed.foo, true); st.equal('baz' in parsed.foo, true); st.equal(parsed.foo.bar, 'baz'); st.deepEqual(parsed.foo.baz, a); st.end(); }); t.test('does not crash when parsing deep objects', function (st) { var parsed; var str = 'foo'; for (var i = 0; i < 5000; i++) { str += '[p]'; } str += '=bar'; st.doesNotThrow(function () { parsed = qs.parse(str, { depth: 5000 }); }); st.equal('foo' in parsed, true, 'parsed has "foo" property'); var depth = 0; var ref = parsed.foo; while ((ref = ref.p)) { depth += 1; } st.equal(depth, 5000, 'parsed is 5000 properties deep'); st.end(); }); t.test('parses null objects correctly', { skip: !Object.create }, function (st) { var a = Object.create(null); a.b = 'c'; st.deepEqual(qs.parse(a), { b: 'c' }); var result = qs.parse({ a: a }); st.equal('a' in result, true, 'result has "a" property'); st.deepEqual(result.a, a); st.end(); }); t.test('parses dates correctly', function (st) { var now = new Date(); st.deepEqual(qs.parse({ a: now }), { a: now }); st.end(); }); t.test('parses regular expressions correctly', function (st) { var re = /^test$/; st.deepEqual(qs.parse({ a: re }), { a: re }); st.end(); }); t.test('does not allow overwriting prototype properties', function (st) { st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: false }), {}); st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: false }), {}); st.deepEqual( qs.parse('toString', { allowPrototypes: false }), {}, 'bare "toString" results in {}' ); st.end(); }); t.test('can allow overwriting prototype properties', function (st) { st.deepEqual(qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }), { a: { hasOwnProperty: 'b' } }); st.deepEqual(qs.parse('hasOwnProperty=b', { allowPrototypes: true }), { hasOwnProperty: 'b' }); st.deepEqual( qs.parse('toString', { allowPrototypes: true }), { toString: '' }, 'bare "toString" results in { toString: "" }' ); st.end(); }); t.test('params starting with a closing bracket', function (st) { st.deepEqual(qs.parse(']=toString'), { ']': 'toString' }); st.deepEqual(qs.parse(']]=toString'), { ']]': 'toString' }); st.deepEqual(qs.parse(']hello]=toString'), { ']hello]': 'toString' }); st.end(); }); t.test('params starting with a starting bracket', function (st) { st.deepEqual(qs.parse('[=toString'), { '[': 'toString' }); st.deepEqual(qs.parse('[[=toString'), { '[[': 'toString' }); st.deepEqual(qs.parse('[hello[=toString'), { '[hello[': 'toString' }); st.end(); }); t.test('add keys to objects', function (st) { st.deepEqual( qs.parse('a[b]=c&a=d'), { a: { b: 'c', d: true } }, 'can add keys to objects' ); st.deepEqual( qs.parse('a[b]=c&a=toString'), { a: { b: 'c' } }, 'can not overwrite prototype' ); st.deepEqual( qs.parse('a[b]=c&a=toString', { allowPrototypes: true }), { a: { b: 'c', toString: true } }, 'can overwrite prototype with allowPrototypes true' ); st.deepEqual( qs.parse('a[b]=c&a=toString', { plainObjects: true }), { __proto__: null, a: { __proto__: null, b: 'c', toString: true } }, 'can overwrite prototype with plainObjects true' ); st.end(); }); t.test('dunder proto is ignored', function (st) { var payload = 'categories[__proto__]=login&categories[__proto__]&categories[length]=42'; var result = qs.parse(payload, { allowPrototypes: true }); st.deepEqual( result, { categories: { length: '42' } }, 'silent [[Prototype]] payload' ); var plainResult = qs.parse(payload, { allowPrototypes: true, plainObjects: true }); st.deepEqual( plainResult, { __proto__: null, categories: { __proto__: null, length: '42' } }, 'silent [[Prototype]] payload: plain objects' ); var query = qs.parse('categories[__proto__]=cats&categories[__proto__]=dogs&categories[some][json]=toInject', { allowPrototypes: true }); st.notOk(Array.isArray(query.categories), 'is not an array'); st.notOk(query.categories instanceof Array, 'is not instanceof an array'); st.deepEqual(query.categories, { some: { json: 'toInject' } }); st.equal(JSON.stringify(query.categories), '{"some":{"json":"toInject"}}', 'stringifies as a non-array'); st.deepEqual( qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true }), { foo: { bar: 'stuffs' } }, 'hidden values' ); st.deepEqual( qs.parse('foo[__proto__][hidden]=value&foo[bar]=stuffs', { allowPrototypes: true, plainObjects: true }), { __proto__: null, foo: { __proto__: null, bar: 'stuffs' } }, 'hidden values: plain objects' ); st.end(); }); t.test('can return null objects', { skip: !Object.create }, function (st) { var expected = Object.create(null); expected.a = Object.create(null); expected.a.b = 'c'; expected.a.hasOwnProperty = 'd'; st.deepEqual(qs.parse('a[b]=c&a[hasOwnProperty]=d', { plainObjects: true }), expected); st.deepEqual(qs.parse(null, { plainObjects: true }), Object.create(null)); var expectedArray = Object.create(null); expectedArray.a = Object.create(null); expectedArray.a[0] = 'b'; expectedArray.a.c = 'd'; st.deepEqual(qs.parse('a[]=b&a[c]=d', { plainObjects: true }), expectedArray); st.end(); }); t.test('can parse with custom encoding', function (st) { st.deepEqual(qs.parse('%8c%a7=%91%e5%8d%e3%95%7b', { decoder: function (str) { var reg = /%([0-9A-F]{2})/ig; var result = []; var parts = reg.exec(str); while (parts) { result.push(parseInt(parts[1], 16)); parts = reg.exec(str); } return String(iconv.decode(SaferBuffer.from(result), 'shift_jis')); } }), { : '' }); st.end(); }); t.test('receives the default decoder as a second argument', function (st) { st.plan(1); qs.parse('a', { decoder: function (str, defaultDecoder) { st.equal(defaultDecoder, utils.decode); } }); st.end(); }); t.test('throws error with wrong decoder', function (st) { st['throws'](function () { qs.parse({}, { decoder: 'string' }); }, new TypeError('Decoder has to be a function.')); st.end(); }); t.test('does not mutate the options argument', function (st) { var options = {}; qs.parse('a[b]=true', options); st.deepEqual(options, {}); st.end(); }); t.test('throws if an invalid charset is specified', function (st) { st['throws'](function () { qs.parse('a=b', { charset: 'foobar' }); }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); st.end(); }); t.test('parses an iso-8859-1 string if asked to', function (st) { st.deepEqual(qs.parse('%A2=%BD', { charset: 'iso-8859-1' }), { '': '' }); st.end(); }); var urlEncodedCheckmarkInUtf8 = '%E2%9C%93'; var urlEncodedOSlashInUtf8 = '%C3%B8'; var urlEncodedNumCheckmark = '%26%2310003%3B'; var urlEncodedNumSmiley = '%26%239786%3B'; t.test('prefers an utf-8 charset specified by the utf8 sentinel to a default charset of iso-8859-1', function (st) { st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'iso-8859-1' }), { : '' }); st.end(); }); t.test('prefers an iso-8859-1 charset specified by the utf8 sentinel to a default charset of utf-8', function (st) { st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { '': '' }); st.end(); }); t.test('does not require the utf8 sentinel to be defined before the parameters whose decoding it affects', function (st) { st.deepEqual(qs.parse('a=' + urlEncodedOSlashInUtf8 + '&utf8=' + urlEncodedNumCheckmark, { charsetSentinel: true, charset: 'utf-8' }), { a: '' }); st.end(); }); t.test('should ignore an utf8 sentinel with an unknown value', function (st) { st.deepEqual(qs.parse('utf8=foo&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true, charset: 'utf-8' }), { : '' }); st.end(); }); t.test('uses the utf8 sentinel to switch to utf-8 when no default charset is given', function (st) { st.deepEqual(qs.parse('utf8=' + urlEncodedCheckmarkInUtf8 + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { : '' }); st.end(); }); t.test('uses the utf8 sentinel to switch to iso-8859-1 when no default charset is given', function (st) { st.deepEqual(qs.parse('utf8=' + urlEncodedNumCheckmark + '&' + urlEncodedOSlashInUtf8 + '=' + urlEncodedOSlashInUtf8, { charsetSentinel: true }), { '': '' }); st.end(); }); t.test('interprets numeric entities in iso-8859-1 when `interpretNumericEntities`', function (st) { st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', interpretNumericEntities: true }), { foo: '' }); st.end(); }); t.test('handles a custom decoder returning `null`, in the `iso-8859-1` charset, when `interpretNumericEntities`', function (st) { st.deepEqual(qs.parse('foo=&bar=' + urlEncodedNumSmiley, { charset: 'iso-8859-1', decoder: function (str, defaultDecoder, charset) { return str ? defaultDecoder(str, defaultDecoder, charset) : null; }, interpretNumericEntities: true }), { foo: null, bar: '' }); st.end(); }); t.test('does not interpret numeric entities in iso-8859-1 when `interpretNumericEntities` is absent', function (st) { st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'iso-8859-1' }), { foo: '&#9786;' }); st.end(); }); t.test('does not interpret numeric entities when the charset is utf-8, even when `interpretNumericEntities`', function (st) { st.deepEqual(qs.parse('foo=' + urlEncodedNumSmiley, { charset: 'utf-8', interpretNumericEntities: true }), { foo: '&#9786;' }); st.end(); }); t.test('does not interpret %uXXXX syntax in iso-8859-1 mode', function (st) { st.deepEqual(qs.parse('%u263A=%u263A', { charset: 'iso-8859-1' }), { '%u263A': '%u263A' }); st.end(); }); t.test('allows for decoding keys and values differently', function (st) { var decoder = function (str, defaultDecoder, charset, type) { if (type === 'key') { return defaultDecoder(str, defaultDecoder, charset, type).toLowerCase(); } if (type === 'value') { return defaultDecoder(str, defaultDecoder, charset, type).toUpperCase(); } throw 'this should never happen! type: ' + type; }; st.deepEqual(qs.parse('KeY=vAlUe', { decoder: decoder }), { key: 'VALUE' }); st.end(); }); t.end(); }); ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/test/parse.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,551
```html <!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>SuperAgent elegant API for AJAX in Node and browsers</title> <link rel="stylesheet" href="path_to_url"> <link rel="stylesheet" href="docs/style.css"> </head> <body> <ul id="menu"></ul> <div id="content"> <section class="suite"> <h1>Agent</h1> <dl> <dt>should remember defaults</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } let called = 0; let event_called = 0; const agent = request .agent() .accept(&#x27;json&#x27;) .use(() =&#x3E; { called++; }) .once(&#x27;request&#x27;, () =&#x3E; { event_called++; }) .query({ hello: &#x27;world&#x27; }) .set(&#x27;X-test&#x27;, &#x27;testing&#x27;); assert.equal(0, called); assert.equal(0, event_called); return agent .get(&#x60;${base}/echo&#x60;) .then((res) =&#x3E; { assert.equal(1, called); assert.equal(1, event_called); assert.equal(&#x27;application/json&#x27;, res.headers.accept); assert.equal(&#x27;testing&#x27;, res.headers[&#x27;x-test&#x27;]); return agent.get(&#x60;${base}/querystring&#x60;); }) .then((res) =&#x3E; { assert.equal(2, called); assert.equal(2, event_called); assert.deepEqual({ hello: &#x27;world&#x27; }, res.body); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>res.statusCode</h1> <dl> <dt>should set statusCode</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;, (err, res) =&#x3E; { try { assert.strictEqual(res.statusCode, 200); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>should allow the send shorthand</h1> <dl> <dt>with callback in the method call</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;, (err, res) =&#x3E; { assert.equal(res.status, 200); done(); });</code></pre></dd> <dt>with data in the method call</dt> <dd><pre><code>request.post(&#x60;${uri}/echo&#x60;, { foo: &#x27;bar&#x27; }).end((err, res) =&#x3E; { assert.equal(&#x27;{&#x22;foo&#x22;:&#x22;bar&#x22;}&#x27;, res.text); done(); });</code></pre></dd> <dt>with callback and data in the method call</dt> <dd><pre><code>request.post(&#x60;${uri}/echo&#x60;, { foo: &#x27;bar&#x27; }, (err, res) =&#x3E; { assert.equal(&#x27;{&#x22;foo&#x22;:&#x22;bar&#x22;}&#x27;, res.text); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with a callback</h1> <dl> <dt>should invoke .end()</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;, (err, res) =&#x3E; { try { assert.equal(res.status, 200); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.end()</h1> <dl> <dt>should issue a request</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;).end((err, res) =&#x3E; { try { assert.equal(res.status, 200); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>is optional with a promise</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } return request .get(&#x60;${uri}/login&#x60;) .then((res) =&#x3E; res.status) .then() .then((status) =&#x3E; { assert.equal(200, status, &#x27;Real promises pass results through&#x27;); });</code></pre></dd> <dt>called only once with a promise</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } const req = request.get(&#x60;${uri}/unique&#x60;); return Promise.all([req, req, req]).then((results) =&#x3E; { results.forEach((item) =&#x3E; { assert.equal( item.body, results[0].body, &#x27;It should keep returning the same result after being called once&#x27; ); }); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.error</h1> <dl> <dt>ok</dt> <dd><pre><code>let calledErrorEvent = false; let calledOKHandler = false; request .get(&#x60;${uri}/error&#x60;) .ok((res) =&#x3E; { assert.strictEqual(500, res.status); calledOKHandler = true; return true; }) .on(&#x27;error&#x27;, (err) =&#x3E; { calledErrorEvent = true; }) .end((err, res) =&#x3E; { try { assert.ifError(err); assert.strictEqual(res.status, 500); assert(!calledErrorEvent); assert(calledOKHandler); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should be an Error object</dt> <dd><pre><code>let calledErrorEvent = false; request .get(&#x60;${uri}/error&#x60;) .on(&#x27;error&#x27;, (err) =&#x3E; { assert.strictEqual(err.status, 500); calledErrorEvent = true; }) .end((err, res) =&#x3E; { try { if (NODE) { res.error.message.should.equal(&#x27;cannot GET /error (500)&#x27;); } else { res.error.message.should.equal(&#x60;cannot GET ${uri}/error (500)&#x60;); } assert.strictEqual(res.error.status, 500); assert(err, &#x27;should have an error for 500&#x27;); assert.equal(err.message, &#x27;Internal Server Error&#x27;); assert(calledErrorEvent); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>with .then() promise</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } return request.get(&#x60;${uri}/error&#x60;).then( () =&#x3E; { assert.fail(); }, (err) =&#x3E; { assert.equal(err.message, &#x27;Internal Server Error&#x27;); } );</code></pre></dd> <dt>with .ok() returning false</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } return request .get(&#x60;${uri}/echo&#x60;) .ok(() =&#x3E; false) .then( () =&#x3E; { assert.fail(); }, (err) =&#x3E; { assert.equal(200, err.response.status); assert.equal(err.message, &#x27;OK&#x27;); } );</code></pre></dd> <dt>with .ok() throwing an Error</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return; } return request .get(&#x60;${uri}/echo&#x60;) .ok(() =&#x3E; { throw new Error(&#x27;boom&#x27;); }) .then( () =&#x3E; { assert.fail(); }, (err) =&#x3E; { assert.equal(200, err.response.status); assert.equal(err.message, &#x27;boom&#x27;); } );</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.header</h1> <dl> <dt>should be an object</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;Express&#x27;, res.header[&#x27;x-powered-by&#x27;]); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>set headers</h1> <dl> <dt>should only set headers for ownProperties of header</dt> <dd><pre><code>try { request .get(&#x60;${uri}/echo-headers&#x60;) .set(&#x27;valid&#x27;, &#x27;ok&#x27;) .end((err, res) =&#x3E; { if ( !err &#x26;&#x26; res.body &#x26;&#x26; res.body.valid &#x26;&#x26; !res.body.hasOwnProperty(&#x27;invalid&#x27;) ) { return done(); } done(err || new Error(&#x27;fail&#x27;)); }); } catch (err) { done(err); }</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.charset</h1> <dl> <dt>should be set when present</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;).end((err, res) =&#x3E; { try { res.charset.should.equal(&#x27;utf-8&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.statusType</h1> <dl> <dt>should provide the first digit</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;).end((err, res) =&#x3E; { try { assert(!err, &#x27;should not have an error for success responses&#x27;); assert.equal(200, res.status); assert.equal(2, res.statusType); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.type</h1> <dl> <dt>should provide the mime-type void of params</dt> <dd><pre><code>request.get(&#x60;${uri}/login&#x60;).end((err, res) =&#x3E; { try { res.type.should.equal(&#x27;text/html&#x27;); res.charset.should.equal(&#x27;utf-8&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.set(field, val)</h1> <dl> <dt>should set the header field</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;X-Foo&#x27;, &#x27;bar&#x27;) .set(&#x27;X-Bar&#x27;, &#x27;baz&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.header[&#x27;x-foo&#x27;]); assert.equal(&#x27;baz&#x27;, res.header[&#x27;x-bar&#x27;]); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.set(obj)</h1> <dl> <dt>should set the header fields</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set({ &#x27;X-Foo&#x27;: &#x27;bar&#x27;, &#x27;X-Bar&#x27;: &#x27;baz&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.header[&#x27;x-foo&#x27;]); assert.equal(&#x27;baz&#x27;, res.header[&#x27;x-bar&#x27;]); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.type(str)</h1> <dl> <dt>should set the Content-Type</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;text/x-foo&#x27;) .end((err, res) =&#x3E; { try { res.header[&#x27;content-type&#x27;].should.equal(&#x27;text/x-foo&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should map &#x22;json&#x22;</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;{&#x22;a&#x22;: 1}&#x27;) .end((err, res) =&#x3E; { try { res.should.be.json(); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should map &#x22;html&#x22;</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;html&#x27;) .end((err, res) =&#x3E; { try { res.header[&#x27;content-type&#x27;].should.equal(&#x27;text/html&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.accept(str)</h1> <dl> <dt>should set Accept</dt> <dd><pre><code>request .get(&#x60;${uri}/echo&#x60;) .accept(&#x27;text/x-foo&#x27;) .end((err, res) =&#x3E; { try { res.header.accept.should.equal(&#x27;text/x-foo&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should map &#x22;json&#x22;</dt> <dd><pre><code>request .get(&#x60;${uri}/echo&#x60;) .accept(&#x27;json&#x27;) .end((err, res) =&#x3E; { try { res.header.accept.should.equal(&#x27;application/json&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should map &#x22;xml&#x22;</dt> <dd><pre><code>request .get(&#x60;${uri}/echo&#x60;) .accept(&#x27;xml&#x27;) .end((err, res) =&#x3E; { try { // Mime module keeps changing this :( assert( res.header.accept == &#x27;application/xml&#x27; || res.header.accept == &#x27;text/xml&#x27; ); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should map &#x22;html&#x22;</dt> <dd><pre><code>request .get(&#x60;${uri}/echo&#x60;) .accept(&#x27;html&#x27;) .end((err, res) =&#x3E; { try { res.header.accept.should.equal(&#x27;text/html&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.send(str)</h1> <dl> <dt>should write the string</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;) .end((err, res) =&#x3E; { try { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.send(Object)</h1> <dl> <dt>should default to json</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { try { res.should.be.json(); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <section class="suite"> <h1>when called several times</h1> <dl> <dt>should merge the objects</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .send({ age: 1 }) .end((err, res) =&#x3E; { try { res.should.be.json(); if (NODE) { res.buffered.should.be.true(); } res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;,&#x22;age&#x22;:1}&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>.end(fn)</h1> <dl> <dt>should check arity</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { try { assert.ifError(err); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should emit request</dt> <dd><pre><code>const req = request.post(&#x60;${uri}/echo&#x60;); req.on(&#x27;request&#x27;, (request) =&#x3E; { assert.equal(req, request); done(); }); req.end();</code></pre></dd> <dt>should emit response</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .on(&#x27;response&#x27;, (res) =&#x3E; { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); }) .end();</code></pre></dd> </dl> </section> <section class="suite"> <h1>.then(fulfill, reject)</h1> <dl> <dt>should support successful fulfills with .then(fulfill)</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return done(); } request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .then((res) =&#x3E; { res.type.should.equal(&#x27;application/json&#x27;); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); });</code></pre></dd> <dt>should reject an error with .then(null, reject)</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return done(); } request.get(&#x60;${uri}/error&#x60;).then(null, (err) =&#x3E; { assert.equal(err.status, 500); assert.equal(err.response.text, &#x27;boom&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.catch(reject)</h1> <dl> <dt>should reject an error with .catch(reject)</dt> <dd><pre><code>if (typeof Promise === &#x27;undefined&#x27;) { return done(); } request.get(&#x60;${uri}/error&#x60;).catch((err) =&#x3E; { assert.equal(err.status, 500); assert.equal(err.response.text, &#x27;boom&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.abort()</h1> <dl> <dt>should abort the request</dt> <dd><pre><code>const req = request.get(&#x60;${uri}/delay/3000&#x60;); req.end((err, res) =&#x3E; { try { assert(false, &#x27;should not complete the request&#x27;); } catch (err_) { done(err_); } }); req.on(&#x27;error&#x27;, (error) =&#x3E; { done(error); }); req.on(&#x27;abort&#x27;, done); setTimeout(() =&#x3E; { req.abort(); }, 500);</code></pre></dd> <dt>should abort the promise</dt> <dd><pre><code>const req = request.get(&#x60;${uri}/delay/3000&#x60;); setTimeout(() =&#x3E; { req.abort(); }, 10); return req.then( () =&#x3E; { assert.fail(&#x27;should not complete the request&#x27;); }, (err) =&#x3E; { assert.equal(&#x27;ABORTED&#x27;, err.code); } );</code></pre></dd> <dt>should allow chaining .abort() several times</dt> <dd><pre><code>const req = request.get(&#x60;${uri}/delay/3000&#x60;); req.end((err, res) =&#x3E; { try { assert(false, &#x27;should not complete the request&#x27;); } catch (err_) { done(err_); } }); // This also verifies only a single &#x27;done&#x27; event is emitted req.on(&#x27;abort&#x27;, done); setTimeout(() =&#x3E; { req.abort().abort().abort(); }, 1000);</code></pre></dd> <dt>should not allow abort then end</dt> <dd><pre><code>request .get(&#x60;${uri}/delay/3000&#x60;) .abort() .end((err, res) =&#x3E; { done(err ? undefined : new Error(&#x27;Expected abort error&#x27;)); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.toJSON()</h1> <dl> <dt>should describe the request</dt> <dd><pre><code>const req = request.post(&#x60;${uri}/echo&#x60;).send({ foo: &#x27;baz&#x27; }); req.end((err, res) =&#x3E; { try { const json = req.toJSON(); assert.equal(&#x27;POST&#x27;, json.method); assert(/\/echo$/.test(json.url)); assert.equal(&#x27;baz&#x27;, json.data.foo); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.options()</h1> <dl> <dt>should allow request body</dt> <dd><pre><code>request .options(&#x60;${uri}/options/echo/body&#x60;) .send({ foo: &#x27;baz&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(err, null); assert.strictEqual(res.body.foo, &#x27;baz&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.sortQuery()</h1> <dl> <dt>nop with no querystring</dt> <dd><pre><code>request .get(&#x60;${uri}/url&#x60;) .sortQuery() .end((err, res) =&#x3E; { try { assert.equal(res.text, &#x27;/url&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should sort the request querystring</dt> <dd><pre><code>request .get(&#x60;${uri}/url&#x60;) .query(&#x27;search=Manny&#x27;) .query(&#x27;order=desc&#x27;) .sortQuery() .end((err, res) =&#x3E; { try { assert.equal(res.text, &#x27;/url?order=desc&#x26;search=Manny&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should allow disabling sorting</dt> <dd><pre><code>request .get(&#x60;${uri}/url&#x60;) .query(&#x27;search=Manny&#x27;) .query(&#x27;order=desc&#x27;) .sortQuery() // take default of true .sortQuery(false) // override it in later call .end((err, res) =&#x3E; { try { assert.equal(res.text, &#x27;/url?search=Manny&#x26;order=desc&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should sort the request querystring using customized function</dt> <dd><pre><code>request .get(&#x60;${uri}/url&#x60;) .query(&#x27;name=Nick&#x27;) .query(&#x27;search=Manny&#x27;) .query(&#x27;order=desc&#x27;) .sortQuery((a, b) =&#x3E; a.length - b.length) .end((err, res) =&#x3E; { try { assert.equal(res.text, &#x27;/url?name=Nick&#x26;order=desc&#x26;search=Manny&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.set(&#x22;Content-Type&#x22;, contentType)</h1> <dl> <dt>should work with just the contentType component</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;application/json&#x27;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { assert(!err); done(); });</code></pre></dd> <dt>should work with the charset component</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;application/json; charset=utf-8&#x27;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { assert(!err); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.send(Object) as &#x22;form&#x22;</h1> <dl> <section class="suite"> <h1>with req.type() set to form</h1> <dl> <dt>should send x-www-form-urlencoded data</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .type(&#x27;form&#x27;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { res.header[&#x27;content-type&#x27;].should.equal( &#x27;application/x-www-form-urlencoded&#x27; ); res.text.should.equal(&#x27;name=tobi&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>when called several times</h1> <dl> <dt>should merge the objects</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .type(&#x27;form&#x27;) .send({ name: { first: &#x27;tobi&#x27;, last: &#x27;holowaychuk&#x27; } }) .send({ age: &#x27;1&#x27; }) .end((err, res) =&#x3E; { res.header[&#x27;content-type&#x27;].should.equal( &#x27;application/x-www-form-urlencoded&#x27; ); res.text.should.equal( &#x27;name%5Bfirst%5D=tobi&#x26;name%5Blast%5D=holowaychuk&#x26;age=1&#x27; ); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.attach</h1> <dl> <dt>ignores null file</dt> <dd><pre><code>request .post(&#x27;/echo&#x27;) .attach(&#x27;image&#x27;, null) .end((err, res) =&#x3E; { done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.field</h1> <dl> <dt>allow bools</dt> <dd><pre><code>if (!formDataSupported) { return done(); } request .post(&#x60;${base}/formecho&#x60;) .field(&#x27;bools&#x27;, true) .field(&#x27;strings&#x27;, &#x27;true&#x27;) .end((err, res) =&#x3E; { assert.ifError(err); assert.deepStrictEqual(res.body, { bools: &#x27;true&#x27;, strings: &#x27;true&#x27; }); done(); });</code></pre></dd> <dt>allow objects</dt> <dd><pre><code>if (!formDataSupported) { return done(); } request .post(&#x60;${base}/formecho&#x60;) .field({ bools: true, strings: &#x27;true&#x27; }) .end((err, res) =&#x3E; { assert.ifError(err); assert.deepStrictEqual(res.body, { bools: &#x27;true&#x27;, strings: &#x27;true&#x27; }); done(); });</code></pre></dd> <dt>works with arrays in objects</dt> <dd><pre><code>if (!formDataSupported) { return done(); } request .post(&#x60;${base}/formecho&#x60;) .field({ numbers: [1, 2, 3] }) .end((err, res) =&#x3E; { assert.ifError(err); assert.deepStrictEqual(res.body, { numbers: [&#x27;1&#x27;, &#x27;2&#x27;, &#x27;3&#x27;] }); done(); });</code></pre></dd> <dt>works with arrays</dt> <dd><pre><code>if (!formDataSupported) { return done(); } request .post(&#x60;${base}/formecho&#x60;) .field(&#x27;letters&#x27;, [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;]) .end((err, res) =&#x3E; { assert.ifError(err); assert.deepStrictEqual(res.body, { letters: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;] }); done(); });</code></pre></dd> <dt>throw when empty</dt> <dd><pre><code>should.throws(() =&#x3E; { request.post(&#x60;${base}/echo&#x60;).field(); }, /name/); should.throws(() =&#x3E; { request.post(&#x60;${base}/echo&#x60;).field(&#x27;name&#x27;); }, /val/);</code></pre></dd> <dt>cannot be mixed with send()</dt> <dd><pre><code>assert.throws(() =&#x3E; { request.post(&#x27;/echo&#x27;).field(&#x27;form&#x27;, &#x27;data&#x27;).send(&#x27;hi&#x27;); }); assert.throws(() =&#x3E; { request.post(&#x27;/echo&#x27;).send(&#x27;hi&#x27;).field(&#x27;form&#x27;, &#x27;data&#x27;); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.send(Object) as &#x22;json&#x22;</h1> <dl> <dt>should default to json</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .end((err, res) =&#x3E; { res.should.be.json(); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); });</code></pre></dd> <dt>should work with arrays</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send([1, 2, 3]) .end((err, res) =&#x3E; { res.should.be.json(); res.text.should.equal(&#x27;[1,2,3]&#x27;); done(); });</code></pre></dd> <dt>should work with value null</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;null&#x27;) .end((err, res) =&#x3E; { res.should.be.json(); assert.strictEqual(res.body, null); done(); });</code></pre></dd> <dt>should work with value false</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;false&#x27;) .end((err, res) =&#x3E; { res.should.be.json(); res.body.should.equal(false); done(); });</code></pre></dd> <dt>should work with value 0</dt> <dd><pre><code>// fails in IE9 request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;0&#x27;) .end((err, res) =&#x3E; { res.should.be.json(); res.body.should.equal(0); done(); });</code></pre></dd> <dt>should work with empty string value</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .type(&#x27;json&#x27;) .send(&#x27;&#x22;&#x22;&#x27;) .end((err, res) =&#x3E; { res.should.be.json(); res.body.should.equal(&#x27;&#x27;); done(); });</code></pre></dd> <dt>should work with GET</dt> <dd><pre><code>request .get(&#x60;${uri}/echo&#x60;) .send({ tobi: &#x27;ferret&#x27; }) .end((err, res) =&#x3E; { try { res.should.be.json(); res.text.should.equal(&#x27;{&#x22;tobi&#x22;:&#x22;ferret&#x22;}&#x27;); ({ tobi: &#x27;ferret&#x27; }.should.eql(res.body)); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should work with vendor MIME type</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;application/vnd.example+json&#x27;) .send({ name: &#x27;vendor&#x27; }) .end((err, res) =&#x3E; { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;vendor&#x22;}&#x27;); ({ name: &#x27;vendor&#x27; }.should.eql(res.body)); done(); });</code></pre></dd> <section class="suite"> <h1>when called several times</h1> <dl> <dt>should merge the objects</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send({ name: &#x27;tobi&#x27; }) .send({ age: 1 }) .end((err, res) =&#x3E; { res.should.be.json(); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;,&#x22;age&#x22;:1}&#x27;); ({ name: &#x27;tobi&#x27;, age: 1 }.should.eql(res.body)); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>res.body</h1> <dl> <section class="suite"> <h1>application/json</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request.get(&#x60;${uri}/json&#x60;).end((err, res) =&#x3E; { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;manny&#x22;}&#x27;); res.body.should.eql({ name: &#x27;manny&#x27; }); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>HEAD requests</h1> <dl> <dt>should not throw a parse error</dt> <dd><pre><code>request.head(&#x60;${uri}/json&#x60;).end((err, res) =&#x3E; { try { assert.strictEqual(err, null); assert.strictEqual(res.text, undefined); assert.strictEqual(Object.keys(res.body).length, 0); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>Invalid JSON response</h1> <dl> <dt>should return the raw response</dt> <dd><pre><code>request.get(&#x60;${uri}/invalid-json&#x60;).end((err, res) =&#x3E; { assert.deepEqual( err.rawResponse, &#x22;)]}&#x27;, {&#x27;header&#x27;:{&#x27;code&#x27;:200,&#x27;text&#x27;:&#x27;OK&#x27;,&#x27;version&#x27;:&#x27;1.0&#x27;},&#x27;data&#x27;:&#x27;some data&#x27;}&#x22; ); done(); });</code></pre></dd> <dt>should return the http status code</dt> <dd><pre><code>request.get(&#x60;${uri}/invalid-json-forbidden&#x60;).end((err, res) =&#x3E; { assert.equal(err.statusCode, 403); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>No content</h1> <dl> <dt>should not throw a parse error</dt> <dd><pre><code>request.get(&#x60;${uri}/no-content&#x60;).end((err, res) =&#x3E; { try { assert.strictEqual(err, null); assert.strictEqual(res.text, &#x27;&#x27;); assert.strictEqual(Object.keys(res.body).length, 0); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>application/json+hal</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request.get(&#x60;${uri}/json-hal&#x60;).end((err, res) =&#x3E; { if (err) return done(err); res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;hal 5000&#x22;}&#x27;); res.body.should.eql({ name: &#x27;hal 5000&#x27; }); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>vnd.collection+json</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request.get(&#x60;${uri}/collection-json&#x60;).end((err, res) =&#x3E; { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;chewbacca&#x22;}&#x27;); res.body.should.eql({ name: &#x27;chewbacca&#x27; }); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>on redirect</h1> <dl> <dt>should retain header fields</dt> <dd><pre><code>request .get(&#x60;${base}/header&#x60;) .set(&#x27;X-Foo&#x27;, &#x27;bar&#x27;) .end((err, res) =&#x3E; { try { assert(res.body); res.body.should.have.property(&#x27;x-foo&#x27;, &#x27;bar&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should preserve timeout across redirects</dt> <dd><pre><code>request .get(&#x60;${base}/movies/random&#x60;) .timeout(250) .end((err, res) =&#x3E; { try { assert(err instanceof Error, &#x27;expected an error&#x27;); err.should.have.property(&#x27;timeout&#x27;, 250); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should successfully redirect after retry on error</dt> <dd><pre><code>const id = Math.random() * 1000000 * Date.now(); request .get(&#x60;${base}/error/redirect/${id}&#x60;) .retry(2) .end((err, res) =&#x3E; { assert(res.ok, &#x27;response should be ok&#x27;); assert(res.text, &#x27;first movie page&#x27;); done(); });</code></pre></dd> <dt>should preserve retries across redirects</dt> <dd><pre><code>const id = Math.random() * 1000000 * Date.now(); request .get(&#x60;${base}/error/redirect-error${id}&#x60;) .retry(2) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal(2, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 303</h1> <dl> <dt>should redirect with same method</dt> <dd><pre><code>request .put(&#x60;${base}/redirect-303&#x60;) .send({ msg: &#x27;hello&#x27; }) .redirects(1) .on(&#x27;redirect&#x27;, (res) =&#x3E; { res.headers.location.should.equal(&#x27;/reply-method&#x27;); }) .end((err, res) =&#x3E; { if (err) { done(err); return; } res.text.should.equal(&#x27;method=get&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 307</h1> <dl> <dt>should redirect with same method</dt> <dd><pre><code>if (isMSIE) return done(); // IE9 broken request .put(&#x60;${base}/redirect-307&#x60;) .send({ msg: &#x27;hello&#x27; }) .redirects(1) .on(&#x27;redirect&#x27;, (res) =&#x3E; { res.headers.location.should.equal(&#x27;/reply-method&#x27;); }) .end((err, res) =&#x3E; { if (err) { done(err); return; } res.text.should.equal(&#x27;method=put&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 308</h1> <dl> <dt>should redirect with same method</dt> <dd><pre><code>if (isMSIE) return done(); // IE9 broken request .put(&#x60;${base}/redirect-308&#x60;) .send({ msg: &#x27;hello&#x27; }) .redirects(1) .on(&#x27;redirect&#x27;, (res) =&#x3E; { res.headers.location.should.equal(&#x27;/reply-method&#x27;); }) .end((err, res) =&#x3E; { if (err) { done(err); return; } res.text.should.equal(&#x27;method=put&#x27;); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <dt>Request inheritance</dt> <dd><pre><code>assert(request.get(&#x60;${uri}/&#x60;) instanceof request.Request);</code></pre></dd> <dt>request() simple GET without callback</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x27;test/test.request.js&#x27;).end(); next();</code></pre></dd> <dt>request() simple GET</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/ok&#x60;).end((err, res) =&#x3E; { try { assert(res instanceof request.Response, &#x27;respond with Response&#x27;); assert(res.ok, &#x27;response should be ok&#x27;); assert(res.text, &#x27;res.text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() simple HEAD</dt> <dd><pre><code>request.head(&#x60;${uri}/ok&#x60;).end((err, res) =&#x3E; { try { assert(res instanceof request.Response, &#x27;respond with Response&#x27;); assert(res.ok, &#x27;response should be ok&#x27;); assert(!res.text, &#x27;res.text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 5xx</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/error&#x60;).end((err, res) =&#x3E; { try { assert(err); assert.equal(err.message, &#x27;Internal Server Error&#x27;); assert(!res.ok, &#x27;response should not be ok&#x27;); assert(res.error, &#x27;response should be an error&#x27;); assert(!res.clientError, &#x27;response should not be a client error&#x27;); assert(res.serverError, &#x27;response should be a server error&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 4xx</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/notfound&#x60;).end((err, res) =&#x3E; { try { assert(err); assert.equal(err.message, &#x27;Not Found&#x27;); assert(!res.ok, &#x27;response should not be ok&#x27;); assert(res.error, &#x27;response should be an error&#x27;); assert(res.clientError, &#x27;response should be a client error&#x27;); assert(!res.serverError, &#x27;response should not be a server error&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 404 Not Found</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/notfound&#x60;).end((err, res) =&#x3E; { try { assert(err); assert(res.notFound, &#x27;response should be .notFound&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 400 Bad Request</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/bad-request&#x60;).end((err, res) =&#x3E; { try { assert(err); assert(res.badRequest, &#x27;response should be .badRequest&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 401 Bad Request</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/unauthorized&#x60;).end((err, res) =&#x3E; { try { assert(err); assert(res.unauthorized, &#x27;response should be .unauthorized&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 406 Not Acceptable</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/not-acceptable&#x60;).end((err, res) =&#x3E; { try { assert(err); assert(res.notAcceptable, &#x27;response should be .notAcceptable&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() GET 204 No Content</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/no-content&#x60;).end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.noContent, &#x27;response should be .noContent&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() DELETE 204 No Content</dt> <dd><pre><code>request(&#x27;DELETE&#x27;, &#x60;${uri}/no-content&#x60;).end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.noContent, &#x27;response should be .noContent&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() header parsing</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/notfound&#x60;).end((err, res) =&#x3E; { try { assert(err); assert.equal(&#x27;text/html; charset=utf-8&#x27;, res.header[&#x27;content-type&#x27;]); assert.equal(&#x27;Express&#x27;, res.header[&#x27;x-powered-by&#x27;]); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request() .status</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/notfound&#x60;).end((err, res) =&#x3E; { try { assert(err); assert.equal(404, res.status, &#x27;response .status&#x27;); assert.equal(4, res.statusType, &#x27;response .statusType&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>get()</dt> <dd><pre><code>request.get(&#x60;${uri}/notfound&#x60;).end((err, res) =&#x3E; { try { assert(err); assert.equal(404, res.status, &#x27;response .status&#x27;); assert.equal(4, res.statusType, &#x27;response .statusType&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>put()</dt> <dd><pre><code>request.put(&#x60;${uri}/user/12&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;updated&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>put().send()</dt> <dd><pre><code>request .put(&#x60;${uri}/user/13/body&#x60;) .send({ user: &#x27;new&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;received new&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>post()</dt> <dd><pre><code>request.post(&#x60;${uri}/user&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;created&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>del()</dt> <dd><pre><code>request.del(&#x60;${uri}/user/12&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;deleted&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>delete()</dt> <dd><pre><code>request.delete(&#x60;${uri}/user/12&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;deleted&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>post() data</dt> <dd><pre><code>request .post(&#x60;${uri}/todo/item&#x60;) .type(&#x27;application/octet-stream&#x27;) .send(&#x27;tobi&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added &#x22;tobi&#x22;&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .type()</dt> <dd><pre><code>request .post(&#x60;${uri}/user/12/pet&#x60;) .type(&#x27;urlencoded&#x27;) .send(&#x27;pet=tobi&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added pet &#x22;tobi&#x22;&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .type() with alias</dt> <dd><pre><code>request .post(&#x60;${uri}/user/12/pet&#x60;) .type(&#x27;application/x-www-form-urlencoded&#x27;) .send(&#x27;pet=tobi&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added pet &#x22;tobi&#x22;&#x27;, res.text, &#x27;response text&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .get() with no data or callback</dt> <dd><pre><code>request.get(&#x60;${uri}/echo-header/content-type&#x60;); next();</code></pre></dd> <dt>request .send() with no data only</dt> <dd><pre><code>request.post(&#x60;${uri}/user/5/pet&#x60;).type(&#x27;urlencoded&#x27;).send(&#x27;pet=tobi&#x27;); next();</code></pre></dd> <dt>request .send() with callback only</dt> <dd><pre><code>request .get(&#x60;${uri}/echo-header/accept&#x60;) .set(&#x27;Accept&#x27;, &#x27;foo/bar&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;foo/bar&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .accept() with json</dt> <dd><pre><code>request .get(&#x60;${uri}/echo-header/accept&#x60;) .accept(&#x27;json&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;application/json&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .accept() with application/json</dt> <dd><pre><code>request .get(&#x60;${uri}/echo-header/accept&#x60;) .accept(&#x27;application/json&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;application/json&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .accept() with xml</dt> <dd><pre><code>request .get(&#x60;${uri}/echo-header/accept&#x60;) .accept(&#x27;xml&#x27;) .end((err, res) =&#x3E; { try { // We can&#x27;t depend on mime module to be consistent with this assert(res.text == &#x27;application/xml&#x27; || res.text == &#x27;text/xml&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .accept() with application/xml</dt> <dd><pre><code>request .get(&#x60;${uri}/echo-header/accept&#x60;) .accept(&#x27;application/xml&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;application/xml&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .end()</dt> <dd><pre><code>request .put(&#x60;${uri}/echo-header/content-type&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;text/plain&#x27;) .send(&#x27;wahoo&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;text/plain&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .send()</dt> <dd><pre><code>request .put(&#x60;${uri}/echo-header/content-type&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;text/plain&#x27;) .send(&#x27;wahoo&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;text/plain&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .set()</dt> <dd><pre><code>request .put(&#x60;${uri}/echo-header/content-type&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;text/plain&#x27;) .send(&#x27;wahoo&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;text/plain&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request .set(object)</dt> <dd><pre><code>request .put(&#x60;${uri}/echo-header/content-type&#x60;) .set({ &#x27;Content-Type&#x27;: &#x27;text/plain&#x27; }) .send(&#x27;wahoo&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;text/plain&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST urlencoded</dt> <dd><pre><code>request .post(&#x60;${uri}/pet&#x60;) .type(&#x27;urlencoded&#x27;) .send({ name: &#x27;Manny&#x27;, species: &#x27;cat&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added Manny the cat&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST json</dt> <dd><pre><code>request .post(&#x60;${uri}/pet&#x60;) .type(&#x27;json&#x27;) .send({ name: &#x27;Manny&#x27;, species: &#x27;cat&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added Manny the cat&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST json array</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send([1, 2, 3]) .end((err, res) =&#x3E; { try { assert.equal( &#x27;application/json&#x27;, res.header[&#x27;content-type&#x27;].split(&#x27;;&#x27;)[0] ); assert.equal(&#x27;[1,2,3]&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST json default</dt> <dd><pre><code>request .post(&#x60;${uri}/pet&#x60;) .send({ name: &#x27;Manny&#x27;, species: &#x27;cat&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added Manny the cat&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST json contentType charset</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;application/json; charset=UTF-8&#x27;) .send({ data: [&#x27;data1&#x27;, &#x27;data2&#x27;] }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;{&#x22;data&#x22;:[&#x22;data1&#x22;,&#x22;data2&#x22;]}&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST json contentType vendor</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;application/vnd.example+json&#x27;) .send({ data: [&#x27;data1&#x27;, &#x27;data2&#x27;] }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;{&#x22;data&#x22;:[&#x22;data1&#x22;,&#x22;data2&#x22;]}&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST multiple .send() calls</dt> <dd><pre><code>request .post(&#x60;${uri}/pet&#x60;) .send({ name: &#x27;Manny&#x27; }) .send({ species: &#x27;cat&#x27; }) .end((err, res) =&#x3E; { try { assert.equal(&#x27;added Manny the cat&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST multiple .send() strings</dt> <dd><pre><code>request .post(&#x60;${uri}/echo&#x60;) .send(&#x27;user[name]=tj&#x27;) .send(&#x27;user[email]=tj@vision-media.ca&#x27;) .end((err, res) =&#x3E; { try { assert.equal( &#x27;application/x-www-form-urlencoded&#x27;, res.header[&#x27;content-type&#x27;].split(&#x27;;&#x27;)[0] ); assert.equal( res.text, &#x27;user[name]=tj&#x26;user[email]=tj@vision-media.ca&#x27; ); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST with no data</dt> <dd><pre><code>request .post(&#x60;${uri}/empty-body&#x60;) .send() .end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.noContent, &#x27;response should be .noContent&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET .type</dt> <dd><pre><code>request.get(&#x60;${uri}/pets&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;application/json&#x27;, res.type); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET Content-Type params</dt> <dd><pre><code>request.get(&#x60;${uri}/text&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;utf-8&#x27;, res.charset); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET json</dt> <dd><pre><code>request.get(&#x60;${uri}/pets&#x60;).end((err, res) =&#x3E; { try { assert.deepEqual(res.body, [&#x27;tobi&#x27;, &#x27;loki&#x27;, &#x27;jane&#x27;]); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET json-seq</dt> <dd><pre><code>request .get(&#x60;${uri}/json-seq&#x60;) .buffer() .end((err, res) =&#x3E; { try { assert.ifError(err); assert.deepEqual(res.text, &#x27;\u001E{&#x22;id&#x22;:1}\n\u001E{&#x22;id&#x22;:2}\n&#x27;); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET x-www-form-urlencoded</dt> <dd><pre><code>request.get(&#x60;${uri}/foo&#x60;).end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { foo: &#x27;bar&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET shorthand</dt> <dd><pre><code>request.get(&#x60;${uri}/foo&#x60;, (err, res) =&#x3E; { try { assert.equal(&#x27;foo=bar&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST shorthand</dt> <dd><pre><code>request.post(&#x60;${uri}/user/0/pet&#x60;, { pet: &#x27;tobi&#x27; }, (err, res) =&#x3E; { try { assert.equal(&#x27;added pet &#x22;tobi&#x22;&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>POST shorthand without callback</dt> <dd><pre><code>request.post(&#x60;${uri}/user/0/pet&#x60;, { pet: &#x27;tobi&#x27; }).end((err, res) =&#x3E; { try { assert.equal(&#x27;added pet &#x22;tobi&#x22;&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring object with array</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query({ val: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;] }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { val: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;] }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring object with array and primitives</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query({ array: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;], string: &#x27;foo&#x27;, number: 10 }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { array: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;], string: &#x27;foo&#x27;, number: 10 }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring object with two arrays</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query({ array1: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;], array2: [1, 2, 3] }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { array1: [&#x27;a&#x27;, &#x27;b&#x27;, &#x27;c&#x27;], array2: [1, 2, 3] }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring object</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query({ search: &#x27;Manny&#x27; }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { search: &#x27;Manny&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring append original</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring?search=Manny&#x60;) .query({ range: &#x27;1..5&#x27; }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { search: &#x27;Manny&#x27;, range: &#x27;1..5&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring multiple objects</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query({ search: &#x27;Manny&#x27; }) .query({ range: &#x27;1..5&#x27; }) .query({ order: &#x27;desc&#x27; }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { search: &#x27;Manny&#x27;, range: &#x27;1..5&#x27;, order: &#x27;desc&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring with strings</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query(&#x27;search=Manny&#x27;) .query(&#x27;range=1..5&#x27;) .query(&#x27;order=desc&#x27;) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { search: &#x27;Manny&#x27;, range: &#x27;1..5&#x27;, order: &#x27;desc&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET querystring with strings and objects</dt> <dd><pre><code>request .get(&#x60;${uri}/querystring&#x60;) .query(&#x27;search=Manny&#x27;) .query({ order: &#x27;desc&#x27;, range: &#x27;1..5&#x27; }) .end((err, res) =&#x3E; { try { assert.deepEqual(res.body, { search: &#x27;Manny&#x27;, range: &#x27;1..5&#x27;, order: &#x27;desc&#x27; }); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>GET shorthand payload goes to querystring</dt> <dd><pre><code>request.get( &#x60;${uri}/querystring&#x60;, { foo: &#x27;FOO&#x27;, bar: &#x27;BAR&#x27; }, (err, res) =&#x3E; { try { assert.deepEqual(res.body, { foo: &#x27;FOO&#x27;, bar: &#x27;BAR&#x27; }); next(); } catch (err_) { next(err_); } } );</code></pre></dd> <dt>HEAD shorthand payload goes to querystring</dt> <dd><pre><code>request.head( &#x60;${uri}/querystring-in-header&#x60;, { foo: &#x27;FOO&#x27;, bar: &#x27;BAR&#x27; }, (err, res) =&#x3E; { try { assert.deepEqual(JSON.parse(res.headers.query), { foo: &#x27;FOO&#x27;, bar: &#x27;BAR&#x27; }); next(); } catch (err_) { next(err_); } } );</code></pre></dd> <dt>request(method, url)</dt> <dd><pre><code>request(&#x27;GET&#x27;, &#x60;${uri}/foo&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.body.foo); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request(url)</dt> <dd><pre><code>request(&#x60;${uri}/foo&#x60;).end((err, res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.body.foo); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request(url, fn)</dt> <dd><pre><code>request(&#x60;${uri}/foo&#x60;, (err, res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.body.foo); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>req.timeout(ms)</dt> <dd><pre><code>const req = request.get(&#x60;${uri}/delay/3000&#x60;).timeout(1000); req.end((err, res) =&#x3E; { try { assert(err, &#x27;error missing&#x27;); assert.equal(1000, err.timeout, &#x27;err.timeout missing&#x27;); assert.equal( &#x27;Timeout of 1000ms exceeded&#x27;, err.message, &#x27;err.message incorrect&#x27; ); assert.equal(null, res); assert(req.timedout, true); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>req.timeout(ms) with redirect</dt> <dd><pre><code>const req = request.get(&#x60;${uri}/delay/const&#x60;).timeout(1000); req.end((err, res) =&#x3E; { try { assert(err, &#x27;error missing&#x27;); assert.equal(1000, err.timeout, &#x27;err.timeout missing&#x27;); assert.equal( &#x27;Timeout of 1000ms exceeded&#x27;, err.message, &#x27;err.message incorrect&#x27; ); assert.equal(null, res); assert(req.timedout, true); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>request event</dt> <dd><pre><code>request .get(&#x60;${uri}/foo&#x60;) .on(&#x27;request&#x27;, (req) =&#x3E; { try { assert.equal(&#x60;${uri}/foo&#x60;, req.url); next(); } catch (err) { next(err); } }) .end();</code></pre></dd> <dt>response event</dt> <dd><pre><code>request .get(&#x60;${uri}/foo&#x60;) .on(&#x27;response&#x27;, (res) =&#x3E; { try { assert.equal(&#x27;bar&#x27;, res.body.foo); next(); } catch (err) { next(err); } }) .end();</code></pre></dd> <dt>response should set statusCode</dt> <dd><pre><code>request.get(&#x60;${uri}/ok&#x60;, (err, res) =&#x3E; { try { assert.strictEqual(res.statusCode, 200); next(); } catch (err_) { next(err_); } });</code></pre></dd> <dt>req.toJSON()</dt> <dd><pre><code>request.get(&#x60;${uri}/ok&#x60;).end((err, res) =&#x3E; { try { const j = (res.request || res.req).toJSON(); [&#x27;url&#x27;, &#x27;method&#x27;, &#x27;data&#x27;, &#x27;headers&#x27;].forEach((prop) =&#x3E; { assert(j.hasOwnProperty(prop)); }); next(); } catch (err_) { next(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.retry(count)</h1> <dl> <dt>should not retry if passed &#x22;0&#x22;</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry(0) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal( undefined, err.retries, &#x27;expected an error without .retries&#x27; ); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should not retry if passed an invalid number</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry(-2) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal( undefined, err.retries, &#x27;expected an error without .retries&#x27; ); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should not retry if passed undefined</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry(undefined) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal( undefined, err.retries, &#x27;expected an error without .retries&#x27; ); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle server error after repeat attempt</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry(2) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(2, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should retry if passed nothing</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry() .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(1, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should retry if passed &#x22;true&#x22;</dt> <dd><pre><code>request .get(&#x60;${base}/error&#x60;) .retry(true) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(1, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle successful request after repeat attempt from server error</dt> <dd><pre><code>request .get(&#x60;${base}/error/ok/${uniqid()}&#x60;) .query({ qs: &#x27;present&#x27; }) .retry(2) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.ok, &#x27;response should be ok&#x27;); assert(res.text, &#x27;res.text&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle server timeout error after repeat attempt</dt> <dd><pre><code>request .get(&#x60;${base}/delay/400&#x60;) .timeout(200) .retry(2) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(2, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle successful request after repeat attempt from server timeout</dt> <dd><pre><code>const url = &#x60;/delay/1200/ok/${uniqid()}?built=in&#x60;; request .get(base + url) .query(&#x27;string=ified&#x27;) .query({ json: &#x27;ed&#x27; }) .timeout(600) .retry(2) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.ok, &#x27;response should be ok&#x27;); assert.equal(res.text, &#x60;ok = ${url}&#x26;string=ified&#x26;json=ed&#x60;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle successful request after repeat attempt from server timeout when using .then(fulfill, reject)</dt> <dd><pre><code>const url = &#x60;/delay/1200/ok/${uniqid()}?built=in&#x60;; request .get(base + url) .query(&#x27;string=ified&#x27;) .query({ json: &#x27;ed&#x27; }) .timeout(600) .retry(1) .then((res, err) =&#x3E; { try { assert.ifError(err); assert(res.ok, &#x27;response should be ok&#x27;); assert.equal(res.text, &#x60;ok = ${url}&#x26;string=ified&#x26;json=ed&#x60;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should correctly abort a retry attempt</dt> <dd><pre><code>let aborted = false; const req = request.get(&#x60;${base}/delay/400&#x60;).timeout(200).retry(2); req.end((err, res) =&#x3E; { try { assert(false, &#x27;should not complete the request&#x27;); } catch (err_) { done(err_); } }); req.on(&#x27;abort&#x27;, () =&#x3E; { aborted = true; }); setTimeout(() =&#x3E; { req.abort(); setTimeout(() =&#x3E; { try { assert(aborted, &#x27;should be aborted&#x27;); done(); } catch (err) { done(err); } }, 150); }, 150);</code></pre></dd> <dt>should correctly retain header fields</dt> <dd><pre><code>request .get(&#x60;${base}/error/ok/${uniqid()}&#x60;) .query({ qs: &#x27;present&#x27; }) .retry(2) .set(&#x27;X-Foo&#x27;, &#x27;bar&#x27;) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(res.body); res.body.should.have.property(&#x27;x-foo&#x27;, &#x27;bar&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should not retry on 4xx responses</dt> <dd><pre><code>request .get(&#x60;${base}/bad-request&#x60;) .retry(2) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(0, err.retries, &#x27;expected an error with 0 .retries&#x27;); assert.equal(400, err.status, &#x27;expected an error status of 400&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should execute callback on retry if passed</dt> <dd><pre><code>let callbackCallCount = 0; function retryCallback(request) { callbackCallCount++; } request .get(&#x60;${base}/error&#x60;) .retry(2, retryCallback) .end((err, res) =&#x3E; { try { assert(err, &#x27;expected an error&#x27;); assert.equal(2, err.retries, &#x27;expected an error with .retries&#x27;); assert.equal(500, err.status, &#x27;expected an error status of 500&#x27;); assert.equal( 2, callbackCallCount, &#x27;expected the callback to be called on each retry&#x27; ); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.timeout(ms)</h1> <dl> <section class="suite"> <h1>when timeout is exceeded</h1> <dl> <dt>should error</dt> <dd><pre><code>request .get(&#x60;${base}/delay/500&#x60;) .timeout(150) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); });</code></pre></dd> <dt>should error in promise interface </dt> <dd><pre><code>request .get(&#x60;${base}/delay/500&#x60;) .timeout(150) .catch((err) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); });</code></pre></dd> <dt>should handle gzip timeout</dt> <dd><pre><code>request .get(&#x60;${base}/delay/zip&#x60;) .timeout(150) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); });</code></pre></dd> <dt>should handle buffer timeout</dt> <dd><pre><code>request .get(&#x60;${base}/delay/json&#x60;) .buffer(true) .timeout(150) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); });</code></pre></dd> <dt>should error on deadline</dt> <dd><pre><code>request .get(&#x60;${base}/delay/500&#x60;) .timeout({ deadline: 150 }) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); done(); });</code></pre></dd> <dt>should support setting individual options</dt> <dd><pre><code>request .get(&#x60;${base}/delay/500&#x60;) .timeout({ deadline: 10 }) .timeout({ response: 99999 }) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); assert.equal(&#x27;ETIME&#x27;, err.errno); done(); });</code></pre></dd> <dt>should error on response</dt> <dd><pre><code>request .get(&#x60;${base}/delay/500&#x60;) .timeout({ response: 150 }) .end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); assert.equal( &#x27;number&#x27;, typeof err.timeout, &#x27;expected an error with .timeout&#x27; ); assert.equal(&#x27;ECONNABORTED&#x27;, err.code, &#x27;expected abort error code&#x27;); assert.equal(&#x27;ETIMEDOUT&#x27;, err.errno); done(); });</code></pre></dd> <dt>should accept slow body with fast response</dt> <dd><pre><code>request .get(&#x60;${base}/delay/slowbody&#x60;) .timeout({ response: 1000 }) .on(&#x27;progress&#x27;, () =&#x3E; { // This only makes the test faster without relying on arbitrary timeouts request.get(&#x60;${base}/delay/slowbody/finish&#x60;).end(); }) .end(done);</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>use</h1> <dl> <dt>should use plugin success</dt> <dd><pre><code>const now = &#x60;${Date.now()}&#x60;; function uuid(req) { req.set(&#x27;X-UUID&#x27;, now); return req; } function prefix(req) { req.url = uri + req.url; return req; } request .get(&#x27;/echo&#x27;) .use(uuid) .use(prefix) .end((err, res) =&#x3E; { assert.strictEqual(res.statusCode, 200); assert.equal(res.get(&#x27;X-UUID&#x27;), now); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>subclass</h1> <dl> <dt>should be an instance of Request</dt> <dd><pre><code>const req = request.get(&#x27;/&#x27;); assert(req instanceof request.Request);</code></pre></dd> <dt>should use patched subclass</dt> <dd><pre><code>assert(OriginalRequest); let constructorCalled; let sendCalled; function NewRequest(...args) { constructorCalled = true; OriginalRequest.apply(this, args); } NewRequest.prototype = Object.create(OriginalRequest.prototype); NewRequest.prototype.send = function () { sendCalled = true; return this; }; request.Request = NewRequest; const req = request.get(&#x27;/&#x27;).send(); assert(constructorCalled); assert(sendCalled); assert(req instanceof NewRequest); assert(req instanceof OriginalRequest);</code></pre></dd> <dt>should use patched subclass in agent too</dt> <dd><pre><code>if (!request.agent) return; // Node-only function NewRequest(...args) { OriginalRequest.apply(this, args); } NewRequest.prototype = Object.create(OriginalRequest.prototype); request.Request = NewRequest; const req = request.agent().del(&#x27;/&#x27;); assert(req instanceof NewRequest); assert(req instanceof OriginalRequest);</code></pre></dd> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>persistent agent</h1> <dl> <dt>should gain a session on POST</dt> <dd><pre><code>agent3.post(&#x60;${base}/signin&#x60;).then((res) =&#x3E; { res.should.have.status(200); should.not.exist(res.headers[&#x27;set-cookie&#x27;]); res.text.should.containEql(&#x27;dashboard&#x27;); })</code></pre></dd> <dt>should start with empty session (set cookies)</dt> <dd><pre><code>agent1.get(&#x60;${base}/dashboard&#x60;).end((err, res) =&#x3E; { should.exist(err); res.should.have.status(401); should.exist(res.headers[&#x27;set-cookie&#x27;]); done(); });</code></pre></dd> <dt>should gain a session (cookies already set)</dt> <dd><pre><code>agent1.post(&#x60;${base}/signin&#x60;).then((res) =&#x3E; { res.should.have.status(200); should.not.exist(res.headers[&#x27;set-cookie&#x27;]); res.text.should.containEql(&#x27;dashboard&#x27;); })</code></pre></dd> <dt>should persist cookies across requests</dt> <dd><pre><code>agent1.get(&#x60;${base}/dashboard&#x60;).then((res) =&#x3E; { res.should.have.status(200); })</code></pre></dd> <dt>should have the cookie set in the end callback</dt> <dd><pre><code>agent4 .post(&#x60;${base}/setcookie&#x60;) .then(() =&#x3E; agent4.get(&#x60;${base}/getcookie&#x60;)) .then((res) =&#x3E; { res.should.have.status(200); assert.strictEqual(res.text, &#x27;jar&#x27;); })</code></pre></dd> <dt>should not share cookies</dt> <dd><pre><code>agent2.get(&#x60;${base}/dashboard&#x60;).end((err, res) =&#x3E; { should.exist(err); res.should.have.status(401); done(); });</code></pre></dd> <dt>should not lose cookies between agents</dt> <dd><pre><code>agent1.get(&#x60;${base}/dashboard&#x60;).then((res) =&#x3E; { res.should.have.status(200); })</code></pre></dd> <dt>should be able to follow redirects</dt> <dd><pre><code>agent1.get(base).then((res) =&#x3E; { res.should.have.status(200); res.text.should.containEql(&#x27;dashboard&#x27;); })</code></pre></dd> <dt>should be able to post redirects</dt> <dd><pre><code>agent1 .post(&#x60;${base}/redirect&#x60;) .send({ foo: &#x27;bar&#x27;, baz: &#x27;blaaah&#x27; }) .then((res) =&#x3E; { res.should.have.status(200); res.text.should.containEql(&#x27;simple&#x27;); res.redirects.should.eql([&#x60;${base}/simple&#x60;]); })</code></pre></dd> <dt>should be able to limit redirects</dt> <dd><pre><code>agent1 .get(base) .redirects(0) .end((err, res) =&#x3E; { should.exist(err); res.should.have.status(302); res.redirects.should.eql([]); res.header.location.should.equal(&#x27;/dashboard&#x27;); done(); });</code></pre></dd> <dt>should be able to create a new session (clear cookie)</dt> <dd><pre><code>agent1.post(&#x60;${base}/signout&#x60;).then((res) =&#x3E; { res.should.have.status(200); should.exist(res.headers[&#x27;set-cookie&#x27;]); })</code></pre></dd> <dt>should regenerate with an empty session</dt> <dd><pre><code>agent1.get(&#x60;${base}/dashboard&#x60;).end((err, res) =&#x3E; { should.exist(err); res.should.have.status(401); should.not.exist(res.headers[&#x27;set-cookie&#x27;]); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>Basic auth</h1> <dl> <section class="suite"> <h1>when credentials are present in url</h1> <dl> <dt>should set Authorization</dt> <dd><pre><code>const new_url = URL.parse(base); new_url.auth = &#x27;tobi:learnboost&#x27;; new_url.pathname = &#x27;/basic-auth&#x27;; request.get(URL.format(new_url)).end((err, res) =&#x3E; { res.status.should.equal(200); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.auth(user, pass)</h1> <dl> <dt>should set Authorization</dt> <dd><pre><code>request .get(&#x60;${base}/basic-auth&#x60;) .auth(&#x27;tobi&#x27;, &#x27;learnboost&#x27;) .end((err, res) =&#x3E; { res.status.should.equal(200); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.auth(user + &#x22;:&#x22; + pass)</h1> <dl> <dt>should set authorization</dt> <dd><pre><code>request .get(&#x60;${base}/basic-auth/again&#x60;) .auth(&#x27;tobi&#x27;) .end((err, res) =&#x3E; { res.status.should.eql(200); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>[node] request</h1> <dl> <dt>should send body with .get().send()</dt> <dd><pre><code>request .get(&#x60;${base}/echo&#x60;) .set(&#x27;Content-Type&#x27;, &#x27;text/plain&#x27;) .send(&#x27;wahoo&#x27;) .end((err, res) =&#x3E; { try { assert.equal(&#x27;wahoo&#x27;, res.text); next(); } catch (err_) { next(err_); } });</code></pre></dd> <section class="suite"> <h1>with an url</h1> <dl> <dt>should preserve the encoding of the url</dt> <dd><pre><code>request.get(&#x60;${base}/url?a=(b%29&#x60;).end((err, res) =&#x3E; { assert.equal(&#x27;/url?a=(b%29&#x27;, res.text); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with an object</h1> <dl> <dt>should format the url</dt> <dd><pre><code>request.get(url.parse(&#x60;${base}/login&#x60;)).then((res) =&#x3E; { assert(res.ok); })</code></pre></dd> </dl> </section> <section class="suite"> <h1>without a schema</h1> <dl> <dt>should default to http</dt> <dd><pre><code>request.get(&#x27;localhost:5000/login&#x27;).then((res) =&#x3E; { assert.equal(res.status, 200); })</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.toJSON()</h1> <dl> <dt>should describe the response</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .send({ foo: &#x27;baz&#x27; }) .then((res) =&#x3E; { const obj = res.toJSON(); assert.equal(&#x27;object&#x27;, typeof obj.header); assert.equal(&#x27;object&#x27;, typeof obj.req); assert.equal(200, obj.status); assert.equal(&#x27;{&#x22;foo&#x22;:&#x22;baz&#x22;}&#x27;, obj.text); })</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.links</h1> <dl> <dt>should default to an empty object</dt> <dd><pre><code>request.get(&#x60;${base}/login&#x60;).then((res) =&#x3E; { res.links.should.eql({}); })</code></pre></dd> <dt>should parse the Link header field</dt> <dd><pre><code>request.get(&#x60;${base}/links&#x60;).end((err, res) =&#x3E; { res.links.next.should.equal( &#x27;path_to_url#x27; ); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.unset(field)</h1> <dl> <dt>should remove the header field</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .unset(&#x27;User-Agent&#x27;) .end((err, res) =&#x3E; { assert.equal(void 0, res.header[&#x27;user-agent&#x27;]); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>case-insensitive</h1> <dl> <dt>should set/get header fields case-insensitively</dt> <dd><pre><code>const r = request.post(&#x60;${base}/echo&#x60;); r.set(&#x27;MiXeD&#x27;, &#x27;helloes&#x27;); assert.strictEqual(r.get(&#x27;mixed&#x27;), &#x27;helloes&#x27;);</code></pre></dd> <dt>should unset header fields case-insensitively</dt> <dd><pre><code>const r = request.post(&#x60;${base}/echo&#x60;); r.set(&#x27;MiXeD&#x27;, &#x27;helloes&#x27;); r.unset(&#x27;MIXED&#x27;); assert.strictEqual(r.get(&#x27;mixed&#x27;), undefined);</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.write(str)</h1> <dl> <dt>should write the given data</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.set(&#x27;Content-Type&#x27;, &#x27;application/json&#x27;); assert.equal(&#x27;boolean&#x27;, typeof req.write(&#x27;{&#x22;name&#x22;&#x27;)); assert.equal(&#x27;boolean&#x27;, typeof req.write(&#x27;:&#x22;tobi&#x22;}&#x27;)); req.end((err, res) =&#x3E; { res.text.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.pipe(stream)</h1> <dl> <dt>should pipe the response to the given stream</dt> <dd><pre><code>const stream = new EventEmitter(); stream.buf = &#x27;&#x27;; stream.writable = true; stream.write = function (chunk) { this.buf += chunk; }; stream.end = function () { this.buf.should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); done(); }; request.post(&#x60;${base}/echo&#x60;).send(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;).pipe(stream);</code></pre></dd> </dl> </section> <section class="suite"> <h1>.buffer()</h1> <dl> <dt>should enable buffering</dt> <dd><pre><code>request .get(&#x60;${base}/custom&#x60;) .buffer() .end((err, res) =&#x3E; { assert.ifError(err); assert.equal(&#x27;custom stuff&#x27;, res.text); assert(res.buffered); done(); });</code></pre></dd> <dt>should take precedence over request.buffer[&#x27;someMimeType&#x27;] = false</dt> <dd><pre><code>const type = &#x27;application/barbaz&#x27;; const send = &#x27;some text&#x27;; request.buffer[type] = false; request .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .buffer() .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(res.type, type); assert.equal(send, res.text); assert(res.buffered); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.buffer(false)</h1> <dl> <dt>should disable buffering</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .type(&#x27;application/x-dog&#x27;) .send(&#x27;hello this is dog&#x27;) .buffer(false) .end((err, res) =&#x3E; { assert.ifError(err); assert.equal(null, res.text); res.body.should.eql({}); let buf = &#x27;&#x27;; res.setEncoding(&#x27;utf8&#x27;); res.on(&#x27;data&#x27;, (chunk) =&#x3E; { buf += chunk; }); res.on(&#x27;end&#x27;, () =&#x3E; { buf.should.equal(&#x27;hello this is dog&#x27;); done(); }); });</code></pre></dd> <dt>should take precedence over request.buffer[&#x27;someMimeType&#x27;] = true</dt> <dd><pre><code>const type = &#x27;application/foobar&#x27;; const send = &#x27;hello this is a dog&#x27;; request.buffer[type] = true; request .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .buffer(false) .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(null, res.text); assert.equal(res.type, type); assert(!res.buffered); res.body.should.eql({}); let buf = &#x27;&#x27;; res.setEncoding(&#x27;utf8&#x27;); res.on(&#x27;data&#x27;, (chunk) =&#x3E; { buf += chunk; }); res.on(&#x27;end&#x27;, () =&#x3E; { buf.should.equal(send); done(); }); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.withCredentials()</h1> <dl> <dt>should not throw an error when using the client-side &#x22;withCredentials&#x22; method</dt> <dd><pre><code>request .get(&#x60;${base}/custom&#x60;) .withCredentials() .end((err, res) =&#x3E; { assert.ifError(err); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>.agent()</h1> <dl> <dt>should return the defaut agent</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.agent().should.equal(false); done();</code></pre></dd> </dl> </section> <section class="suite"> <h1>.agent(undefined)</h1> <dl> <dt>should set an agent to undefined and ensure it is chainable</dt> <dd><pre><code>const req = request.get(&#x60;${base}/echo&#x60;); const ret = req.agent(undefined); ret.should.equal(req); assert.strictEqual(req.agent(), undefined); done();</code></pre></dd> </dl> </section> <section class="suite"> <h1>.agent(new http.Agent())</h1> <dl> <dt>should set passed agent</dt> <dd><pre><code>const http = require(&#x27;http&#x27;); const req = request.get(&#x60;${base}/echo&#x60;); const agent = new http.Agent(); const ret = req.agent(agent); ret.should.equal(req); req.agent().should.equal(agent); done();</code></pre></dd> </dl> </section> <section class="suite"> <h1>with a content type other than application/json or text/*</h1> <dl> <dt>should still use buffering</dt> <dd><pre><code>return request .post(&#x60;${base}/echo&#x60;) .type(&#x27;application/x-dog&#x27;) .send(&#x27;hello this is dog&#x27;) .then((res) =&#x3E; { assert.equal(null, res.text); assert.equal(res.body.toString(), &#x27;hello this is dog&#x27;); res.buffered.should.be.true; });</code></pre></dd> </dl> </section> <section class="suite"> <h1>content-length</h1> <dl> <dt>should be set to the byte length of a non-buffer object</dt> <dd><pre><code>const decoder = new StringDecoder(&#x27;utf8&#x27;); let img = fs.readFileSync(&#x60;${__dirname}/fixtures/test.png&#x60;); img = decoder.write(img); request .post(&#x60;${base}/echo&#x60;) .type(&#x27;application/x-image&#x27;) .send(img) .buffer(false) .end((err, res) =&#x3E; { assert.ifError(err); assert(!res.buffered); assert.equal(res.header[&#x27;content-length&#x27;], Buffer.byteLength(img)); done(); });</code></pre></dd> <dt>should be set to the length of a buffer object</dt> <dd><pre><code>const img = fs.readFileSync(&#x60;${__dirname}/fixtures/test.png&#x60;); request .post(&#x60;${base}/echo&#x60;) .type(&#x27;application/x-image&#x27;) .send(img) .buffer(true) .end((err, res) =&#x3E; { assert.ifError(err); assert(res.buffered); assert.equal(res.header[&#x27;content-length&#x27;], img.length); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.buffer[&#x27;someMimeType&#x27;]</h1> <dl> <dt>should respect that agent.buffer(true) takes precedent</dt> <dd><pre><code>const agent = request.agent(); agent.buffer(true); const type = &#x27;application/somerandomtype&#x27;; const send = &#x27;somerandomtext&#x27;; request.buffer[type] = false; agent .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(res.type, type); assert.equal(send, res.text); assert(res.buffered); done(); });</code></pre></dd> <dt>should respect that agent.buffer(false) takes precedent</dt> <dd><pre><code>const agent = request.agent(); agent.buffer(false); const type = &#x27;application/barrr&#x27;; const send = &#x27;some random text2&#x27;; request.buffer[type] = true; agent .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(null, res.text); assert.equal(res.type, type); assert(!res.buffered); res.body.should.eql({}); let buf = &#x27;&#x27;; res.setEncoding(&#x27;utf8&#x27;); res.on(&#x27;data&#x27;, (chunk) =&#x3E; { buf += chunk; }); res.on(&#x27;end&#x27;, () =&#x3E; { buf.should.equal(send); done(); }); });</code></pre></dd> <dt>should disable buffering for that mimetype when false</dt> <dd><pre><code>const type = &#x27;application/bar&#x27;; const send = &#x27;some random text&#x27;; request.buffer[type] = false; request .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(null, res.text); assert.equal(res.type, type); assert(!res.buffered); res.body.should.eql({}); let buf = &#x27;&#x27;; res.setEncoding(&#x27;utf8&#x27;); res.on(&#x27;data&#x27;, (chunk) =&#x3E; { buf += chunk; }); res.on(&#x27;end&#x27;, () =&#x3E; { buf.should.equal(send); done(); }); });</code></pre></dd> <dt>should enable buffering for that mimetype when true</dt> <dd><pre><code>const type = &#x27;application/baz&#x27;; const send = &#x27;woooo&#x27;; request.buffer[type] = true; request .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .end((err, res) =&#x3E; { delete request.buffer[type]; assert.ifError(err); assert.equal(res.type, type); assert.equal(send, res.text); assert(res.buffered); done(); });</code></pre></dd> <dt>should fallback to default handling for that mimetype when undefined</dt> <dd><pre><code>const type = &#x27;application/bazzz&#x27;; const send = &#x27;woooooo&#x27;; return request .post(&#x60;${base}/echo&#x60;) .type(type) .send(send) .then((res) =&#x3E; { assert.equal(res.type, type); assert.equal(send, res.body.toString()); assert(res.buffered); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>exports</h1> <dl> <dt>should expose .protocols</dt> <dd><pre><code>Object.keys(request.protocols).should.eql([&#x27;http:&#x27;, &#x27;https:&#x27;, &#x27;http2:&#x27;]);</code></pre></dd> <dt>should expose .serialize</dt> <dd><pre><code>Object.keys(request.serialize).should.eql([ &#x27;application/x-www-form-urlencoded&#x27;, &#x27;application/json&#x27; ]);</code></pre></dd> <dt>should expose .parse</dt> <dd><pre><code>Object.keys(request.parse).should.eql([ &#x27;application/x-www-form-urlencoded&#x27;, &#x27;application/json&#x27;, &#x27;text&#x27;, &#x27;application/octet-stream&#x27;, &#x27;application/pdf&#x27;, &#x27;image&#x27; ]);</code></pre></dd> <dt>should export .buffer</dt> <dd><pre><code>Object.keys(request.buffer).should.eql([]);</code></pre></dd> </dl> </section> <section class="suite"> <h1>flags</h1> <dl> <section class="suite"> <h1>with 4xx response</h1> <dl> <dt>should set res.error and res.clientError</dt> <dd><pre><code>request.get(&#x60;${base}/notfound&#x60;).end((err, res) =&#x3E; { assert(err); assert(!res.ok, &#x27;response should not be ok&#x27;); assert(res.error, &#x27;response should be an error&#x27;); assert(res.clientError, &#x27;response should be a client error&#x27;); assert(!res.serverError, &#x27;response should not be a server error&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 5xx response</h1> <dl> <dt>should set res.error and res.serverError</dt> <dd><pre><code>request.get(&#x60;${base}/error&#x60;).end((err, res) =&#x3E; { assert(err); assert(!res.ok, &#x27;response should not be ok&#x27;); assert(!res.notFound, &#x27;response should not be notFound&#x27;); assert(res.error, &#x27;response should be an error&#x27;); assert(!res.clientError, &#x27;response should not be a client error&#x27;); assert(res.serverError, &#x27;response should be a server error&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 404 Not Found</h1> <dl> <dt>should res.notFound</dt> <dd><pre><code>request.get(&#x60;${base}/notfound&#x60;).end((err, res) =&#x3E; { assert(err); assert(res.notFound, &#x27;response should be .notFound&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 400 Bad Request</h1> <dl> <dt>should set req.badRequest</dt> <dd><pre><code>request.get(&#x60;${base}/bad-request&#x60;).end((err, res) =&#x3E; { assert(err); assert(res.badRequest, &#x27;response should be .badRequest&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 401 Bad Request</h1> <dl> <dt>should set res.unauthorized</dt> <dd><pre><code>request.get(&#x60;${base}/unauthorized&#x60;).end((err, res) =&#x3E; { assert(err); assert(res.unauthorized, &#x27;response should be .unauthorized&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 406 Not Acceptable</h1> <dl> <dt>should set res.notAcceptable</dt> <dd><pre><code>request.get(&#x60;${base}/not-acceptable&#x60;).end((err, res) =&#x3E; { assert(err); assert(res.notAcceptable, &#x27;response should be .notAcceptable&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 204 No Content</h1> <dl> <dt>should set res.noContent</dt> <dd><pre><code>request.get(&#x60;${base}/no-content&#x60;).end((err, res) =&#x3E; { assert(!err); assert(res.noContent, &#x27;response should be .noContent&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 201 Created</h1> <dl> <dt>should set res.created</dt> <dd><pre><code>request.post(&#x60;${base}/created&#x60;).end((err, res) =&#x3E; { assert(!err); assert(res.created, &#x27;response should be .created&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>with 422 Unprocessable Entity</h1> <dl> <dt>should set res.unprocessableEntity</dt> <dd><pre><code>request.post(&#x60;${base}/unprocessable-entity&#x60;).end((err, res) =&#x3E; { assert(err); assert( res.unprocessableEntity, &#x27;response should be .unprocessableEntity&#x27; ); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>Merging objects</h1> <dl> <dt>Don&#x27;t mix Buffer and JSON</dt> <dd><pre><code>assert.throws(() =&#x3E; { request .post(&#x27;/echo&#x27;) .send(Buffer.from(&#x27;some buffer&#x27;)) .send({ allowed: false }); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.send(String)</h1> <dl> <dt>should default to &#x22;form&#x22;</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .send(&#x27;user[name]=tj&#x27;) .send(&#x27;user[email]=tj@vision-media.ca&#x27;) .end((err, res) =&#x3E; { res.header[&#x27;content-type&#x27;].should.equal( &#x27;application/x-www-form-urlencoded&#x27; ); res.body.should.eql({ user: { name: &#x27;tj&#x27;, email: &#x27;tj@vision-media.ca&#x27; } }); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.body</h1> <dl> <section class="suite"> <h1>application/x-www-form-urlencoded</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request.get(&#x60;${base}/form-data&#x60;).end((err, res) =&#x3E; { res.text.should.equal(&#x27;pet[name]=manny&#x27;); res.body.should.eql({ pet: { name: &#x27;manny&#x27; } }); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>https</h1> <dl> <section class="suite"> <h1>certificate authority</h1> <dl> <section class="suite"> <h1>request</h1> <dl> <dt>should give a good response</dt> <dd><pre><code>request .get(testEndpoint) .ca(ca) .end((err, res) =&#x3E; { assert.ifError(err); assert(res.ok); assert.strictEqual(&#x27;Safe and secure!&#x27;, res.text); done(); });</code></pre></dd> <dt>should reject unauthorized response</dt> <dd><pre><code>return request .get(testEndpoint) .trustLocalhost(false) .then( () =&#x3E; { throw new Error(&#x27;Allows MITM&#x27;); }, () =&#x3E; {} );</code></pre></dd> <dt>should not reject unauthorized response</dt> <dd><pre><code>return request .get(testEndpoint) .disableTLSCerts() .then(({ status }) =&#x3E; { assert.strictEqual(status, 200); });</code></pre></dd> <dt>should trust localhost unauthorized response</dt> <dd><pre><code>return request.get(testEndpoint).trustLocalhost(true);</code></pre></dd> <dt>should trust overriden localhost unauthorized response</dt> <dd><pre><code>return request .get(&#x60;path_to_url{server.address().port}&#x60;) .connect(&#x27;127.0.0.1&#x27;) .trustLocalhost();</code></pre></dd> </dl> </section> <section class="suite"> <h1>.agent</h1> <dl> <dt>should be able to make multiple requests without redefining the certificate</dt> <dd><pre><code>const agent = request.agent({ ca }); agent.get(testEndpoint).end((err, res) =&#x3E; { assert.ifError(err); assert(res.ok); assert.strictEqual(&#x27;Safe and secure!&#x27;, res.text); agent.get(url.parse(testEndpoint)).end((err, res) =&#x3E; { assert.ifError(err); assert(res.ok); assert.strictEqual(&#x27;Safe and secure!&#x27;, res.text); done(); }); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>client certificates</h1> <dl> <section class="suite"> <h1>request</h1> <dl> </dl> </section> <section class="suite"> <h1>.agent</h1> <dl> </dl> </section> </dl> </section> </dl> </section> <section class="suite"> <h1>res.body</h1> <dl> <section class="suite"> <h1>image/png</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request.get(&#x60;${base}/image&#x60;).end((err, res) =&#x3E; { res.type.should.equal(&#x27;image/png&#x27;); Buffer.isBuffer(res.body).should.be.true(); (res.body.length - img.length).should.equal(0); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>application/octet-stream</h1> <dl> <dt>should parse the body</dt> <dd><pre><code>request .get(&#x60;${base}/image-as-octets&#x60;) .buffer(true) // that&#x27;s tech debt :( .end((err, res) =&#x3E; { res.type.should.equal(&#x27;application/octet-stream&#x27;); Buffer.isBuffer(res.body).should.be.true(); (res.body.length - img.length).should.equal(0); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>application/octet-stream</h1> <dl> <dt>should parse the body (using responseType)</dt> <dd><pre><code>request .get(&#x60;${base}/image-as-octets&#x60;) .responseType(&#x27;blob&#x27;) .end((err, res) =&#x3E; { res.type.should.equal(&#x27;application/octet-stream&#x27;); Buffer.isBuffer(res.body).should.be.true(); (res.body.length - img.length).should.equal(0); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>zlib</h1> <dl> <dt>should deflate the content</dt> <dd><pre><code>request.get(base).end((err, res) =&#x3E; { res.should.have.status(200); res.text.should.equal(subject); res.headers[&#x27;content-length&#x27;].should.be.below(subject.length); done(); });</code></pre></dd> <dt>should protect from zip bombs</dt> <dd><pre><code>request .get(base) .buffer(true) .maxResponseSize(1) .end((err, res) =&#x3E; { try { assert.equal(&#x27;Maximum response size reached&#x27;, err &#x26;&#x26; err.message); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should ignore trailing junk</dt> <dd><pre><code>request.get(&#x60;${base}/junk&#x60;).end((err, res) =&#x3E; { res.should.have.status(200); res.text.should.equal(subject); done(); });</code></pre></dd> <dt>should ignore missing data</dt> <dd><pre><code>request.get(&#x60;${base}/chopped&#x60;).end((err, res) =&#x3E; { assert.equal(undefined, err); res.should.have.status(200); res.text.should.startWith(subject); done(); });</code></pre></dd> <dt>should handle corrupted responses</dt> <dd><pre><code>request.get(&#x60;${base}/corrupt&#x60;).end((err, res) =&#x3E; { assert(err, &#x27;missing error&#x27;); assert(!res, &#x27;response should not be defined&#x27;); done(); });</code></pre></dd> <dt>should handle no content with gzip header</dt> <dd><pre><code>request.get(&#x60;${base}/nocontent&#x60;).end((err, res) =&#x3E; { assert.ifError(err); assert(res); res.should.have.status(204); res.text.should.equal(&#x27;&#x27;); res.headers.should.not.have.property(&#x27;content-length&#x27;); done(); });</code></pre></dd> <section class="suite"> <h1>without encoding set</h1> <dl> <dt>should buffer if asked</dt> <dd><pre><code>return request .get(&#x60;${base}/binary&#x60;) .buffer(true) .then((res) =&#x3E; { res.should.have.status(200); assert(res.headers[&#x27;content-length&#x27;]); assert(res.body.byteLength); assert.equal(subject, res.body.toString()); });</code></pre></dd> <dt>should emit buffers</dt> <dd><pre><code>request.get(&#x60;${base}/binary&#x60;).end((err, res) =&#x3E; { res.should.have.status(200); res.headers[&#x27;content-length&#x27;].should.be.below(subject.length); res.on(&#x27;data&#x27;, (chunk) =&#x3E; { chunk.should.have.length(subject.length); }); res.on(&#x27;end&#x27;, done); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>Multipart</h1> <dl> <section class="suite"> <h1>#field(name, value)</h1> <dl> <dt>should set a multipart field value</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.field(&#x27;user[name]&#x27;, &#x27;tobi&#x27;); req.field(&#x27;user[age]&#x27;, &#x27;2&#x27;); req.field(&#x27;user[species]&#x27;, &#x27;ferret&#x27;); return req.then((res) =&#x3E; { res.body[&#x27;user[name]&#x27;].should.equal(&#x27;tobi&#x27;); res.body[&#x27;user[age]&#x27;].should.equal(&#x27;2&#x27;); res.body[&#x27;user[species]&#x27;].should.equal(&#x27;ferret&#x27;); });</code></pre></dd> <dt>should work with file attachments</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.field(&#x27;name&#x27;, &#x27;Tobi&#x27;); req.attach(&#x27;document&#x27;, &#x27;test/node/fixtures/user.html&#x27;); req.field(&#x27;species&#x27;, &#x27;ferret&#x27;); return req.then((res) =&#x3E; { res.body.name.should.equal(&#x27;Tobi&#x27;); res.body.species.should.equal(&#x27;ferret&#x27;); const html = res.files.document; html.name.should.equal(&#x27;user.html&#x27;); html.type.should.equal(&#x27;text/html&#x27;); read(html.path).should.equal(&#x27;&#x3C;h1&#x3E;name&#x3C;/h1&#x3E;&#x27;); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>#attach(name, path)</h1> <dl> <dt>should attach a file</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.attach(&#x27;one&#x27;, &#x27;test/node/fixtures/user.html&#x27;); req.attach(&#x27;two&#x27;, &#x27;test/node/fixtures/user.json&#x27;); req.attach(&#x27;three&#x27;, &#x27;test/node/fixtures/user.txt&#x27;); return req.then((res) =&#x3E; { const html = res.files.one; const json = res.files.two; const text = res.files.three; html.name.should.equal(&#x27;user.html&#x27;); html.type.should.equal(&#x27;text/html&#x27;); read(html.path).should.equal(&#x27;&#x3C;h1&#x3E;name&#x3C;/h1&#x3E;&#x27;); json.name.should.equal(&#x27;user.json&#x27;); json.type.should.equal(&#x27;application/json&#x27;); read(json.path).should.equal(&#x27;{&#x22;name&#x22;:&#x22;tobi&#x22;}&#x27;); text.name.should.equal(&#x27;user.txt&#x27;); text.type.should.equal(&#x27;text/plain&#x27;); read(text.path).should.equal(&#x27;Tobi&#x27;); });</code></pre></dd> <section class="suite"> <h1>when a file does not exist</h1> <dl> <dt>should fail the request with an error</dt> <dd><pre><code>const req = request.post(&#x60;${base}/echo&#x60;); req.attach(&#x27;name&#x27;, &#x27;foo&#x27;); req.attach(&#x27;name2&#x27;, &#x27;bar&#x27;); req.attach(&#x27;name3&#x27;, &#x27;baz&#x27;); req.end((err, res) =&#x3E; { assert.ok(Boolean(err), &#x27;Request should have failed.&#x27;); err.code.should.equal(&#x27;ENOENT&#x27;); err.message.should.containEql(&#x27;ENOENT&#x27;); err.path.should.equal(&#x27;foo&#x27;); done(); });</code></pre></dd> <dt>promise should fail</dt> <dd><pre><code>return request .post(&#x60;${base}/echo&#x60;) .field({ a: 1, b: 2 }) .attach(&#x27;c&#x27;, &#x27;does-not-exist.txt&#x27;) .then( (res) =&#x3E; assert.fail(&#x27;It should not allow this&#x27;), (err) =&#x3E; { err.code.should.equal(&#x27;ENOENT&#x27;); err.path.should.equal(&#x27;does-not-exist.txt&#x27;); } );</code></pre></dd> <dt>should report ECONNREFUSED via the callback</dt> <dd><pre><code>request .post(&#x27;path_to_url#x27;) // nobody is listening there .attach(&#x27;name&#x27;, &#x27;file-does-not-exist&#x27;) .end((err, res) =&#x3E; { assert.ok(Boolean(err), &#x27;Request should have failed&#x27;); err.code.should.equal(&#x27;ECONNREFUSED&#x27;); done(); });</code></pre></dd> <dt>should report ECONNREFUSED via Promise</dt> <dd><pre><code>return request .post(&#x27;path_to_url#x27;) // nobody is listening there .attach(&#x27;name&#x27;, &#x27;file-does-not-exist&#x27;) .then( (res) =&#x3E; assert.fail(&#x27;Request should have failed&#x27;), (err) =&#x3E; err.code.should.equal(&#x27;ECONNREFUSED&#x27;) );</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>#attach(name, path, filename)</h1> <dl> <dt>should use the custom filename</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .attach(&#x27;document&#x27;, &#x27;test/node/fixtures/user.html&#x27;, &#x27;doc.html&#x27;) .then((res) =&#x3E; { const html = res.files.document; html.name.should.equal(&#x27;doc.html&#x27;); html.type.should.equal(&#x27;text/html&#x27;); read(html.path).should.equal(&#x27;&#x3C;h1&#x3E;name&#x3C;/h1&#x3E;&#x27;); })</code></pre></dd> <dt>should fire progress event</dt> <dd><pre><code>let loaded = 0; let total = 0; let uploadEventWasFired = false; request .post(&#x60;${base}/echo&#x60;) .attach(&#x27;document&#x27;, &#x27;test/node/fixtures/user.html&#x27;) .on(&#x27;progress&#x27;, (event) =&#x3E; { total = event.total; loaded = event.loaded; if (event.direction === &#x27;upload&#x27;) { uploadEventWasFired = true; } }) .end((err, res) =&#x3E; { if (err) return done(err); const html = res.files.document; html.name.should.equal(&#x27;user.html&#x27;); html.type.should.equal(&#x27;text/html&#x27;); read(html.path).should.equal(&#x27;&#x3C;h1&#x3E;name&#x3C;/h1&#x3E;&#x27;); total.should.equal(223); loaded.should.equal(223); uploadEventWasFired.should.equal(true); done(); });</code></pre></dd> <dt>filesystem errors should be caught</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .attach(&#x27;filedata&#x27;, &#x27;test/node/fixtures/non-existent-file.ext&#x27;) .end((err, res) =&#x3E; { assert.ok(Boolean(err), &#x27;Request should have failed.&#x27;); err.code.should.equal(&#x27;ENOENT&#x27;); err.path.should.equal(&#x27;test/node/fixtures/non-existent-file.ext&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>#field(name, val)</h1> <dl> <dt>should set a multipart field value</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .field(&#x27;first-name&#x27;, &#x27;foo&#x27;) .field(&#x27;last-name&#x27;, &#x27;bar&#x27;) .end((err, res) =&#x3E; { if (err) done(err); res.should.be.ok(); res.body[&#x27;first-name&#x27;].should.equal(&#x27;foo&#x27;); res.body[&#x27;last-name&#x27;].should.equal(&#x27;bar&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>#field(object)</h1> <dl> <dt>should set multiple multipart fields</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .field({ &#x27;first-name&#x27;: &#x27;foo&#x27;, &#x27;last-name&#x27;: &#x27;bar&#x27; }) .end((err, res) =&#x3E; { if (err) done(err); res.should.be.ok(); res.body[&#x27;first-name&#x27;].should.equal(&#x27;foo&#x27;); res.body[&#x27;last-name&#x27;].should.equal(&#x27;bar&#x27;); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>with network error</h1> <dl> <dt>should error</dt> <dd><pre><code>request.get(&#x60;path_to_url{this.port}/&#x60;).end((err, res) =&#x3E; { assert(err, &#x27;expected an error&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>not modified</h1> <dl> <dt>should start with 200</dt> <dd><pre><code>request.get(&#x60;${base}/if-mod&#x60;).end((err, res) =&#x3E; { res.should.have.status(200); res.text.should.match(/^\d+$/); ts = Number(res.text); done(); });</code></pre></dd> <dt>should then be 304</dt> <dd><pre><code>request .get(&#x60;${base}/if-mod&#x60;) .set(&#x27;If-Modified-Since&#x27;, new Date(ts).toUTCString()) .end((err, res) =&#x3E; { res.should.have.status(304); // res.text.should.be.empty done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.parse(fn)</h1> <dl> <dt>should take precedence over default parsers</dt> <dd><pre><code>request .get(&#x60;${base}/manny&#x60;) .parse(request.parse[&#x27;application/json&#x27;]) .end((err, res) =&#x3E; { assert(res.ok); assert.equal(&#x27;{&#x22;name&#x22;:&#x22;manny&#x22;}&#x27;, res.text); assert.equal(&#x27;manny&#x27;, res.body.name); done(); });</code></pre></dd> <dt>should be the only parser</dt> <dd><pre><code>request .get(&#x60;${base}/image&#x60;) .buffer(false) .parse((res, fn) =&#x3E; { res.on(&#x27;data&#x27;, () =&#x3E; {}); }) .then((res) =&#x3E; { assert(res.ok); assert.strictEqual(res.text, undefined); res.body.should.eql({}); })</code></pre></dd> <dt>should emit error if parser throws</dt> <dd><pre><code>request .get(&#x60;${base}/manny&#x60;) .parse(() =&#x3E; { throw new Error(&#x27;I am broken&#x27;); }) .on(&#x27;error&#x27;, (err) =&#x3E; { err.message.should.equal(&#x27;I am broken&#x27;); done(); }) .end();</code></pre></dd> <dt>should emit error if parser returns an error</dt> <dd><pre><code>request .get(&#x60;${base}/manny&#x60;) .parse((res, fn) =&#x3E; { fn(new Error(&#x27;I am broken&#x27;)); }) .on(&#x27;error&#x27;, (err) =&#x3E; { err.message.should.equal(&#x27;I am broken&#x27;); done(); }) .end();</code></pre></dd> <dt>should not emit error on chunked json</dt> <dd><pre><code>request.get(&#x60;${base}/chunked-json&#x60;).end((err) =&#x3E; { assert.ifError(err); done(); });</code></pre></dd> <dt>should not emit error on aborted chunked json</dt> <dd><pre><code>const req = request.get(&#x60;${base}/chunked-json&#x60;); req.end((err) =&#x3E; { assert.ifError(err); done(); }); setTimeout(() =&#x3E; { req.abort(); }, 50);</code></pre></dd> </dl> </section> <section class="suite"> <h1>pipe on redirect</h1> <dl> <dt>should follow Location</dt> <dd><pre><code>const stream = fs.createWriteStream(destPath); const redirects = []; const req = request .get(base) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .connect({ inapplicable: &#x27;should be ignored&#x27; }); stream.on(&#x27;finish&#x27;, () =&#x3E; { redirects.should.eql([&#x27;/movies&#x27;, &#x27;/movies/all&#x27;, &#x27;/movies/all/0&#x27;]); fs.readFileSync(destPath, &#x27;utf8&#x27;).should.eql(&#x27;first movie page&#x27;); done(); }); req.pipe(stream);</code></pre></dd> </dl> </section> <section class="suite"> <h1>request pipe</h1> <dl> <dt>should act as a writable stream</dt> <dd><pre><code>const req = request.post(base); const stream = fs.createReadStream(&#x27;test/node/fixtures/user.json&#x27;); req.type(&#x27;json&#x27;); req.on(&#x27;response&#x27;, (res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27; }); done(); }); stream.pipe(req);</code></pre></dd> <dt>end() stops piping</dt> <dd><pre><code>const stream = fs.createWriteStream(destPath); request.get(base).end((err, res) =&#x3E; { try { res.pipe(stream); return done(new Error(&#x27;Did not prevent nonsense pipe&#x27;)); } catch { /* expected error */ } done(); });</code></pre></dd> <dt>should act as a readable stream</dt> <dd><pre><code>const stream = fs.createWriteStream(destPath); let responseCalled = false; const req = request.get(base); req.type(&#x27;json&#x27;); req.on(&#x27;response&#x27;, (res) =&#x3E; { res.status.should.eql(200); responseCalled = true; }); stream.on(&#x27;finish&#x27;, () =&#x3E; { JSON.parse(fs.readFileSync(destPath, &#x27;utf8&#x27;)).should.eql({ name: &#x27;tobi&#x27; }); responseCalled.should.be.true(); done(); }); req.pipe(stream);</code></pre></dd> <dt>should follow redirects</dt> <dd><pre><code>const stream = fs.createWriteStream(destPath); let responseCalled = false; const req = request.get(base + &#x27;/redirect&#x27;); req.type(&#x27;json&#x27;); req.on(&#x27;response&#x27;, (res) =&#x3E; { res.status.should.eql(200); responseCalled = true; }); stream.on(&#x27;finish&#x27;, () =&#x3E; { JSON.parse(fs.readFileSync(destPath, &#x27;utf8&#x27;)).should.eql({ name: &#x27;tobi&#x27; }); responseCalled.should.be.true(); done(); }); req.pipe(stream);</code></pre></dd> <dt>should not throw on bad redirects</dt> <dd><pre><code>const stream = fs.createWriteStream(destPath); let responseCalled = false; let errorCalled = false; const req = request.get(base + &#x27;/badRedirectNoLocation&#x27;); req.type(&#x27;json&#x27;); req.on(&#x27;response&#x27;, (res) =&#x3E; { responseCalled = true; }); req.on(&#x27;error&#x27;, (err) =&#x3E; { err.message.should.eql(&#x27;No location header for redirect&#x27;); errorCalled = true; stream.end(); }); stream.on(&#x27;finish&#x27;, () =&#x3E; { responseCalled.should.be.false(); errorCalled.should.be.true(); done(); }); req.pipe(stream);</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.query(String)</h1> <dl> <dt>should support passing in a string</dt> <dd><pre><code>request .del(base) .query(&#x27;name=t%F6bi&#x27;) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;t%F6bi&#x27; }); done(); });</code></pre></dd> <dt>should work with url query-string and string for query</dt> <dd><pre><code>request .del(&#x60;${base}/?name=tobi&#x60;) .query(&#x27;age=2%20&#x27;) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27;, age: &#x27;2 &#x27; }); done(); });</code></pre></dd> <dt>should support compound elements in a string</dt> <dd><pre><code>request .del(base) .query(&#x27;name=t%F6bi&#x26;age=2&#x27;) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;t%F6bi&#x27;, age: &#x27;2&#x27; }); done(); });</code></pre></dd> <dt>should work when called multiple times with a string</dt> <dd><pre><code>request .del(base) .query(&#x27;name=t%F6bi&#x27;) .query(&#x27;age=2%F6&#x27;) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;t%F6bi&#x27;, age: &#x27;2%F6&#x27; }); done(); });</code></pre></dd> <dt>should work with normal &#x60;query&#x60; object and query string</dt> <dd><pre><code>request .del(base) .query(&#x27;name=t%F6bi&#x27;) .query({ age: &#x27;2&#x27; }) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;t%F6bi&#x27;, age: &#x27;2&#x27; }); done(); });</code></pre></dd> <dt>should not encode raw backticks, but leave encoded ones as is</dt> <dd><pre><code>return Promise.all([ request .get(&#x60;${base}/raw-query&#x60;) .query(&#x27;name=&#x60;t%60bi&#x60;&#x26;age&#x60;=2&#x27;) .then((res) =&#x3E; { res.text.should.eql(&#x27;name=&#x60;t%60bi&#x60;&#x26;age&#x60;=2&#x27;); }), request.get(base + &#x27;/raw-query?&#x60;age%60&#x60;=2%60&#x60;&#x27;).then((res) =&#x3E; { res.text.should.eql(&#x27;&#x60;age%60&#x60;=2%60&#x60;&#x27;); }), request .get(&#x60;${base}/raw-query&#x60;) .query(&#x27;name=&#x60;t%60bi&#x60;&#x27;) .query(&#x27;age&#x60;=2&#x27;) .then((res) =&#x3E; { res.text.should.eql(&#x27;name=&#x60;t%60bi&#x60;&#x26;age&#x60;=2&#x27;); }) ]);</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.query(Object)</h1> <dl> <dt>should construct the query-string</dt> <dd><pre><code>request .del(base) .query({ name: &#x27;tobi&#x27; }) .query({ order: &#x27;asc&#x27; }) .query({ limit: [&#x27;1&#x27;, &#x27;2&#x27;] }) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27;, order: &#x27;asc&#x27;, limit: [&#x27;1&#x27;, &#x27;2&#x27;] }); done(); });</code></pre></dd> <dt>should encode raw backticks</dt> <dd><pre><code>request .get(&#x60;${base}/raw-query&#x60;) .query({ name: &#x27;&#x60;tobi&#x60;&#x27; }) .query({ &#x27;orde%60r&#x27;: null }) .query({ &#x27;&#x60;limit&#x60;&#x27;: [&#x27;%602&#x60;&#x27;] }) .end((err, res) =&#x3E; { res.text.should.eql(&#x27;name=%60tobi%60&#x26;orde%2560r&#x26;%60limit%60=%25602%60&#x27;); done(); });</code></pre></dd> <dt>should not error on dates</dt> <dd><pre><code>const date = new Date(0); request .del(base) .query({ at: date }) .end((err, res) =&#x3E; { assert.equal(date.toISOString(), res.body.at); done(); });</code></pre></dd> <dt>should work after setting header fields</dt> <dd><pre><code>request .del(base) .set(&#x27;Foo&#x27;, &#x27;bar&#x27;) .set(&#x27;Bar&#x27;, &#x27;baz&#x27;) .query({ name: &#x27;tobi&#x27; }) .query({ order: &#x27;asc&#x27; }) .query({ limit: [&#x27;1&#x27;, &#x27;2&#x27;] }) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27;, order: &#x27;asc&#x27;, limit: [&#x27;1&#x27;, &#x27;2&#x27;] }); done(); });</code></pre></dd> <dt>should append to the original query-string</dt> <dd><pre><code>request .del(&#x60;${base}/?name=tobi&#x60;) .query({ order: &#x27;asc&#x27; }) .end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27;, order: &#x27;asc&#x27; }); done(); });</code></pre></dd> <dt>should retain the original query-string</dt> <dd><pre><code>request.del(&#x60;${base}/?name=tobi&#x60;).end((err, res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27; }); done(); });</code></pre></dd> <dt>should keep only keys with null querystring values</dt> <dd><pre><code>request .del(&#x60;${base}/url&#x60;) .query({ nil: null }) .end((err, res) =&#x3E; { res.text.should.equal(&#x27;/url?nil&#x27;); done(); });</code></pre></dd> <dt>query-string should be sent on pipe</dt> <dd><pre><code>const req = request.put(&#x60;${base}/?name=tobi&#x60;); const stream = fs.createReadStream(&#x27;test/node/fixtures/user.json&#x27;); req.on(&#x27;response&#x27;, (res) =&#x3E; { res.body.should.eql({ name: &#x27;tobi&#x27; }); done(); }); stream.pipe(req);</code></pre></dd> </dl> </section> <section class="suite"> <h1>request.get</h1> <dl> <section class="suite"> <h1>on 301 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.get(&#x60;${base}/test-301&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 302 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.get(&#x60;${base}/test-302&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 303 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.get(&#x60;${base}/test-303&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 307 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.get(&#x60;${base}/test-307&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 308 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.get(&#x60;${base}/test-308&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>request.post</h1> <dl> <section class="suite"> <h1>on 301 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.post(&#x60;${base}/test-301&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 302 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.post(&#x60;${base}/test-302&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 303 redirect</h1> <dl> <dt>should follow Location with a GET request</dt> <dd><pre><code>const req = request.post(&#x60;${base}/test-303&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;GET&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 307 redirect</h1> <dl> <dt>should follow Location with a POST request</dt> <dd><pre><code>const req = request.post(&#x60;${base}/test-307&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;POST&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on 308 redirect</h1> <dl> <dt>should follow Location with a POST request</dt> <dd><pre><code>const req = request.post(&#x60;${base}/test-308&#x60;).redirects(1); req.end((err, res) =&#x3E; { const headers = req.req.getHeaders ? req.req.getHeaders() : req.req._headers; headers.host.should.eql(&#x60;localhost:${server2.address().port}&#x60;); res.status.should.eql(200); res.text.should.eql(&#x27;POST&#x27;); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>request</h1> <dl> <section class="suite"> <h1>on redirect</h1> <dl> <dt>should merge cookies if agent is used</dt> <dd><pre><code>request .agent() .get(&#x60;${base}/cookie-redirect&#x60;) .set(&#x27;Cookie&#x27;, &#x27;orig=1; replaced=not&#x27;) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(/orig=1/.test(res.text), &#x27;orig=1/.test&#x27;); assert(/replaced=yes/.test(res.text), &#x27;replaced=yes/.test&#x27;); assert(/from-redir=1/.test(res.text), &#x27;from-redir=1&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should not merge cookies if agent is not used</dt> <dd><pre><code>request .get(&#x60;${base}/cookie-redirect&#x60;) .set(&#x27;Cookie&#x27;, &#x27;orig=1; replaced=not&#x27;) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(/orig=1/.test(res.text), &#x27;/orig=1&#x27;); assert(/replaced=not/.test(res.text), &#x27;/replaced=not&#x27;); assert(!/replaced=yes/.test(res.text), &#x27;!/replaced=yes&#x27;); assert(!/from-redir/.test(res.text), &#x27;!/from-redir&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should have previously set cookie for subsquent requests when agent is used</dt> <dd><pre><code>const agent = request.agent(); agent.get(&#x60;${base}/set-cookie&#x60;).end((err) =&#x3E; { assert.ifError(err); agent .get(&#x60;${base}/show-cookies&#x60;) .set({ Cookie: &#x27;orig=1&#x27; }) .end((err, res) =&#x3E; { try { assert.ifError(err); assert(/orig=1/.test(res.text), &#x27;orig=1/.test&#x27;); assert(/persist=123/.test(res.text), &#x27;persist=123&#x27;); done(); } catch (err_) { done(err_); } }); });</code></pre></dd> <dt>should follow Location</dt> <dd><pre><code>const redirects = []; request .get(base) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { const arr = [&#x27;/movies&#x27;, &#x27;/movies/all&#x27;, &#x27;/movies/all/0&#x27;]; redirects.should.eql(arr); res.text.should.equal(&#x27;first movie page&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should follow Location with IP override</dt> <dd><pre><code>const redirects = []; const url = URL.parse(base); return request .get(&#x60;path_to_url{url.port || &#x27;80&#x27;}${url.pathname}&#x60;) .connect({ &#x27;*&#x27;: url.hostname }) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .then((res) =&#x3E; { const arr = [&#x27;/movies&#x27;, &#x27;/movies/all&#x27;, &#x27;/movies/all/0&#x27;]; redirects.should.eql(arr); res.text.should.equal(&#x27;first movie page&#x27;); });</code></pre></dd> <dt>should follow Location with IP:port override</dt> <dd><pre><code>const redirects = []; const url = URL.parse(base); return request .get(&#x60;path_to_url{url.pathname}&#x60;) .connect({ &#x27;*&#x27;: { host: url.hostname, port: url.port || 80 } }) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .then((res) =&#x3E; { const arr = [&#x27;/movies&#x27;, &#x27;/movies/all&#x27;, &#x27;/movies/all/0&#x27;]; redirects.should.eql(arr); res.text.should.equal(&#x27;first movie page&#x27;); });</code></pre></dd> <dt>should not follow on HEAD by default</dt> <dd><pre><code>const redirects = []; return request .head(base) .ok(() =&#x3E; true) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .then((res) =&#x3E; { redirects.should.eql([]); res.status.should.equal(302); });</code></pre></dd> <dt>should follow on HEAD when redirects are set</dt> <dd><pre><code>const redirects = []; request .head(base) .redirects(10) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { const arr = []; arr.push(&#x27;/movies&#x27;); arr.push(&#x27;/movies/all&#x27;); arr.push(&#x27;/movies/all/0&#x27;); redirects.should.eql(arr); assert(!res.text); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should remove Content-* fields</dt> <dd><pre><code>request .post(&#x60;${base}/header&#x60;) .type(&#x27;txt&#x27;) .set(&#x27;X-Foo&#x27;, &#x27;bar&#x27;) .set(&#x27;X-Bar&#x27;, &#x27;baz&#x27;) .send(&#x27;hey&#x27;) .end((err, res) =&#x3E; { try { assert(res.body); res.body.should.have.property(&#x27;x-foo&#x27;, &#x27;bar&#x27;); res.body.should.have.property(&#x27;x-bar&#x27;, &#x27;baz&#x27;); res.body.should.not.have.property(&#x27;content-type&#x27;); res.body.should.not.have.property(&#x27;content-length&#x27;); res.body.should.not.have.property(&#x27;transfer-encoding&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should retain cookies</dt> <dd><pre><code>request .get(&#x60;${base}/header&#x60;) .set(&#x27;Cookie&#x27;, &#x27;foo=bar;&#x27;) .end((err, res) =&#x3E; { try { assert(res.body); res.body.should.have.property(&#x27;cookie&#x27;, &#x27;foo=bar;&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should not resend query parameters</dt> <dd><pre><code>const redirects = []; const query = []; request .get(&#x60;${base}/?foo=bar&#x60;) .on(&#x27;redirect&#x27;, (res) =&#x3E; { query.push(res.headers.query); redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { const arr = []; arr.push(&#x27;/movies&#x27;); arr.push(&#x27;/movies/all&#x27;); arr.push(&#x27;/movies/all/0&#x27;); redirects.should.eql(arr); res.text.should.equal(&#x27;first movie page&#x27;); query.should.eql([&#x27;{&#x22;foo&#x22;:&#x22;bar&#x22;}&#x27;, &#x27;{}&#x27;, &#x27;{}&#x27;]); res.headers.query.should.eql(&#x27;{}&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should handle no location header</dt> <dd><pre><code>request.get(&#x60;${base}/bad-redirect&#x60;).end((err, res) =&#x3E; { try { err.message.should.equal(&#x27;No location header for redirect&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <section class="suite"> <h1>when relative</h1> <dl> <dt>should redirect to a sibling path</dt> <dd><pre><code>const redirects = []; request .get(&#x60;${base}/relative&#x60;) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { redirects.should.eql([&#x27;tobi&#x27;]); res.text.should.equal(&#x27;tobi&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> <dt>should redirect to a parent path</dt> <dd><pre><code>const redirects = []; request .get(&#x60;${base}/relative/sub&#x60;) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { redirects.should.eql([&#x27;../tobi&#x27;]); res.text.should.equal(&#x27;tobi&#x27;); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.redirects(n)</h1> <dl> <dt>should alter the default number of redirects to follow</dt> <dd><pre><code>const redirects = []; request .get(base) .redirects(2) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .end((err, res) =&#x3E; { try { const arr = []; assert(res.redirect, &#x27;res.redirect&#x27;); arr.push(&#x27;/movies&#x27;); arr.push(&#x27;/movies/all&#x27;); redirects.should.eql(arr); res.text.should.match(/Moved Temporarily|Found/); done(); } catch (err_) { done(err_); } });</code></pre></dd> </dl> </section> <section class="suite"> <h1>on POST</h1> <dl> <dt>should redirect as GET</dt> <dd><pre><code>const redirects = []; return request .post(&#x60;${base}/movie&#x60;) .send({ name: &#x27;Tobi&#x27; }) .redirects(2) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .then((res) =&#x3E; { redirects.should.eql([&#x27;/movies/all/0&#x27;]); res.text.should.equal(&#x27;first movie page&#x27;); });</code></pre></dd> <dt>using multipart/form-data should redirect as GET</dt> <dd><pre><code>const redirects = []; request .post(&#x60;${base}/movie&#x60;) .type(&#x27;form&#x27;) .field(&#x27;name&#x27;, &#x27;Tobi&#x27;) .redirects(2) .on(&#x27;redirect&#x27;, (res) =&#x3E; { redirects.push(res.headers.location); }) .then((res) =&#x3E; { redirects.should.eql([&#x27;/movies/all/0&#x27;]); res.text.should.equal(&#x27;first movie page&#x27;); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>response</h1> <dl> <dt>should act as a readable stream</dt> <dd><pre><code>const req = request.get(base).buffer(false); req.end((err, res) =&#x3E; { if (err) return done(err); let trackEndEvent = 0; let trackCloseEvent = 0; res.on(&#x27;end&#x27;, () =&#x3E; { trackEndEvent++; trackEndEvent.should.equal(1); if (!process.env.HTTP2_TEST) { trackCloseEvent.should.equal(0); // close should not have been called } done(); }); res.on(&#x27;close&#x27;, () =&#x3E; { trackCloseEvent++; }); (() =&#x3E; { res.pause(); }).should.not.throw(); (() =&#x3E; { res.resume(); }).should.not.throw(); (() =&#x3E; { res.destroy(); }).should.not.throw(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>req.serialize(fn)</h1> <dl> <dt>should take precedence over default parsers</dt> <dd><pre><code>request .post(&#x60;${base}/echo&#x60;) .send({ foo: 123 }) .serialize((data) =&#x3E; &#x27;{&#x22;bar&#x22;:456}&#x27;) .end((err, res) =&#x3E; { assert.ifError(err); assert.equal(&#x27;{&#x22;bar&#x22;:456}&#x27;, res.text); assert.equal(456, res.body.bar); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>request.get().set()</h1> <dl> <dt>should set host header after get()</dt> <dd><pre><code>app.get(&#x27;/&#x27;, (req, res) =&#x3E; { assert.equal(req.hostname, &#x27;example.com&#x27;); res.end(); }); server = http.createServer(app); server.listen(0, function listening() { request .get(&#x60;path_to_url{server.address().port}&#x60;) .set(&#x27;host&#x27;, &#x27;example.com&#x27;) .then(() =&#x3E; { return request .get(&#x60;path_to_url{server.address().port}&#x60;) .connect({ &#x27;example.com&#x27;: &#x27;localhost&#x27;, &#x27;*&#x27;: &#x27;fail&#x27; }); }) .then(() =&#x3E; done(), done); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>res.toError()</h1> <dl> <dt>should return an Error</dt> <dd><pre><code>request.get(base).end((err, res) =&#x3E; { var err = res.toError(); assert.equal(err.status, 400); assert.equal(err.method, &#x27;GET&#x27;); assert.equal(err.path, &#x27;/&#x27;); assert.equal(err.message, &#x27;cannot GET / (400)&#x27;); assert.equal(err.text, &#x27;invalid json&#x27;); done(); });</code></pre></dd> </dl> </section> <section class="suite"> <h1>[unix-sockets] http</h1> <dl> <section class="suite"> <h1>request</h1> <dl> <dt>path: / (root)</dt> <dd><pre><code>request.get(&#x60;${base}/&#x60;).end((err, res) =&#x3E; { assert(res.ok); assert.strictEqual(&#x27;root ok!&#x27;, res.text); done(); });</code></pre></dd> <dt>path: /request/path</dt> <dd><pre><code>request.get(&#x60;${base}/request/path&#x60;).end((err, res) =&#x3E; { assert(res.ok); assert.strictEqual(&#x27;request path ok!&#x27;, res.text); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>[unix-sockets] https</h1> <dl> <section class="suite"> <h1>request</h1> <dl> <dt>path: / (root)</dt> <dd><pre><code>request .get(&#x60;${base}/&#x60;) .ca(cacert) .end((err, res) =&#x3E; { assert.ifError(err); assert(res.ok); assert.strictEqual(&#x27;root ok!&#x27;, res.text); done(); });</code></pre></dd> <dt>path: /request/path</dt> <dd><pre><code>request .get(&#x60;${base}/request/path&#x60;) .ca(cacert) .end((err, res) =&#x3E; { assert.ifError(err); assert(res.ok); assert.strictEqual(&#x27;request path ok!&#x27;, res.text); done(); });</code></pre></dd> </dl> </section> </dl> </section> <section class="suite"> <h1>req.get()</h1> <dl> <dt>should not set a default user-agent</dt> <dd><pre><code>request.get(&#x60;${base}/ua&#x60;).then((res) =&#x3E; { assert(res.headers); assert(!res.headers[&#x27;user-agent&#x27;]); })</code></pre></dd> </dl> </section> <section class="suite"> <h1>utils.type(str)</h1> <dl> <dt>should return the mime type</dt> <dd><pre><code>utils .type(&#x27;application/json; charset=utf-8&#x27;) .should.equal(&#x27;application/json&#x27;); utils.type(&#x27;application/json&#x27;).should.equal(&#x27;application/json&#x27;);</code></pre></dd> </dl> </section> <section class="suite"> <h1>utils.params(str)</h1> <dl> <dt>should return the field parameters</dt> <dd><pre><code>const obj = utils.params(&#x27;application/json; charset=utf-8; foo = bar&#x27;); obj.charset.should.equal(&#x27;utf-8&#x27;); obj.foo.should.equal(&#x27;bar&#x27;); utils.params(&#x27;application/json&#x27;).should.eql({});</code></pre></dd> </dl> </section> <section class="suite"> <h1>utils.parseLinks(str)</h1> <dl> <dt>should parse links</dt> <dd><pre><code>const str = &#x27;&#x3C;path_to_url#x3E;; rel=&#x22;next&#x22;, &#x3C;path_to_url#x3E;; rel=&#x22;last&#x22;&#x27;; const ret = utils.parseLinks(str); ret.next.should.equal( &#x27;path_to_url#x27; ); ret.last.should.equal( &#x27;path_to_url#x27; );</code></pre></dd> </dl> </section> </div> <a href="path_to_url"><img style="position: absolute; top: 0; right: 0; border: 0;" src="path_to_url" alt="Fork me on GitHub"></a> <script src="path_to_url"></script> <script> $('code').each(function(){ $(this).html(highlight($(this).text())); }); function highlight(js) { return js .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/('.*?')/gm, '<span class="string">$1</span>') .replace(/(\d+\.\d+)/gm, '<span class="number">$1</span>') .replace(/(\d+)/gm, '<span class="number">$1</span>') .replace(/\bnew *(\w+)/gm, '<span class="keyword">new</span> <span class="init">$1</span>') .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '<span class="keyword">$1</span>') } </script> <script src="path_to_url"></script> <script> // Only use tocbot for main docs, not test docs if (document.querySelector('#superagent')) { tocbot.init({ // Where to render the table of contents. tocSelector: '#menu', // Where to grab the headings to build the table of contents. contentSelector: '#content', // Which headings to grab inside of the contentSelector element. headingSelector: 'h2', smoothScroll: false }); } </script> </body> </html> ```
/content/code_sandbox/node_modules/superagent/docs/test.html
html
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
50,283
```javascript 'use strict'; var test = require('tape'); var inspect = require('object-inspect'); var SaferBuffer = require('safer-buffer').Buffer; var forEach = require('for-each'); var utils = require('../lib/utils'); test('merge()', function (t) { t.deepEqual(utils.merge(null, true), [null, true], 'merges true into null'); t.deepEqual(utils.merge(null, [42]), [null, 42], 'merges null into an array'); t.deepEqual(utils.merge({ a: 'b' }, { a: 'c' }), { a: ['b', 'c'] }, 'merges two objects with the same key'); var oneMerged = utils.merge({ foo: 'bar' }, { foo: { first: '123' } }); t.deepEqual(oneMerged, { foo: ['bar', { first: '123' }] }, 'merges a standalone and an object into an array'); var twoMerged = utils.merge({ foo: ['bar', { first: '123' }] }, { foo: { second: '456' } }); t.deepEqual(twoMerged, { foo: { 0: 'bar', 1: { first: '123' }, second: '456' } }, 'merges a standalone and two objects into an array'); var sandwiched = utils.merge({ foo: ['bar', { first: '123', second: '456' }] }, { foo: 'baz' }); t.deepEqual(sandwiched, { foo: ['bar', { first: '123', second: '456' }, 'baz'] }, 'merges an object sandwiched by two standalones into an array'); var nestedArrays = utils.merge({ foo: ['baz'] }, { foo: ['bar', 'xyzzy'] }); t.deepEqual(nestedArrays, { foo: ['baz', 'bar', 'xyzzy'] }); var noOptionsNonObjectSource = utils.merge({ foo: 'baz' }, 'bar'); t.deepEqual(noOptionsNonObjectSource, { foo: 'baz', bar: true }); t.test( 'avoids invoking array setters unnecessarily', { skip: typeof Object.defineProperty !== 'function' }, function (st) { var setCount = 0; var getCount = 0; var observed = []; Object.defineProperty(observed, 0, { get: function () { getCount += 1; return { bar: 'baz' }; }, set: function () { setCount += 1; } }); utils.merge(observed, [null]); st.equal(setCount, 0); st.equal(getCount, 1); observed[0] = observed[0]; // eslint-disable-line no-self-assign st.equal(setCount, 1); st.equal(getCount, 2); st.end(); } ); t.end(); }); test('assign()', function (t) { var target = { a: 1, b: 2 }; var source = { b: 3, c: 4 }; var result = utils.assign(target, source); t.equal(result, target, 'returns the target'); t.deepEqual(target, { a: 1, b: 3, c: 4 }, 'target and source are merged'); t.deepEqual(source, { b: 3, c: 4 }, 'source is untouched'); t.end(); }); test('combine()', function (t) { t.test('both arrays', function (st) { var a = [1]; var b = [2]; var combined = utils.combine(a, b); st.deepEqual(a, [1], 'a is not mutated'); st.deepEqual(b, [2], 'b is not mutated'); st.notEqual(a, combined, 'a !== combined'); st.notEqual(b, combined, 'b !== combined'); st.deepEqual(combined, [1, 2], 'combined is a + b'); st.end(); }); t.test('one array, one non-array', function (st) { var aN = 1; var a = [aN]; var bN = 2; var b = [bN]; var combinedAnB = utils.combine(aN, b); st.deepEqual(b, [bN], 'b is not mutated'); st.notEqual(aN, combinedAnB, 'aN + b !== aN'); st.notEqual(a, combinedAnB, 'aN + b !== a'); st.notEqual(bN, combinedAnB, 'aN + b !== bN'); st.notEqual(b, combinedAnB, 'aN + b !== b'); st.deepEqual([1, 2], combinedAnB, 'first argument is array-wrapped when not an array'); var combinedABn = utils.combine(a, bN); st.deepEqual(a, [aN], 'a is not mutated'); st.notEqual(aN, combinedABn, 'a + bN !== aN'); st.notEqual(a, combinedABn, 'a + bN !== a'); st.notEqual(bN, combinedABn, 'a + bN !== bN'); st.notEqual(b, combinedABn, 'a + bN !== b'); st.deepEqual([1, 2], combinedABn, 'second argument is array-wrapped when not an array'); st.end(); }); t.test('neither is an array', function (st) { var combined = utils.combine(1, 2); st.notEqual(1, combined, '1 + 2 !== 1'); st.notEqual(2, combined, '1 + 2 !== 2'); st.deepEqual([1, 2], combined, 'both arguments are array-wrapped when not an array'); st.end(); }); t.end(); }); test('isBuffer()', function (t) { forEach([null, undefined, true, false, '', 'abc', 42, 0, NaN, {}, [], function () {}, /a/g], function (x) { t.equal(utils.isBuffer(x), false, inspect(x) + ' is not a buffer'); }); var fakeBuffer = { constructor: Buffer }; t.equal(utils.isBuffer(fakeBuffer), false, 'fake buffer is not a buffer'); var saferBuffer = SaferBuffer.from('abc'); t.equal(utils.isBuffer(saferBuffer), true, 'SaferBuffer instance is a buffer'); var buffer = Buffer.from && Buffer.alloc ? Buffer.from('abc') : new Buffer('abc'); t.equal(utils.isBuffer(buffer), true, 'real Buffer instance is a buffer'); t.end(); }); ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/test/utils.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,439
```javascript 'use strict'; var test = require('tape'); var qs = require('../'); var utils = require('../lib/utils'); var iconv = require('iconv-lite'); var SaferBuffer = require('safer-buffer').Buffer; var hasSymbols = require('has-symbols'); var hasBigInt = typeof BigInt === 'function'; test('stringify()', function (t) { t.test('stringifies a querystring object', function (st) { st.equal(qs.stringify({ a: 'b' }), 'a=b'); st.equal(qs.stringify({ a: 1 }), 'a=1'); st.equal(qs.stringify({ a: 1, b: 2 }), 'a=1&b=2'); st.equal(qs.stringify({ a: 'A_Z' }), 'a=A_Z'); st.equal(qs.stringify({ a: '' }), 'a=%E2%82%AC'); st.equal(qs.stringify({ a: '' }), 'a=%EE%80%80'); st.equal(qs.stringify({ a: '' }), 'a=%D7%90'); st.equal(qs.stringify({ a: '' }), 'a=%F0%90%90%B7'); st.end(); }); t.test('stringifies falsy values', function (st) { st.equal(qs.stringify(undefined), ''); st.equal(qs.stringify(null), ''); st.equal(qs.stringify(null, { strictNullHandling: true }), ''); st.equal(qs.stringify(false), ''); st.equal(qs.stringify(0), ''); st.end(); }); t.test('stringifies symbols', { skip: !hasSymbols() }, function (st) { st.equal(qs.stringify(Symbol.iterator), ''); st.equal(qs.stringify([Symbol.iterator]), '0=Symbol%28Symbol.iterator%29'); st.equal(qs.stringify({ a: Symbol.iterator }), 'a=Symbol%28Symbol.iterator%29'); st.equal( qs.stringify({ a: [Symbol.iterator] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=Symbol%28Symbol.iterator%29' ); st.end(); }); t.test('stringifies bigints', { skip: !hasBigInt }, function (st) { var three = BigInt(3); var encodeWithN = function (value, defaultEncoder, charset) { var result = defaultEncoder(value, defaultEncoder, charset); return typeof value === 'bigint' ? result + 'n' : result; }; st.equal(qs.stringify(three), ''); st.equal(qs.stringify([three]), '0=3'); st.equal(qs.stringify([three], { encoder: encodeWithN }), '0=3n'); st.equal(qs.stringify({ a: three }), 'a=3'); st.equal(qs.stringify({ a: three }, { encoder: encodeWithN }), 'a=3n'); st.equal( qs.stringify({ a: [three] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=3' ); st.equal( qs.stringify({ a: [three] }, { encodeValuesOnly: true, encoder: encodeWithN, arrayFormat: 'brackets' }), 'a[]=3n' ); st.end(); }); t.test('adds query prefix', function (st) { st.equal(qs.stringify({ a: 'b' }, { addQueryPrefix: true }), '?a=b'); st.end(); }); t.test('with query prefix, outputs blank string given an empty object', function (st) { st.equal(qs.stringify({}, { addQueryPrefix: true }), ''); st.end(); }); t.test('stringifies nested falsy values', function (st) { st.equal(qs.stringify({ a: { b: { c: null } } }), 'a%5Bb%5D%5Bc%5D='); st.equal(qs.stringify({ a: { b: { c: null } } }, { strictNullHandling: true }), 'a%5Bb%5D%5Bc%5D'); st.equal(qs.stringify({ a: { b: { c: false } } }), 'a%5Bb%5D%5Bc%5D=false'); st.end(); }); t.test('stringifies a nested object', function (st) { st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }), 'a%5Bb%5D%5Bc%5D%5Bd%5D=e'); st.end(); }); t.test('stringifies a nested object with dots notation', function (st) { st.equal(qs.stringify({ a: { b: 'c' } }, { allowDots: true }), 'a.b=c'); st.equal(qs.stringify({ a: { b: { c: { d: 'e' } } } }, { allowDots: true }), 'a.b.c.d=e'); st.end(); }); t.test('stringifies an array value', function (st) { st.equal( qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', 'indices => indices' ); st.equal( qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c&a%5B%5D=d', 'brackets => brackets' ); st.equal( qs.stringify({ a: ['b', 'c', 'd'] }, { arrayFormat: 'comma' }), 'a=b%2Cc%2Cd', 'comma => comma' ); st.equal( qs.stringify({ a: ['b', 'c', 'd'] }), 'a%5B0%5D=b&a%5B1%5D=c&a%5B2%5D=d', 'default => indices' ); st.end(); }); t.test('omits nulls when asked', function (st) { st.equal(qs.stringify({ a: 'b', c: null }, { skipNulls: true }), 'a=b'); st.end(); }); t.test('omits nested nulls when asked', function (st) { st.equal(qs.stringify({ a: { b: 'c', d: null } }, { skipNulls: true }), 'a%5Bb%5D=c'); st.end(); }); t.test('omits array indices when asked', function (st) { st.equal(qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }), 'a=b&a=c&a=d'); st.end(); }); t.test('stringifies an array value with one item vs multiple items', function (st) { st.test('non-array item', function (s2t) { s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a=c'); s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a=c'); s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); s2t.equal(qs.stringify({ a: 'c' }, { encodeValuesOnly: true }), 'a=c'); s2t.end(); }); st.test('array with a single item', function (s2t) { s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c'); s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c'); s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c'); s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true, arrayFormat: 'comma', commaRoundTrip: true }), 'a[]=c'); // so it parses back as an array s2t.equal(qs.stringify({ a: ['c'] }, { encodeValuesOnly: true }), 'a[0]=c'); s2t.end(); }); st.test('array with multiple items', function (s2t) { s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0]=c&a[1]=d'); s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[]=c&a[]=d'); s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a=c,d'); s2t.equal(qs.stringify({ a: ['c', 'd'] }, { encodeValuesOnly: true }), 'a[0]=c&a[1]=d'); s2t.end(); }); st.end(); }); t.test('stringifies a nested array value', function (st) { st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[b][0]=c&a[b][1]=d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[b][]=c&a[b][]=d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true, arrayFormat: 'comma' }), 'a[b]=c,d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { encodeValuesOnly: true }), 'a[b][0]=c&a[b][1]=d'); st.end(); }); t.test('stringifies a nested array value with dots notation', function (st) { st.equal( qs.stringify( { a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true, arrayFormat: 'indices' } ), 'a.b[0]=c&a.b[1]=d', 'indices: stringifies with dots + indices' ); st.equal( qs.stringify( { a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true, arrayFormat: 'brackets' } ), 'a.b[]=c&a.b[]=d', 'brackets: stringifies with dots + brackets' ); st.equal( qs.stringify( { a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true, arrayFormat: 'comma' } ), 'a.b=c,d', 'comma: stringifies with dots + comma' ); st.equal( qs.stringify( { a: { b: ['c', 'd'] } }, { allowDots: true, encodeValuesOnly: true } ), 'a.b[0]=c&a.b[1]=d', 'default: stringifies with dots + indices' ); st.end(); }); t.test('stringifies an object inside an array', function (st) { st.equal( qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'indices' }), 'a%5B0%5D%5Bb%5D=c', // a[0][b]=c 'indices => brackets' ); st.equal( qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), 'a%5B%5D%5Bb%5D=c', // a[][b]=c 'brackets => brackets' ); st.equal( qs.stringify({ a: [{ b: 'c' }] }), 'a%5B0%5D%5Bb%5D=c', 'default => indices' ); st.equal( qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'indices' }), 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', 'indices => indices' ); st.equal( qs.stringify({ a: [{ b: { c: [1] } }] }, { arrayFormat: 'brackets' }), 'a%5B%5D%5Bb%5D%5Bc%5D%5B%5D=1', 'brackets => brackets' ); st.equal( qs.stringify({ a: [{ b: { c: [1] } }] }), 'a%5B0%5D%5Bb%5D%5Bc%5D%5B0%5D=1', 'default => indices' ); st.end(); }); t.test('stringifies an array with mixed objects and primitives', function (st) { st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'indices' }), 'a[0][b]=1&a[1]=2&a[2]=3', 'indices => indices' ); st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'brackets' }), 'a[][b]=1&a[]=2&a[]=3', 'brackets => brackets' ); st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true, arrayFormat: 'comma' }), '???', 'brackets => brackets', { skip: 'TODO: figure out what this should do' } ); st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encodeValuesOnly: true }), 'a[0][b]=1&a[1]=2&a[2]=3', 'default => indices' ); st.end(); }); t.test('stringifies an object inside an array with dots notation', function (st) { st.equal( qs.stringify( { a: [{ b: 'c' }] }, { allowDots: true, encode: false, arrayFormat: 'indices' } ), 'a[0].b=c', 'indices => indices' ); st.equal( qs.stringify( { a: [{ b: 'c' }] }, { allowDots: true, encode: false, arrayFormat: 'brackets' } ), 'a[].b=c', 'brackets => brackets' ); st.equal( qs.stringify( { a: [{ b: 'c' }] }, { allowDots: true, encode: false } ), 'a[0].b=c', 'default => indices' ); st.equal( qs.stringify( { a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false, arrayFormat: 'indices' } ), 'a[0].b.c[0]=1', 'indices => indices' ); st.equal( qs.stringify( { a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false, arrayFormat: 'brackets' } ), 'a[].b.c[]=1', 'brackets => brackets' ); st.equal( qs.stringify( { a: [{ b: { c: [1] } }] }, { allowDots: true, encode: false } ), 'a[0].b.c[0]=1', 'default => indices' ); st.end(); }); t.test('does not omit object keys when indices = false', function (st) { st.equal(qs.stringify({ a: [{ b: 'c' }] }, { indices: false }), 'a%5Bb%5D=c'); st.end(); }); t.test('uses indices notation for arrays when indices=true', function (st) { st.equal(qs.stringify({ a: ['b', 'c'] }, { indices: true }), 'a%5B0%5D=b&a%5B1%5D=c'); st.end(); }); t.test('uses indices notation for arrays when no arrayFormat is specified', function (st) { st.equal(qs.stringify({ a: ['b', 'c'] }), 'a%5B0%5D=b&a%5B1%5D=c'); st.end(); }); t.test('uses indices notation for arrays when no arrayFormat=indices', function (st) { st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }), 'a%5B0%5D=b&a%5B1%5D=c'); st.end(); }); t.test('uses repeat notation for arrays when no arrayFormat=repeat', function (st) { st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }), 'a=b&a=c'); st.end(); }); t.test('uses brackets notation for arrays when no arrayFormat=brackets', function (st) { st.equal(qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }), 'a%5B%5D=b&a%5B%5D=c'); st.end(); }); t.test('stringifies a complicated object', function (st) { st.equal(qs.stringify({ a: { b: 'c', d: 'e' } }), 'a%5Bb%5D=c&a%5Bd%5D=e'); st.end(); }); t.test('stringifies an empty value', function (st) { st.equal(qs.stringify({ a: '' }), 'a='); st.equal(qs.stringify({ a: null }, { strictNullHandling: true }), 'a'); st.equal(qs.stringify({ a: '', b: '' }), 'a=&b='); st.equal(qs.stringify({ a: null, b: '' }, { strictNullHandling: true }), 'a&b='); st.equal(qs.stringify({ a: { b: '' } }), 'a%5Bb%5D='); st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: true }), 'a%5Bb%5D'); st.equal(qs.stringify({ a: { b: null } }, { strictNullHandling: false }), 'a%5Bb%5D='); st.end(); }); t.test('stringifies an empty array in different arrayFormat', function (st) { st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false }), 'b[0]=&c=c'); // arrayFormat default st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices' }), 'b[0]=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets' }), 'b[]=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat' }), 'b=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma' }), 'b=&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', commaRoundTrip: true }), 'b[]=&c=c'); // with strictNullHandling st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', strictNullHandling: true }), 'b[0]&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', strictNullHandling: true }), 'b[]&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', strictNullHandling: true }), 'b&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true }), 'b&c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', strictNullHandling: true, commaRoundTrip: true }), 'b[]&c=c'); // with skipNulls st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'indices', skipNulls: true }), 'c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'brackets', skipNulls: true }), 'c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'repeat', skipNulls: true }), 'c=c'); st.equal(qs.stringify({ a: [], b: [null], c: 'c' }, { encode: false, arrayFormat: 'comma', skipNulls: true }), 'c=c'); st.end(); }); t.test('stringifies a null object', { skip: !Object.create }, function (st) { var obj = Object.create(null); obj.a = 'b'; st.equal(qs.stringify(obj), 'a=b'); st.end(); }); t.test('returns an empty string for invalid input', function (st) { st.equal(qs.stringify(undefined), ''); st.equal(qs.stringify(false), ''); st.equal(qs.stringify(null), ''); st.equal(qs.stringify(''), ''); st.end(); }); t.test('stringifies an object with a null object as a child', { skip: !Object.create }, function (st) { var obj = { a: Object.create(null) }; obj.a.b = 'c'; st.equal(qs.stringify(obj), 'a%5Bb%5D=c'); st.end(); }); t.test('drops keys with a value of undefined', function (st) { st.equal(qs.stringify({ a: undefined }), ''); st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: true }), 'a%5Bc%5D'); st.equal(qs.stringify({ a: { b: undefined, c: null } }, { strictNullHandling: false }), 'a%5Bc%5D='); st.equal(qs.stringify({ a: { b: undefined, c: '' } }), 'a%5Bc%5D='); st.end(); }); t.test('url encodes values', function (st) { st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); st.end(); }); t.test('stringifies a date', function (st) { var now = new Date(); var str = 'a=' + encodeURIComponent(now.toISOString()); st.equal(qs.stringify({ a: now }), str); st.end(); }); t.test('stringifies the weird object from qs', function (st) { st.equal(qs.stringify({ 'my weird field': '~q1!2"\'w$5&7/z8)?' }), 'my%20weird%20field=~q1%212%22%27w%245%267%2Fz8%29%3F'); st.end(); }); t.test('skips properties that are part of the object prototype', function (st) { Object.prototype.crash = 'test'; st.equal(qs.stringify({ a: 'b' }), 'a=b'); st.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); delete Object.prototype.crash; st.end(); }); t.test('stringifies boolean values', function (st) { st.equal(qs.stringify({ a: true }), 'a=true'); st.equal(qs.stringify({ a: { b: true } }), 'a%5Bb%5D=true'); st.equal(qs.stringify({ b: false }), 'b=false'); st.equal(qs.stringify({ b: { c: false } }), 'b%5Bc%5D=false'); st.end(); }); t.test('stringifies buffer values', function (st) { st.equal(qs.stringify({ a: SaferBuffer.from('test') }), 'a=test'); st.equal(qs.stringify({ a: { b: SaferBuffer.from('test') } }), 'a%5Bb%5D=test'); st.end(); }); t.test('stringifies an object using an alternative delimiter', function (st) { st.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); st.end(); }); t.test('does not blow up when Buffer global is missing', function (st) { var tempBuffer = global.Buffer; delete global.Buffer; var result = qs.stringify({ a: 'b', c: 'd' }); global.Buffer = tempBuffer; st.equal(result, 'a=b&c=d'); st.end(); }); t.test('does not crash when parsing circular references', function (st) { var a = {}; a.b = a; st['throws']( function () { qs.stringify({ 'foo[bar]': 'baz', 'foo[baz]': a }); }, /RangeError: Cyclic object value/, 'cyclic values throw' ); var circular = { a: 'value' }; circular.a = circular; st['throws']( function () { qs.stringify(circular); }, /RangeError: Cyclic object value/, 'cyclic values throw' ); var arr = ['a']; st.doesNotThrow( function () { qs.stringify({ x: arr, y: arr }); }, 'non-cyclic values do not throw' ); st.end(); }); t.test('non-circular duplicated references can still work', function (st) { var hourOfDay = { 'function': 'hour_of_day' }; var p1 = { 'function': 'gte', arguments: [hourOfDay, 0] }; var p2 = { 'function': 'lte', arguments: [hourOfDay, 23] }; st.equal( qs.stringify({ filters: { $and: [p1, p2] } }, { encodeValuesOnly: true }), 'filters[$and][0][function]=gte&filters[$and][0][arguments][0][function]=hour_of_day&filters[$and][0][arguments][1]=0&filters[$and][1][function]=lte&filters[$and][1][arguments][0][function]=hour_of_day&filters[$and][1][arguments][1]=23' ); st.end(); }); t.test('selects properties when filter=array', function (st) { st.equal(qs.stringify({ a: 'b' }, { filter: ['a'] }), 'a=b'); st.equal(qs.stringify({ a: 1 }, { filter: [] }), ''); st.equal( qs.stringify( { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2], arrayFormat: 'indices' } ), 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', 'indices => indices' ); st.equal( qs.stringify( { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2], arrayFormat: 'brackets' } ), 'a%5Bb%5D%5B%5D=1&a%5Bb%5D%5B%5D=3', 'brackets => brackets' ); st.equal( qs.stringify( { a: { b: [1, 2, 3, 4], c: 'd' }, c: 'f' }, { filter: ['a', 'b', 0, 2] } ), 'a%5Bb%5D%5B0%5D=1&a%5Bb%5D%5B2%5D=3', 'default => indices' ); st.end(); }); t.test('supports custom representations when filter=function', function (st) { var calls = 0; var obj = { a: 'b', c: 'd', e: { f: new Date(1257894000000) } }; var filterFunc = function (prefix, value) { calls += 1; if (calls === 1) { st.equal(prefix, '', 'prefix is empty'); st.equal(value, obj); } else if (prefix === 'c') { return void 0; } else if (value instanceof Date) { st.equal(prefix, 'e[f]'); return value.getTime(); } return value; }; st.equal(qs.stringify(obj, { filter: filterFunc }), 'a=b&e%5Bf%5D=1257894000000'); st.equal(calls, 5); st.end(); }); t.test('can disable uri encoding', function (st) { st.equal(qs.stringify({ a: 'b' }, { encode: false }), 'a=b'); st.equal(qs.stringify({ a: { b: 'c' } }, { encode: false }), 'a[b]=c'); st.equal(qs.stringify({ a: 'b', c: null }, { strictNullHandling: true, encode: false }), 'a=b&c'); st.end(); }); t.test('can sort the keys', function (st) { var sort = function (a, b) { return a.localeCompare(b); }; st.equal(qs.stringify({ a: 'c', z: 'y', b: 'f' }, { sort: sort }), 'a=c&b=f&z=y'); st.equal(qs.stringify({ a: 'c', z: { j: 'a', i: 'b' }, b: 'f' }, { sort: sort }), 'a=c&b=f&z%5Bi%5D=b&z%5Bj%5D=a'); st.end(); }); t.test('can sort the keys at depth 3 or more too', function (st) { var sort = function (a, b) { return a.localeCompare(b); }; st.equal( qs.stringify( { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, { sort: sort, encode: false } ), 'a=a&b=b&z[zi][zia]=zia&z[zi][zib]=zib&z[zj][zja]=zja&z[zj][zjb]=zjb' ); st.equal( qs.stringify( { a: 'a', z: { zj: { zjb: 'zjb', zja: 'zja' }, zi: { zib: 'zib', zia: 'zia' } }, b: 'b' }, { sort: null, encode: false } ), 'a=a&z[zj][zjb]=zjb&z[zj][zja]=zja&z[zi][zib]=zib&z[zi][zia]=zia&b=b' ); st.end(); }); t.test('can stringify with custom encoding', function (st) { st.equal(qs.stringify({ : '', '': '' }, { encoder: function (str) { if (str.length === 0) { return ''; } var buf = iconv.encode(str, 'shiftjis'); var result = []; for (var i = 0; i < buf.length; ++i) { result.push(buf.readUInt8(i).toString(16)); } return '%' + result.join('%'); } }), '%8c%a7=%91%e5%8d%e3%95%7b&='); st.end(); }); t.test('receives the default encoder as a second argument', function (st) { st.plan(2); qs.stringify({ a: 1 }, { encoder: function (str, defaultEncoder) { st.equal(defaultEncoder, utils.encode); } }); st.end(); }); t.test('throws error with wrong encoder', function (st) { st['throws'](function () { qs.stringify({}, { encoder: 'string' }); }, new TypeError('Encoder has to be a function.')); st.end(); }); t.test('can use custom encoder for a buffer object', { skip: typeof Buffer === 'undefined' }, function (st) { st.equal(qs.stringify({ a: SaferBuffer.from([1]) }, { encoder: function (buffer) { if (typeof buffer === 'string') { return buffer; } return String.fromCharCode(buffer.readUInt8(0) + 97); } }), 'a=b'); st.equal(qs.stringify({ a: SaferBuffer.from('a b') }, { encoder: function (buffer) { return buffer; } }), 'a=a b'); st.end(); }); t.test('serializeDate option', function (st) { var date = new Date(); st.equal( qs.stringify({ a: date }), 'a=' + date.toISOString().replace(/:/g, '%3A'), 'default is toISOString' ); var mutatedDate = new Date(); mutatedDate.toISOString = function () { throw new SyntaxError(); }; st['throws'](function () { mutatedDate.toISOString(); }, SyntaxError); st.equal( qs.stringify({ a: mutatedDate }), 'a=' + Date.prototype.toISOString.call(mutatedDate).replace(/:/g, '%3A'), 'toISOString works even when method is not locally present' ); var specificDate = new Date(6); st.equal( qs.stringify( { a: specificDate }, { serializeDate: function (d) { return d.getTime() * 7; } } ), 'a=42', 'custom serializeDate function called' ); st.equal( qs.stringify( { a: [date] }, { serializeDate: function (d) { return d.getTime(); }, arrayFormat: 'comma' } ), 'a=' + date.getTime(), 'works with arrayFormat comma' ); st.equal( qs.stringify( { a: [date] }, { serializeDate: function (d) { return d.getTime(); }, arrayFormat: 'comma', commaRoundTrip: true } ), 'a%5B%5D=' + date.getTime(), 'works with arrayFormat comma' ); st.end(); }); t.test('RFC 1738 serialization', function (st) { st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC1738 }), 'a=b+c'); st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC1738 }), 'a+b=c+d'); st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC1738 }), 'a+b=a+b'); st.equal(qs.stringify({ 'foo(ref)': 'bar' }, { format: qs.formats.RFC1738 }), 'foo(ref)=bar'); st.end(); }); t.test('RFC 3986 spaces serialization', function (st) { st.equal(qs.stringify({ a: 'b c' }, { format: qs.formats.RFC3986 }), 'a=b%20c'); st.equal(qs.stringify({ 'a b': 'c d' }, { format: qs.formats.RFC3986 }), 'a%20b=c%20d'); st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }, { format: qs.formats.RFC3986 }), 'a%20b=a%20b'); st.end(); }); t.test('Backward compatibility to RFC 3986', function (st) { st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); st.equal(qs.stringify({ 'a b': SaferBuffer.from('a b') }), 'a%20b=a%20b'); st.end(); }); t.test('Edge cases and unknown formats', function (st) { ['UFO1234', false, 1234, null, {}, []].forEach(function (format) { st['throws']( function () { qs.stringify({ a: 'b c' }, { format: format }); }, new TypeError('Unknown format option provided.') ); }); st.end(); }); t.test('encodeValuesOnly', function (st) { st.equal( qs.stringify( { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, { encodeValuesOnly: true } ), 'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h' ); st.equal( qs.stringify( { a: 'b', c: ['d', 'e'], f: [['g'], ['h']] } ), 'a=b&c%5B0%5D=d&c%5B1%5D=e&f%5B0%5D%5B0%5D=g&f%5B1%5D%5B0%5D=h' ); st.end(); }); t.test('encodeValuesOnly - strictNullHandling', function (st) { st.equal( qs.stringify( { a: { b: null } }, { encodeValuesOnly: true, strictNullHandling: true } ), 'a[b]' ); st.end(); }); t.test('throws if an invalid charset is specified', function (st) { st['throws'](function () { qs.stringify({ a: 'b' }, { charset: 'foobar' }); }, new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined')); st.end(); }); t.test('respects a charset of iso-8859-1', function (st) { st.equal(qs.stringify({ : '' }, { charset: 'iso-8859-1' }), '%E6=%E6'); st.end(); }); t.test('encodes unrepresentable chars as numeric entities in iso-8859-1 mode', function (st) { st.equal(qs.stringify({ a: '' }, { charset: 'iso-8859-1' }), 'a=%26%239786%3B'); st.end(); }); t.test('respects an explicit charset of utf-8 (the default)', function (st) { st.equal(qs.stringify({ a: '' }, { charset: 'utf-8' }), 'a=%C3%A6'); st.end(); }); t.test('adds the right sentinel when instructed to and the charset is utf-8', function (st) { st.equal(qs.stringify({ a: '' }, { charsetSentinel: true, charset: 'utf-8' }), 'utf8=%E2%9C%93&a=%C3%A6'); st.end(); }); t.test('adds the right sentinel when instructed to and the charset is iso-8859-1', function (st) { st.equal(qs.stringify({ a: '' }, { charsetSentinel: true, charset: 'iso-8859-1' }), 'utf8=%26%2310003%3B&a=%E6'); st.end(); }); t.test('does not mutate the options argument', function (st) { var options = {}; qs.stringify({}, options); st.deepEqual(options, {}); st.end(); }); t.test('strictNullHandling works with custom filter', function (st) { var filter = function (prefix, value) { return value; }; var options = { strictNullHandling: true, filter: filter }; st.equal(qs.stringify({ key: null }, options), 'key'); st.end(); }); t.test('strictNullHandling works with null serializeDate', function (st) { var serializeDate = function () { return null; }; var options = { strictNullHandling: true, serializeDate: serializeDate }; var date = new Date(); st.equal(qs.stringify({ key: date }, options), 'key'); st.end(); }); t.test('allows for encoding keys and values differently', function (st) { var encoder = function (str, defaultEncoder, charset, type) { if (type === 'key') { return defaultEncoder(str, defaultEncoder, charset, type).toLowerCase(); } if (type === 'value') { return defaultEncoder(str, defaultEncoder, charset, type).toUpperCase(); } throw 'this should never happen! type: ' + type; }; st.deepEqual(qs.stringify({ KeY: 'vAlUe' }, { encoder: encoder }), 'key=VALUE'); st.end(); }); t.test('objects inside arrays', function (st) { var obj = { a: { b: { c: 'd', e: 'f' } } }; var withArray = { a: { b: [{ c: 'd', e: 'f' }] } }; st.equal(qs.stringify(obj, { encode: false }), 'a[b][c]=d&a[b][e]=f', 'no array, no arrayFormat'); st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'bracket' }), 'a[b][c]=d&a[b][e]=f', 'no array, bracket'); st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'indices' }), 'a[b][c]=d&a[b][e]=f', 'no array, indices'); st.equal(qs.stringify(obj, { encode: false, arrayFormat: 'comma' }), 'a[b][c]=d&a[b][e]=f', 'no array, comma'); st.equal(qs.stringify(withArray, { encode: false }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, no arrayFormat'); st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'bracket' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, bracket'); st.equal(qs.stringify(withArray, { encode: false, arrayFormat: 'indices' }), 'a[b][0][c]=d&a[b][0][e]=f', 'array, indices'); st.equal( qs.stringify(withArray, { encode: false, arrayFormat: 'comma' }), '???', 'array, comma', { skip: 'TODO: figure out what this should do' } ); st.end(); }); t.test('stringifies sparse arrays', function (st) { /* eslint no-sparse-arrays: 0 */ st.equal(qs.stringify({ a: [, '2', , , '1'] }, { encodeValuesOnly: true }), 'a[1]=2&a[4]=1'); st.equal(qs.stringify({ a: [, { b: [, , { c: '1' }] }] }, { encodeValuesOnly: true }), 'a[1][b][2][c]=1'); st.equal(qs.stringify({ a: [, [, , [, , , { c: '1' }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c]=1'); st.equal(qs.stringify({ a: [, [, , [, , , { c: [, '1'] }]]] }, { encodeValuesOnly: true }), 'a[1][2][3][c][1]=1'); st.end(); }); t.end(); }); ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/test/stringify.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
10,194
```javascript 'use strict'; const codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error } function getMessage (arg1, arg2, arg3) { if (typeof message === 'string') { return message } else { return message(arg1, arg2, arg3) } } class NodeError extends Base { constructor (arg1, arg2, arg3) { super(getMessage(arg1, arg2, arg3)); } } NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // path_to_url function oneOf(expected, thing) { if (Array.isArray(expected)) { const len = expected.length; expected = expected.map((i) => String(i)); if (len > 2) { return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1]; } else if (len === 2) { return `one of ${thing} ${expected[0]} or ${expected[1]}`; } else { return `of ${thing} ${expected[0]}`; } } else { return `of ${thing} ${String(expected)}`; } } // path_to_url function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // path_to_url function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // path_to_url function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"' }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' let determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } let msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; } else { const type = includes(name, '.') ? 'property' : 'argument'; msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; } msg += `. Received type ${typeof actual}`; return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented' }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/errors.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
905
```javascript 'use strict'; function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var codes = {}; function createErrorType(code, message, Base) { if (!Base) { Base = Error; } function getMessage(arg1, arg2, arg3) { if (typeof message === 'string') { return message; } else { return message(arg1, arg2, arg3); } } var NodeError = /*#__PURE__*/ function (_Base) { _inheritsLoose(NodeError, _Base); function NodeError(arg1, arg2, arg3) { return _Base.call(this, getMessage(arg1, arg2, arg3)) || this; } return NodeError; }(Base); NodeError.prototype.name = Base.name; NodeError.prototype.code = code; codes[code] = NodeError; } // path_to_url function oneOf(expected, thing) { if (Array.isArray(expected)) { var len = expected.length; expected = expected.map(function (i) { return String(i); }); if (len > 2) { return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1]; } else if (len === 2) { return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]); } else { return "of ".concat(thing, " ").concat(expected[0]); } } else { return "of ".concat(thing, " ").concat(String(expected)); } } // path_to_url function startsWith(str, search, pos) { return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; } // path_to_url function endsWith(str, search, this_len) { if (this_len === undefined || this_len > str.length) { this_len = str.length; } return str.substring(this_len - search.length, this_len) === search; } // path_to_url function includes(str, search, start) { if (typeof start !== 'number') { start = 0; } if (start + search.length > str.length) { return false; } else { return str.indexOf(search, start) !== -1; } } createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { return 'The value "' + value + '" is invalid for option "' + name + '"'; }, TypeError); createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { // determiner: 'must be' or 'must not be' var determiner; if (typeof expected === 'string' && startsWith(expected, 'not ')) { determiner = 'must not be'; expected = expected.replace(/^not /, ''); } else { determiner = 'must be'; } var msg; if (endsWith(name, ' argument')) { // For cases like 'first argument' msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } else { var type = includes(name, '.') ? 'property' : 'argument'; msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type')); } msg += ". Received type ".concat(typeof actual); return msg; }, TypeError); createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { return 'The ' + name + ' method is not implemented'; }); createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); createErrorType('ERR_STREAM_DESTROYED', function (name) { return 'Cannot call ' + name + ' after a stream was destroyed'; }); createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { return 'Unknown encoding: ' + arg; }, TypeError); createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); module.exports.codes = codes; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/errors-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,006
```javascript exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js'); ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/readable-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
103
```javascript 'use strict' var experimentalWarnings = new Set(); function emitExperimentalWarning(feature) { if (experimentalWarnings.has(feature)) return; var msg = feature + ' is an experimental feature. This feature could ' + 'change at any time'; experimentalWarnings.add(feature); process.emitWarning(msg, 'ExperimentalWarning'); } function noop() {} module.exports.emitExperimentalWarning = process.emitWarning ? emitExperimentalWarning : noop; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/experimentalWarning.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
93
```javascript var Stream = require('stream'); if (process.env.READABLE_STREAM === 'disable' && Stream) { module.exports = Stream.Readable; Object.assign(module.exports, Stream); module.exports.Stream = Stream; } else { exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = Stream || exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); exports.finished = require('./lib/internal/streams/end-of-stream.js'); exports.pipeline = require('./lib/internal/streams/pipeline.js'); } ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/readable.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
163
```javascript // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); require('inherits')(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/_stream_passthrough.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
326
```javascript // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; module.exports = Writable; /* <replacement> */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* </replacement> */ /*<replacement>*/ var Duplex; /*</replacement>*/ Writable.WritableState = WritableState; /*<replacement>*/ var internalUtil = { deprecate: require('util-deprecate') }; /*</replacement>*/ /*<replacement>*/ var Stream = require('./internal/streams/stream'); /*</replacement>*/ var Buffer = require('buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } var destroyImpl = require('./internal/streams/destroy'); var _require = require('./internal/streams/state'), getHighWaterMark = _require.getHighWaterMark; var _require$codes = require('../errors').codes, ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED, ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES, ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END, ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING; var errorOrDestroy = destroyImpl.errorOrDestroy; require('inherits')(Writable, Stream); function nop() {} function WritableState(options, stream, isDuplex) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // Duplex streams are both readable and writable, but share // the same options object. // However, some cases require setting options to different // values for the readable and the writable sides of the duplex stream, // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true. this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end') this.autoDestroy = !!options.autoDestroy; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function writableStateBufferGetter() { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function value(object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function realHasInstance(object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. // Checking for a Stream.Duplex instance is faster here instead of inside // the WritableState constructor, at least with V8 6.5 var isDuplex = this instanceof Duplex; if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options); this._writableState = new WritableState(options, this, isDuplex); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb errorOrDestroy(stream, er); process.nextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var er; if (chunk === null) { er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk); } if (er) { errorOrDestroy(stream, er); process.nextTick(cb, er); return false; } return true; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = !state.objectMode && _isUint8Array(chunk); if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { this._writableState.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; Object.defineProperty(Writable.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack process.nextTick(cb, er); // this can emit finish, and it will always happen // after error process.nextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; errorOrDestroy(stream, er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK(); onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state) || stream.destroyed; if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { process.nextTick(afterWrite, stream, state, finished, cb); } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } state.bufferedRequestCount = 0; } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending) endWritable(this, state, cb); return this; }; Object.defineProperty(Writable.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { errorOrDestroy(stream, err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function' && !state.destroyed) { state.pendingcb++; state.finalCalled = true; process.nextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); if (state.autoDestroy) { // In case of duplex streams we need a way to detect // if the readable side is ready for autoDestroy as well var rState = stream._readableState; if (!rState || rState.autoDestroy && rState.endEmitted) { stream.destroy(); } } } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) process.nextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } // reuse the free corkReq. state.corkedRequestsFree.next = corkReq; } Object.defineProperty(Writable.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { cb(err); }; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/_stream_writable.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
5,347
```javascript (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Qs = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){ 'use strict'; var replace = String.prototype.replace; var percentTwenties = /%20/g; var Format = { RFC1738: 'RFC1738', RFC3986: 'RFC3986' }; module.exports = { 'default': Format.RFC3986, formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return String(value); } }, RFC1738: Format.RFC1738, RFC3986: Format.RFC3986 }; },{}],2:[function(require,module,exports){ 'use strict'; var stringify = require('./stringify'); var parse = require('./parse'); var formats = require('./formats'); module.exports = { formats: formats, parse: parse, stringify: stringify }; },{"./formats":1,"./parse":3,"./stringify":4}],3:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var defaults = { allowDots: false, allowPrototypes: false, allowSparse: false, arrayLimit: 20, charset: 'utf-8', charsetSentinel: false, comma: false, decoder: utils.decode, delimiter: '&', depth: 5, ignoreQueryPrefix: false, interpretNumericEntities: false, parameterLimit: 1000, parseArrays: true, plainObjects: false, strictNullHandling: false }; var interpretNumericEntities = function (str) { return str.replace(/&#(\d+);/g, function ($0, numberStr) { return String.fromCharCode(parseInt(numberStr, 10)); }); }; var parseArrayValue = function (val, options) { if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { return val.split(','); } return val; }; // This is what browsers will submit when the character occurs in an // application/x-www-form-urlencoded body and the encoding of the page containing // the form is iso-8859-1, or when the submitted form has an accept-charset // attribute of iso-8859-1. Presumably also with other charsets that do not contain // the character, such as us-ascii. var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('&#10003;') // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('') var parseValues = function parseQueryStringValues(str, options) { var obj = {}; var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; var limit = options.parameterLimit === Infinity ? undefined : options.parameterLimit; var parts = cleanStr.split(options.delimiter, limit); var skipIndex = -1; // Keep track of where the utf8 sentinel was found var i; var charset = options.charset; if (options.charsetSentinel) { for (i = 0; i < parts.length; ++i) { if (parts[i].indexOf('utf8=') === 0) { if (parts[i] === charsetSentinel) { charset = 'utf-8'; } else if (parts[i] === isoSentinel) { charset = 'iso-8859-1'; } skipIndex = i; i = parts.length; // The eslint settings do not allow break; } } } for (i = 0; i < parts.length; ++i) { if (i === skipIndex) { continue; } var part = parts[i]; var bracketEqualsPos = part.indexOf(']='); var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; var key, val; if (pos === -1) { key = options.decoder(part, defaults.decoder, charset, 'key'); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); val = utils.maybeMap( parseArrayValue(part.slice(pos + 1), options), function (encodedVal) { return options.decoder(encodedVal, defaults.decoder, charset, 'value'); } ); } if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { val = interpretNumericEntities(val); } if (part.indexOf('[]=') > -1) { val = isArray(val) ? [val] : val; } if (has.call(obj, key)) { obj[key] = utils.combine(obj[key], val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options, valuesParsed) { var leaf = valuesParsed ? val : parseArrayValue(val, options); for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]' && options.parseArrays) { obj = [].concat(leaf); } else { obj = options.plainObjects ? Object.create(null) : {}; var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; var index = parseInt(cleanRoot, 10); if (!options.parseArrays && cleanRoot === '') { obj = { 0: leaf }; } else if ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else if (cleanRoot !== '__proto__') { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { if (!givenKey) { return; } // Transform dot notation to bracket notation var key = options.allowDots ? givenKey.replace(/\.([^.[]+)/g, '[$1]') : givenKey; // The regex chunks var brackets = /(\[[^[\]]*])/; var child = /(\[[^[\]]*])/g; // Get the parent var segment = options.depth > 0 && brackets.exec(key); var parent = segment ? key.slice(0, segment.index) : key; // Stash the parent if it exists var keys = []; if (parent) { // If we aren't using plain objects, optionally prefix keys that would overwrite object prototype properties if (!options.plainObjects && has.call(Object.prototype, parent)) { if (!options.allowPrototypes) { return; } } keys.push(parent); } // Loop through children appending to the array until we hit depth var i = 0; while (options.depth > 0 && (segment = child.exec(key)) !== null && i < options.depth) { i += 1; if (!options.plainObjects && has.call(Object.prototype, segment[1].slice(1, -1))) { if (!options.allowPrototypes) { return; } } keys.push(segment[1]); } // If there's a remainder, just add whatever is left if (segment) { keys.push('[' + key.slice(segment.index) + ']'); } return parseObject(keys, val, options, valuesParsed); }; var normalizeParseOptions = function normalizeParseOptions(opts) { if (!opts) { return defaults; } if (opts.decoder !== null && opts.decoder !== undefined && typeof opts.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; return { allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, // eslint-disable-next-line no-implicit-coercion, no-extra-parens depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, ignoreQueryPrefix: opts.ignoreQueryPrefix === true, interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, parseArrays: opts.parseArrays !== false, plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (str, opts) { var options = normalizeParseOptions(opts); if (str === '' || str === null || typeof str === 'undefined') { return options.plainObjects ? Object.create(null) : {}; } var tempObj = typeof str === 'string' ? parseValues(str, options) : str; var obj = options.plainObjects ? Object.create(null) : {}; // Iterate over the keys and setup the new object var keys = Object.keys(tempObj); for (var i = 0; i < keys.length; ++i) { var key = keys[i]; var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); obj = utils.merge(obj, newObj, options); } if (options.allowSparse === true) { return obj; } return utils.compact(obj); }; },{"./utils":5}],4:[function(require,module,exports){ 'use strict'; var getSideChannel = require('side-channel'); var utils = require('./utils'); var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var arrayPrefixGenerators = { brackets: function brackets(prefix) { return prefix + '[]'; }, comma: 'comma', indices: function indices(prefix, key) { return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { return prefix; } }; var isArray = Array.isArray; var split = String.prototype.split; var push = Array.prototype.push; var pushToArray = function (arr, valueOrArray) { push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); }; var toISO = Date.prototype.toISOString; var defaultFormat = formats['default']; var defaults = { addQueryPrefix: false, allowDots: false, charset: 'utf-8', charsetSentinel: false, delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, format: defaultFormat, formatter: formats.formatters[defaultFormat], // deprecated indices: false, serializeDate: function serializeDate(date) { return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var isNonNullishPrimitive = function isNonNullishPrimitive(v) { return typeof v === 'string' || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'symbol' || typeof v === 'bigint'; }; var sentinel = {}; var stringify = function stringify( object, prefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel ) { var obj = object; var tmpSc = sideChannel; var step = 0; var findFlag = false; while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { // Where object last appeared in the ref tree var pos = tmpSc.get(object); step += 1; if (typeof pos !== 'undefined') { if (pos === step) { throw new RangeError('Cyclic object value'); } else { findFlag = true; // Break while } } if (typeof tmpSc.get(sentinel) === 'undefined') { step = 0; } } if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (generateArrayPrefix === 'comma' && isArray(obj)) { obj = utils.maybeMap(obj, function (value) { if (value instanceof Date) { return serializeDate(value); } return value; }); } if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix; } obj = ''; } if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); if (generateArrayPrefix === 'comma' && encodeValuesOnly) { var valuesArray = split.call(String(obj), ','); var valuesJoined = ''; for (var i = 0; i < valuesArray.length; ++i) { valuesJoined += (i === 0 ? '' : ',') + formatter(encoder(valuesArray[i], defaults.encoder, charset, 'value', format)); } return [formatter(keyValue) + (commaRoundTrip && isArray(obj) && valuesArray.length === 1 ? '[]' : '') + '=' + valuesJoined]; } return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (generateArrayPrefix === 'comma' && isArray(obj)) { // we need to join elements in objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; } else if (isArray(filter)) { objKeys = filter; } else { var keys = Object.keys(obj); objKeys = sort ? keys.sort(sort) : keys; } var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? prefix + '[]' : prefix; for (var j = 0; j < objKeys.length; ++j) { var key = objKeys[j]; var value = typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; if (skipNulls && value === null) { continue; } var keyPrefix = isArray(obj) ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, key) : adjustedPrefix : adjustedPrefix + (allowDots ? '.' + key : '[' + key + ']'); sideChannel.set(object, step); var valueSideChannel = getSideChannel(); valueSideChannel.set(sentinel, sideChannel); pushToArray(values, stringify( value, keyPrefix, generateArrayPrefix, commaRoundTrip, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel )); } return values; }; var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { if (!opts) { return defaults; } if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var charset = opts.charset || defaults.charset; if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); } var format = formats['default']; if (typeof opts.format !== 'undefined') { if (!has.call(formats.formatters, opts.format)) { throw new TypeError('Unknown format option provided.'); } format = opts.format; } var formatter = formats.formatters[format]; var filter = defaults.filter; if (typeof opts.filter === 'function' || isArray(opts.filter)) { filter = opts.filter; } return { addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, allowDots: typeof opts.allowDots === 'undefined' ? defaults.allowDots : !!opts.allowDots, charset: charset, charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, filter: filter, format: format, formatter: formatter, serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, sort: typeof opts.sort === 'function' ? opts.sort : null, strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling }; }; module.exports = function (object, opts) { var obj = object; var options = normalizeStringifyOptions(opts); var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (opts && opts.arrayFormat in arrayPrefixGenerators) { arrayFormat = opts.arrayFormat; } else if (opts && 'indices' in opts) { arrayFormat = opts.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (opts && 'commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); } var commaRoundTrip = generateArrayPrefix === 'comma' && opts && opts.commaRoundTrip; if (!objKeys) { objKeys = Object.keys(obj); } if (options.sort) { objKeys.sort(options.sort); } var sideChannel = getSideChannel(); for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (options.skipNulls && obj[key] === null) { continue; } pushToArray(keys, stringify( obj[key], key, generateArrayPrefix, commaRoundTrip, options.strictNullHandling, options.skipNulls, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel )); } var joined = keys.join(options.delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; if (options.charsetSentinel) { if (options.charset === 'iso-8859-1') { // encodeURIComponent('&#10003;'), the "numeric entity" representation of a checkmark prefix += 'utf8=%26%2310003%3B&'; } else { // encodeURIComponent('') prefix += 'utf8=%E2%9C%93&'; } } return joined.length > 0 ? prefix + joined : ''; }; },{"./formats":1,"./utils":5,"side-channel":16}],5:[function(require,module,exports){ 'use strict'; var formats = require('./formats'); var has = Object.prototype.hasOwnProperty; var isArray = Array.isArray; var hexTable = (function () { var array = []; for (var i = 0; i < 256; ++i) { array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); } return array; }()); var compactQueue = function compactQueue(queue) { while (queue.length > 1) { var item = queue.pop(); var obj = item.obj[item.prop]; if (isArray(obj)) { var compacted = []; for (var j = 0; j < obj.length; ++j) { if (typeof obj[j] !== 'undefined') { compacted.push(obj[j]); } } item.obj[item.prop] = compacted; } } }; var arrayToObject = function arrayToObject(source, options) { var obj = options && options.plainObjects ? Object.create(null) : {}; for (var i = 0; i < source.length; ++i) { if (typeof source[i] !== 'undefined') { obj[i] = source[i]; } } return obj; }; var merge = function merge(target, source, options) { /* eslint no-param-reassign: 0 */ if (!source) { return target; } if (typeof source !== 'object') { if (isArray(target)) { target.push(source); } else if (target && typeof target === 'object') { if ((options && (options.plainObjects || options.allowPrototypes)) || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (!target || typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (isArray(target) && !isArray(source)) { mergeTarget = arrayToObject(target, options); } if (isArray(target) && isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { var targetItem = target[i]; if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { target[i] = merge(targetItem, item, options); } else { target.push(item); } } else { target[i] = item; } }); return target; } return Object.keys(source).reduce(function (acc, key) { var value = source[key]; if (has.call(acc, key)) { acc[key] = merge(acc[key], value, options); } else { acc[key] = value; } return acc; }, mergeTarget); }; var assign = function assignSingleSource(target, source) { return Object.keys(source).reduce(function (acc, key) { acc[key] = source[key]; return acc; }, target); }; var decode = function (str, decoder, charset) { var strWithoutPlus = str.replace(/\+/g, ' '); if (charset === 'iso-8859-1') { // unescape never throws, no try...catch needed: return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); } // utf-8 try { return decodeURIComponent(strWithoutPlus); } catch (e) { return strWithoutPlus; } }; var encode = function encode(str, defaultEncoder, charset, kind, format) { // This code was originally written by Brian White (mscdex) for the io.js core querystring library. // It has been adapted here for stricter adherence to RFC 3986 if (str.length === 0) { return str; } var string = str; if (typeof str === 'symbol') { string = Symbol.prototype.toString.call(str); } else if (typeof str !== 'string') { string = String(str); } if (charset === 'iso-8859-1') { return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; }); } var out = ''; for (var i = 0; i < string.length; ++i) { var c = string.charCodeAt(i); if ( c === 0x2D // - || c === 0x2E // . || c === 0x5F // _ || c === 0x7E // ~ || (c >= 0x30 && c <= 0x39) // 0-9 || (c >= 0x41 && c <= 0x5A) // a-z || (c >= 0x61 && c <= 0x7A) // A-Z || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) ) { out += string.charAt(i); continue; } if (c < 0x80) { out = out + hexTable[c]; continue; } if (c < 0x800) { out = out + (hexTable[0xC0 | (c >> 6)] + hexTable[0x80 | (c & 0x3F)]); continue; } if (c < 0xD800 || c >= 0xE000) { out = out + (hexTable[0xE0 | (c >> 12)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]); continue; } i += 1; c = 0x10000 + (((c & 0x3FF) << 10) | (string.charCodeAt(i) & 0x3FF)); /* eslint operator-linebreak: [2, "before"] */ out += hexTable[0xF0 | (c >> 18)] + hexTable[0x80 | ((c >> 12) & 0x3F)] + hexTable[0x80 | ((c >> 6) & 0x3F)] + hexTable[0x80 | (c & 0x3F)]; } return out; }; var compact = function compact(value) { var queue = [{ obj: { o: value }, prop: 'o' }]; var refs = []; for (var i = 0; i < queue.length; ++i) { var item = queue[i]; var obj = item.obj[item.prop]; var keys = Object.keys(obj); for (var j = 0; j < keys.length; ++j) { var key = keys[j]; var val = obj[key]; if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { queue.push({ obj: obj, prop: key }); refs.push(val); } } } compactQueue(queue); return value; }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (!obj || typeof obj !== 'object') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; var combine = function combine(a, b) { return [].concat(a, b); }; var maybeMap = function maybeMap(val, fn) { if (isArray(val)) { var mapped = []; for (var i = 0; i < val.length; i += 1) { mapped.push(fn(val[i])); } return mapped; } return fn(val); }; module.exports = { arrayToObject: arrayToObject, assign: assign, combine: combine, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, maybeMap: maybeMap, merge: merge }; },{"./formats":1}],6:[function(require,module,exports){ },{}],7:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); var callBind = require('./'); var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); module.exports = function callBoundIntrinsic(name, allowMissing) { var intrinsic = GetIntrinsic(name, !!allowMissing); if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { return callBind(intrinsic); } return intrinsic; }; },{"./":8,"get-intrinsic":11}],8:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); var GetIntrinsic = require('get-intrinsic'); var $apply = GetIntrinsic('%Function.prototype.apply%'); var $call = GetIntrinsic('%Function.prototype.call%'); var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); var $max = GetIntrinsic('%Math.max%'); if ($defineProperty) { try { $defineProperty({}, 'a', { value: 1 }); } catch (e) { // IE 8 has a broken defineProperty $defineProperty = null; } } module.exports = function callBind(originalFunction) { var func = $reflectApply(bind, $call, arguments); if ($gOPD && $defineProperty) { var desc = $gOPD(func, 'length'); if (desc.configurable) { // original length, plus the receiver, minus any additional arguments (after the receiver) $defineProperty( func, 'length', { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } ); } } return func; }; var applyBind = function applyBind() { return $reflectApply(bind, $apply, arguments); }; if ($defineProperty) { $defineProperty(module.exports, 'apply', { value: applyBind }); } else { module.exports.apply = applyBind; } },{"function-bind":10,"get-intrinsic":11}],9:[function(require,module,exports){ 'use strict'; /* eslint no-invalid-this: 1 */ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; },{}],10:[function(require,module,exports){ 'use strict'; var implementation = require('./implementation'); module.exports = Function.prototype.bind || implementation; },{"./implementation":9}],11:[function(require,module,exports){ 'use strict'; var undefined; var $SyntaxError = SyntaxError; var $Function = Function; var $TypeError = TypeError; // eslint-disable-next-line consistent-return var getEvalledConstructor = function (expressionSyntax) { try { return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); } catch (e) {} }; var $gOPD = Object.getOwnPropertyDescriptor; if ($gOPD) { try { $gOPD({}, ''); } catch (e) { $gOPD = null; // this is IE 8, which has a broken gOPD } } var throwTypeError = function () { throw new $TypeError(); }; var ThrowTypeError = $gOPD ? (function () { try { // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties arguments.callee; // IE 8 does not throw here return throwTypeError; } catch (calleeThrows) { try { // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') return $gOPD(arguments, 'callee').get; } catch (gOPDthrows) { return throwTypeError; } } }()) : throwTypeError; var hasSymbols = require('has-symbols')(); var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto var needsEval = {}; var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); var INTRINSICS = { '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, '%Array%': Array, '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, '%AsyncFromSyncIteratorPrototype%': undefined, '%AsyncFunction%': needsEval, '%AsyncGenerator%': needsEval, '%AsyncGeneratorFunction%': needsEval, '%AsyncIteratorPrototype%': needsEval, '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, '%Boolean%': Boolean, '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, '%Date%': Date, '%decodeURI%': decodeURI, '%decodeURIComponent%': decodeURIComponent, '%encodeURI%': encodeURI, '%encodeURIComponent%': encodeURIComponent, '%Error%': Error, '%eval%': eval, // eslint-disable-line no-eval '%EvalError%': EvalError, '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, '%Function%': $Function, '%GeneratorFunction%': needsEval, '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, '%isFinite%': isFinite, '%isNaN%': isNaN, '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, '%JSON%': typeof JSON === 'object' ? JSON : undefined, '%Map%': typeof Map === 'undefined' ? undefined : Map, '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), '%Math%': Math, '%Number%': Number, '%Object%': Object, '%parseFloat%': parseFloat, '%parseInt%': parseInt, '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, '%RangeError%': RangeError, '%ReferenceError%': ReferenceError, '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, '%RegExp%': RegExp, '%Set%': typeof Set === 'undefined' ? undefined : Set, '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, '%String%': String, '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, '%Symbol%': hasSymbols ? Symbol : undefined, '%SyntaxError%': $SyntaxError, '%ThrowTypeError%': ThrowTypeError, '%TypedArray%': TypedArray, '%TypeError%': $TypeError, '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, '%URIError%': URIError, '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet }; var doEval = function doEval(name) { var value; if (name === '%AsyncFunction%') { value = getEvalledConstructor('async function () {}'); } else if (name === '%GeneratorFunction%') { value = getEvalledConstructor('function* () {}'); } else if (name === '%AsyncGeneratorFunction%') { value = getEvalledConstructor('async function* () {}'); } else if (name === '%AsyncGenerator%') { var fn = doEval('%AsyncGeneratorFunction%'); if (fn) { value = fn.prototype; } } else if (name === '%AsyncIteratorPrototype%') { var gen = doEval('%AsyncGenerator%'); if (gen) { value = getProto(gen.prototype); } } INTRINSICS[name] = value; return value; }; var LEGACY_ALIASES = { '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], '%ArrayPrototype%': ['Array', 'prototype'], '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], '%ArrayProto_values%': ['Array', 'prototype', 'values'], '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], '%BooleanPrototype%': ['Boolean', 'prototype'], '%DataViewPrototype%': ['DataView', 'prototype'], '%DatePrototype%': ['Date', 'prototype'], '%ErrorPrototype%': ['Error', 'prototype'], '%EvalErrorPrototype%': ['EvalError', 'prototype'], '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], '%FunctionPrototype%': ['Function', 'prototype'], '%Generator%': ['GeneratorFunction', 'prototype'], '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], '%JSONParse%': ['JSON', 'parse'], '%JSONStringify%': ['JSON', 'stringify'], '%MapPrototype%': ['Map', 'prototype'], '%NumberPrototype%': ['Number', 'prototype'], '%ObjectPrototype%': ['Object', 'prototype'], '%ObjProto_toString%': ['Object', 'prototype', 'toString'], '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], '%PromisePrototype%': ['Promise', 'prototype'], '%PromiseProto_then%': ['Promise', 'prototype', 'then'], '%Promise_all%': ['Promise', 'all'], '%Promise_reject%': ['Promise', 'reject'], '%Promise_resolve%': ['Promise', 'resolve'], '%RangeErrorPrototype%': ['RangeError', 'prototype'], '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], '%RegExpPrototype%': ['RegExp', 'prototype'], '%SetPrototype%': ['Set', 'prototype'], '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], '%StringPrototype%': ['String', 'prototype'], '%SymbolPrototype%': ['Symbol', 'prototype'], '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], '%TypedArrayPrototype%': ['TypedArray', 'prototype'], '%TypeErrorPrototype%': ['TypeError', 'prototype'], '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], '%URIErrorPrototype%': ['URIError', 'prototype'], '%WeakMapPrototype%': ['WeakMap', 'prototype'], '%WeakSetPrototype%': ['WeakSet', 'prototype'] }; var bind = require('function-bind'); var hasOwn = require('has'); var $concat = bind.call(Function.call, Array.prototype.concat); var $spliceApply = bind.call(Function.apply, Array.prototype.splice); var $replace = bind.call(Function.call, String.prototype.replace); var $strSlice = bind.call(Function.call, String.prototype.slice); /* adapted from path_to_url#L6735-L6744 */ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ var stringToPath = function stringToPath(string) { var first = $strSlice(string, 0, 1); var last = $strSlice(string, -1); if (first === '%' && last !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); } else if (last === '%' && first !== '%') { throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); } var result = []; $replace(string, rePropName, function (match, number, quote, subString) { result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; }); return result; }; /* end adaptation */ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { var intrinsicName = name; var alias; if (hasOwn(LEGACY_ALIASES, intrinsicName)) { alias = LEGACY_ALIASES[intrinsicName]; intrinsicName = '%' + alias[0] + '%'; } if (hasOwn(INTRINSICS, intrinsicName)) { var value = INTRINSICS[intrinsicName]; if (value === needsEval) { value = doEval(intrinsicName); } if (typeof value === 'undefined' && !allowMissing) { throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); } return { alias: alias, name: intrinsicName, value: value }; } throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); }; module.exports = function GetIntrinsic(name, allowMissing) { if (typeof name !== 'string' || name.length === 0) { throw new $TypeError('intrinsic name must be a non-empty string'); } if (arguments.length > 1 && typeof allowMissing !== 'boolean') { throw new $TypeError('"allowMissing" argument must be a boolean'); } var parts = stringToPath(name); var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); var intrinsicRealName = intrinsic.name; var value = intrinsic.value; var skipFurtherCaching = false; var alias = intrinsic.alias; if (alias) { intrinsicBaseName = alias[0]; $spliceApply(parts, $concat([0, 1], alias)); } for (var i = 1, isOwn = true; i < parts.length; i += 1) { var part = parts[i]; var first = $strSlice(part, 0, 1); var last = $strSlice(part, -1); if ( ( (first === '"' || first === "'" || first === '`') || (last === '"' || last === "'" || last === '`') ) && first !== last ) { throw new $SyntaxError('property names with quotes must have matching quotes'); } if (part === 'constructor' || !isOwn) { skipFurtherCaching = true; } intrinsicBaseName += '.' + part; intrinsicRealName = '%' + intrinsicBaseName + '%'; if (hasOwn(INTRINSICS, intrinsicRealName)) { value = INTRINSICS[intrinsicRealName]; } else if (value != null) { if (!(part in value)) { if (!allowMissing) { throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); } return void undefined; } if ($gOPD && (i + 1) >= parts.length) { var desc = $gOPD(value, part); isOwn = !!desc; // By convention, when a data property is converted to an accessor // property to emulate a data property that does not suffer from // the override mistake, that accessor's getter is marked with // an `originalValue` property. Here, when we detect this, we // uphold the illusion by pretending to see that original data // property, i.e., returning the value rather than the getter // itself. if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { value = desc.get; } else { value = value[part]; } } else { isOwn = hasOwn(value, part); value = value[part]; } if (isOwn && !skipFurtherCaching) { INTRINSICS[intrinsicRealName] = value; } } } return value; }; },{"function-bind":10,"has":14,"has-symbols":12}],12:[function(require,module,exports){ 'use strict'; var origSymbol = typeof Symbol !== 'undefined' && Symbol; var hasSymbolSham = require('./shams'); module.exports = function hasNativeSymbols() { if (typeof origSymbol !== 'function') { return false; } if (typeof Symbol !== 'function') { return false; } if (typeof origSymbol('foo') !== 'symbol') { return false; } if (typeof Symbol('bar') !== 'symbol') { return false; } return hasSymbolSham(); }; },{"./shams":13}],13:[function(require,module,exports){ 'use strict'; /* eslint complexity: [2, 18], max-statements: [2, 33] */ module.exports = function hasSymbols() { if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } if (typeof Symbol.iterator === 'symbol') { return true; } var obj = {}; var sym = Symbol('test'); var symObj = Object(sym); if (typeof sym === 'string') { return false; } if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } // temp disabled per path_to_url // if (sym instanceof Symbol) { return false; } // temp disabled per path_to_url // if (!(symObj instanceof Symbol)) { return false; } // if (typeof Symbol.prototype.toString !== 'function') { return false; } // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } var symVal = 42; obj[sym] = symVal; for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } var syms = Object.getOwnPropertySymbols(obj); if (syms.length !== 1 || syms[0] !== sym) { return false; } if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } if (typeof Object.getOwnPropertyDescriptor === 'function') { var descriptor = Object.getOwnPropertyDescriptor(obj, sym); if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } } return true; }; },{}],14:[function(require,module,exports){ 'use strict'; var bind = require('function-bind'); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); },{"function-bind":10}],15:[function(require,module,exports){ var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; var booleanValueOf = Boolean.prototype.valueOf; var objectToString = Object.prototype.toString; var functionToString = Function.prototype.toString; var $match = String.prototype.match; var $slice = String.prototype.slice; var $replace = String.prototype.replace; var $toUpperCase = String.prototype.toUpperCase; var $toLowerCase = String.prototype.toLowerCase; var $test = RegExp.prototype.test; var $concat = Array.prototype.concat; var $join = Array.prototype.join; var $arrSlice = Array.prototype.slice; var $floor = Math.floor; var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; var gOPS = Object.getOwnPropertySymbols; var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; // ie, `has-tostringtag/shams var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') ? Symbol.toStringTag : null; var isEnumerable = Object.prototype.propertyIsEnumerable; var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( [].__proto__ === Array.prototype // eslint-disable-line no-proto ? function (O) { return O.__proto__; // eslint-disable-line no-proto } : null ); function addNumericSeparator(num, str) { if ( num === Infinity || num === -Infinity || num !== num || (num && num > -1000 && num < 1000) || $test.call(/e/, str) ) { return str; } var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; if (typeof num === 'number') { var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) if (int !== num) { var intStr = String(int); var dec = $slice.call(str, intStr.length + 1); return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); } } return $replace.call(str, sepRegex, '$&_'); } var utilInspect = require('./util.inspect'); var inspectCustom = utilInspect.custom; var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; module.exports = function inspect_(obj, options, depth, seen) { var opts = options || {}; if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) { throw new TypeError('option "quoteStyle" must be "single" or "double"'); } if ( has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity : opts.maxStringLength !== null ) ) { throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); } var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); } if ( has(opts, 'indent') && opts.indent !== null && opts.indent !== '\t' && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) ) { throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); } if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); } var numericSeparator = opts.numericSeparator; if (typeof obj === 'undefined') { return 'undefined'; } if (obj === null) { return 'null'; } if (typeof obj === 'boolean') { return obj ? 'true' : 'false'; } if (typeof obj === 'string') { return inspectString(obj, opts); } if (typeof obj === 'number') { if (obj === 0) { return Infinity / obj > 0 ? '0' : '-0'; } var str = String(obj); return numericSeparator ? addNumericSeparator(obj, str) : str; } if (typeof obj === 'bigint') { var bigIntStr = String(obj) + 'n'; return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; } var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; if (typeof depth === 'undefined') { depth = 0; } if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { return isArray(obj) ? '[Array]' : '[Object]'; } var indent = getIndent(opts, depth); if (typeof seen === 'undefined') { seen = []; } else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect(value, from, noIndent) { if (from) { seen = $arrSlice.call(seen); seen.push(from); } if (noIndent) { var newOpts = { depth: opts.depth }; if (has(opts, 'quoteStyle')) { newOpts.quoteStyle = opts.quoteStyle; } return inspect_(value, newOpts, depth + 1, seen); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable var name = nameOf(obj); var keys = arrObjKeys(obj, inspect); return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); } if (isSymbol(obj)) { var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; } if (isElement(obj)) { var s = '<' + $toLowerCase.call(String(obj.nodeName)); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); } s += '>'; if (obj.childNodes && obj.childNodes.length) { s += '...'; } s += '</' + $toLowerCase.call(String(obj.nodeName)) + '>'; return s; } if (isArray(obj)) { if (obj.length === 0) { return '[]'; } var xs = arrObjKeys(obj, inspect); if (indent && !singleLineValues(xs)) { return '[' + indentedJoin(xs, indent) + ']'; } return '[ ' + $join.call(xs, ', ') + ' ]'; } if (isError(obj)) { var parts = arrObjKeys(obj, inspect); if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; } if (parts.length === 0) { return '[' + String(obj) + ']'; } return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; } if (typeof obj === 'object' && customInspect) { if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { return utilInspect(obj, { depth: maxDepth - depth }); } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { return obj.inspect(); } } if (isMap(obj)) { var mapParts = []; mapForEach.call(obj, function (value, key) { mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); }); return collectionOf('Map', mapSize.call(obj), mapParts, indent); } if (isSet(obj)) { var setParts = []; setForEach.call(obj, function (value) { setParts.push(inspect(value, obj)); }); return collectionOf('Set', setSize.call(obj), setParts, indent); } if (isWeakMap(obj)) { return weakCollectionOf('WeakMap'); } if (isWeakSet(obj)) { return weakCollectionOf('WeakSet'); } if (isWeakRef(obj)) { return weakCollectionOf('WeakRef'); } if (isNumber(obj)) { return markBoxed(inspect(Number(obj))); } if (isBigInt(obj)) { return markBoxed(inspect(bigIntValueOf.call(obj))); } if (isBoolean(obj)) { return markBoxed(booleanValueOf.call(obj)); } if (isString(obj)) { return markBoxed(inspect(String(obj))); } if (!isDate(obj) && !isRegExp(obj)) { var ys = arrObjKeys(obj, inspect); var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; var protoTag = obj instanceof Object ? '' : 'null prototype'; var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); if (ys.length === 0) { return tag + '{}'; } if (indent) { return tag + '{' + indentedJoin(ys, indent) + '}'; } return tag + '{ ' + $join.call(ys, ', ') + ' }'; } return String(obj); }; function wrapQuotes(s, defaultStyle, opts) { var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'"; return quoteChar + s + quoteChar; } function quote(s) { return $replace.call(String(s), /"/g, '&quot;'); } function isArray(obj) { return toStr(obj) === '[object Array]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isDate(obj) { return toStr(obj) === '[object Date]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isError(obj) { return toStr(obj) === '[object Error]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isString(obj) { return toStr(obj) === '[object String]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isNumber(obj) { return toStr(obj) === '[object Number]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && (!toStringTag || !(typeof obj === 'object' && toStringTag in obj)); } // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives function isSymbol(obj) { if (hasShammedSymbols) { return obj && typeof obj === 'object' && obj instanceof Symbol; } if (typeof obj === 'symbol') { return true; } if (!obj || typeof obj !== 'object' || !symToString) { return false; } try { symToString.call(obj); return true; } catch (e) {} return false; } function isBigInt(obj) { if (!obj || typeof obj !== 'object' || !bigIntValueOf) { return false; } try { bigIntValueOf.call(obj); return true; } catch (e) {} return false; } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has(obj, key) { return hasOwn.call(obj, key); } function toStr(obj) { return objectToString.call(obj); } function nameOf(f) { if (f.name) { return f.name; } var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); if (m) { return m[1]; } return null; } function indexOf(xs, x) { if (xs.indexOf) { return xs.indexOf(x); } for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) { return i; } } return -1; } function isMap(x) { if (!mapSize || !x || typeof x !== 'object') { return false; } try { mapSize.call(x); try { setSize.call(x); } catch (s) { return true; } return x instanceof Map; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakMap(x) { if (!weakMapHas || !x || typeof x !== 'object') { return false; } try { weakMapHas.call(x, weakMapHas); try { weakSetHas.call(x, weakSetHas); } catch (s) { return true; } return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakRef(x) { if (!weakRefDeref || !x || typeof x !== 'object') { return false; } try { weakRefDeref.call(x); return true; } catch (e) {} return false; } function isSet(x) { if (!setSize || !x || typeof x !== 'object') { return false; } try { setSize.call(x); try { mapSize.call(x); } catch (m) { return true; } return x instanceof Set; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isWeakSet(x) { if (!weakSetHas || !x || typeof x !== 'object') { return false; } try { weakSetHas.call(x, weakSetHas); try { weakMapHas.call(x, weakMapHas); } catch (s) { return true; } return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 } catch (e) {} return false; } function isElement(x) { if (!x || typeof x !== 'object') { return false; } if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; } function inspectString(str, opts) { if (str.length > opts.maxStringLength) { var remaining = str.length - opts.maxStringLength; var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; } // eslint-disable-next-line no-control-regex var s = $replace.call($replace.call(str, /(['\\])/g, '\\$1'), /[\x00-\x1f]/g, lowbyte); return wrapQuotes(s, 'single', opts); } function lowbyte(c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) { return '\\' + x; } return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); } function markBoxed(str) { return 'Object(' + str + ')'; } function weakCollectionOf(type) { return type + ' { ? }'; } function collectionOf(type, size, entries, indent) { var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); return type + ' (' + size + ') {' + joinedEntries + '}'; } function singleLineValues(xs) { for (var i = 0; i < xs.length; i++) { if (indexOf(xs[i], '\n') >= 0) { return false; } } return true; } function getIndent(opts, depth) { var baseIndent; if (opts.indent === '\t') { baseIndent = '\t'; } else if (typeof opts.indent === 'number' && opts.indent > 0) { baseIndent = $join.call(Array(opts.indent + 1), ' '); } else { return null; } return { base: baseIndent, prev: $join.call(Array(depth + 1), baseIndent) }; } function indentedJoin(xs, indent) { if (xs.length === 0) { return ''; } var lineJoiner = '\n' + indent.prev + indent.base; return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; } function arrObjKeys(obj, inspect) { var isArr = isArray(obj); var xs = []; if (isArr) { xs.length = obj.length; for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } } var syms = typeof gOPS === 'function' ? gOPS(obj) : []; var symMap; if (hasShammedSymbols) { symMap = {}; for (var k = 0; k < syms.length; k++) { symMap['$' + syms[k]] = syms[k]; } } for (var key in obj) { // eslint-disable-line no-restricted-syntax if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section continue; // eslint-disable-line no-restricted-syntax, no-continue } else if ($test.call(/[^\w$]/, key)) { xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); } else { xs.push(key + ': ' + inspect(obj[key], obj)); } } if (typeof gOPS === 'function') { for (var j = 0; j < syms.length; j++) { if (isEnumerable.call(obj, syms[j])) { xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); } } } return xs; } },{"./util.inspect":6}],16:[function(require,module,exports){ 'use strict'; var GetIntrinsic = require('get-intrinsic'); var callBound = require('call-bind/callBound'); var inspect = require('object-inspect'); var $TypeError = GetIntrinsic('%TypeError%'); var $WeakMap = GetIntrinsic('%WeakMap%', true); var $Map = GetIntrinsic('%Map%', true); var $weakMapGet = callBound('WeakMap.prototype.get', true); var $weakMapSet = callBound('WeakMap.prototype.set', true); var $weakMapHas = callBound('WeakMap.prototype.has', true); var $mapGet = callBound('Map.prototype.get', true); var $mapSet = callBound('Map.prototype.set', true); var $mapHas = callBound('Map.prototype.has', true); /* * This function traverses the list returning the node corresponding to the * given key. * * That node is also moved to the head of the list, so that if it's accessed * again we don't need to traverse the whole list. By doing so, all the recently * used nodes can be accessed relatively quickly. */ var listGetNode = function (list, key) { // eslint-disable-line consistent-return for (var prev = list, curr; (curr = prev.next) !== null; prev = curr) { if (curr.key === key) { prev.next = curr.next; curr.next = list.next; list.next = curr; // eslint-disable-line no-param-reassign return curr; } } }; var listGet = function (objects, key) { var node = listGetNode(objects, key); return node && node.value; }; var listSet = function (objects, key, value) { var node = listGetNode(objects, key); if (node) { node.value = value; } else { // Prepend the new node to the beginning of the list objects.next = { // eslint-disable-line no-param-reassign key: key, next: objects.next, value: value }; } }; var listHas = function (objects, key) { return !!listGetNode(objects, key); }; module.exports = function getSideChannel() { var $wm; var $m; var $o; var channel = { assert: function (key) { if (!channel.has(key)) { throw new $TypeError('Side channel does not contain ' + inspect(key)); } }, get: function (key) { // eslint-disable-line consistent-return if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapGet($wm, key); } } else if ($Map) { if ($m) { return $mapGet($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listGet($o, key); } } }, has: function (key) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if ($wm) { return $weakMapHas($wm, key); } } else if ($Map) { if ($m) { return $mapHas($m, key); } } else { if ($o) { // eslint-disable-line no-lonely-if return listHas($o, key); } } return false; }, set: function (key, value) { if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { if (!$wm) { $wm = new $WeakMap(); } $weakMapSet($wm, key, value); } else if ($Map) { if (!$m) { $m = new $Map(); } $mapSet($m, key, value); } else { if (!$o) { /* * Initialize the linked list as an empty node, so that we don't have * to special-case handling of the first node: we can always refer to * it as (previous node).next, instead of something like (list).head */ $o = { key: {}, next: null }; } listSet($o, key, value); } } }; return channel; }; },{"call-bind/callBound":7,"get-intrinsic":11,"object-inspect":15}]},{},[2])(2) }); ```
/content/code_sandbox/node_modules/superagent/node_modules/qs/dist/qs.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
17,517
```javascript // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /*<replacement>*/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); } return keys; }; /*</replacement>*/ module.exports = Duplex; var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); require('inherits')(Duplex, Readable); { // Allow the keys array to be GC'ed. var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); this.allowHalfOpen = true; if (options) { if (options.readable === false) this.readable = false; if (options.writable === false) this.writable = false; if (options.allowHalfOpen === false) { this.allowHalfOpen = false; this.once('end', onend); } } } Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.highWaterMark; } }); Object.defineProperty(Duplex.prototype, 'writableBuffer', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState && this._writableState.getBuffer(); } }); Object.defineProperty(Duplex.prototype, 'writableLength', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { return this._writableState.length; } }); // the no-half-open enforcer function onend() { // If the writable side ended, then we're ok. if (this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. process.nextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { // making it explicit this property is not enumerable // because otherwise some prototype manipulation in // userland will fail enumerable: false, get: function get() { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function set(value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/_stream_duplex.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,015
```javascript // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var _require$codes = require('../errors').codes, ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK, ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING, ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0; var Duplex = require('./_stream_duplex'); require('inherits')(Transform, Duplex); function afterTransform(er, data) { var ts = this._transformState; ts.transforming = false; var cb = ts.writecb; if (cb === null) { return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; ts.writecb = null; if (data != null) // single equals check for both `null` and `undefined` this.push(data); cb(er); var rs = this._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { this._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = { afterTransform: afterTransform.bind(this), needTransform: false, transforming: false, writecb: null, writechunk: null, writeencoding: null }; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.on('prefinish', prefinish); } function prefinish() { var _this = this; if (typeof this._flush === 'function' && !this._readableState.destroyed) { this._flush(function (er, data) { done(_this, er, data); }); } else { done(this, null, null); } } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()')); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data != null) // single equals check for both `null` and `undefined` stream.push(data); // TODO(BridgeAR): Write a test for these two error cases // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/_stream_transform.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,879
```javascript 'use strict'; // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err) { if (!this._writableState) { process.nextTick(emitErrorNT, this, err); } else if (!this._writableState.errorEmitted) { this._writableState.errorEmitted = true; process.nextTick(emitErrorNT, this, err); } } return this; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { if (!_this._writableState) { process.nextTick(emitErrorAndCloseNT, _this, err); } else if (!_this._writableState.errorEmitted) { _this._writableState.errorEmitted = true; process.nextTick(emitErrorAndCloseNT, _this, err); } else { process.nextTick(emitCloseNT, _this); } } else if (cb) { process.nextTick(emitCloseNT, _this); cb(err); } else { process.nextTick(emitCloseNT, _this); } }); return this; } function emitErrorAndCloseNT(self, err) { emitErrorNT(self, err); emitCloseNT(self); } function emitCloseNT(self) { if (self._writableState && !self._writableState.emitClose) return; if (self._readableState && !self._readableState.emitClose) return; self.emit('close'); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finalCalled = false; this._writableState.prefinished = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } function errorOrDestroy(stream, err) { // We have tests that rely on errors being emitted // in the same tick, so changing this is semver major. // For now when you opt-in to autoDestroy we allow // the error to be emitted nextTick. In a future // semver major update we should change the default to this. var rState = stream._readableState; var wState = stream._writableState; if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy, errorOrDestroy: errorOrDestroy }; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/destroy.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
833
```javascript module.exports = function () { throw new Error('Readable.from is not available in the browser') }; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/from-browser.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
22
```javascript // Ported from path_to_url with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE; function once(callback) { var called = false; return function () { if (called) return; called = true; for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } callback.apply(this, args); }; } function noop() {} function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function eos(stream, opts, callback) { if (typeof opts === 'function') return eos(stream, null, opts); if (!opts) opts = {}; callback = once(callback || noop); var readable = opts.readable || opts.readable !== false && stream.readable; var writable = opts.writable || opts.writable !== false && stream.writable; var onlegacyfinish = function onlegacyfinish() { if (!stream.writable) onfinish(); }; var writableEnded = stream._writableState && stream._writableState.finished; var onfinish = function onfinish() { writable = false; writableEnded = true; if (!readable) callback.call(stream); }; var readableEnded = stream._readableState && stream._readableState.endEmitted; var onend = function onend() { readable = false; readableEnded = true; if (!writable) callback.call(stream); }; var onerror = function onerror(err) { callback.call(stream, err); }; var onclose = function onclose() { var err; if (readable && !readableEnded) { if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } if (writable && !writableEnded) { if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE(); return callback.call(stream, err); } }; var onrequest = function onrequest() { stream.req.on('finish', onfinish); }; if (isRequest(stream)) { stream.on('complete', onfinish); stream.on('abort', onclose); if (stream.req) onrequest();else stream.on('request', onrequest); } else if (writable && !stream._writableState) { // legacy streams stream.on('end', onlegacyfinish); stream.on('close', onlegacyfinish); } stream.on('end', onend); stream.on('finish', onfinish); if (opts.error !== false) stream.on('error', onerror); stream.on('close', onclose); return function () { stream.removeListener('complete', onfinish); stream.removeListener('abort', onclose); stream.removeListener('request', onrequest); if (stream.req) stream.req.removeListener('finish', onfinish); stream.removeListener('end', onlegacyfinish); stream.removeListener('close', onlegacyfinish); stream.removeListener('finish', onfinish); stream.removeListener('end', onend); stream.removeListener('error', onerror); stream.removeListener('close', onclose); }; } module.exports = eos; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/end-of-stream.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
758
```javascript 'use strict'; var _Object$setPrototypeO; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var finished = require('./end-of-stream'); var kLastResolve = Symbol('lastResolve'); var kLastReject = Symbol('lastReject'); var kError = Symbol('error'); var kEnded = Symbol('ended'); var kLastPromise = Symbol('lastPromise'); var kHandlePromise = Symbol('handlePromise'); var kStream = Symbol('stream'); function createIterResult(value, done) { return { value: value, done: done }; } function readAndResolve(iter) { var resolve = iter[kLastResolve]; if (resolve !== null) { var data = iter[kStream].read(); // we defer if data is null // we can be expecting either 'end' or // 'error' if (data !== null) { iter[kLastPromise] = null; iter[kLastResolve] = null; iter[kLastReject] = null; resolve(createIterResult(data, false)); } } } function onReadable(iter) { // we wait for the next tick, because it might // emit an error with process.nextTick process.nextTick(readAndResolve, iter); } function wrapForNext(lastPromise, iter) { return function (resolve, reject) { lastPromise.then(function () { if (iter[kEnded]) { resolve(createIterResult(undefined, true)); return; } iter[kHandlePromise](resolve, reject); }, reject); }; } var AsyncIteratorPrototype = Object.getPrototypeOf(function () {}); var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = { get stream() { return this[kStream]; }, next: function next() { var _this = this; // if we have detected an error in the meanwhile // reject straight away var error = this[kError]; if (error !== null) { return Promise.reject(error); } if (this[kEnded]) { return Promise.resolve(createIterResult(undefined, true)); } if (this[kStream].destroyed) { // We need to defer via nextTick because if .destroy(err) is // called, the error will be emitted via nextTick, and // we cannot guarantee that there is no error lingering around // waiting to be emitted. return new Promise(function (resolve, reject) { process.nextTick(function () { if (_this[kError]) { reject(_this[kError]); } else { resolve(createIterResult(undefined, true)); } }); }); } // if we have multiple next() calls // we will wait for the previous Promise to finish // this logic is optimized to support for await loops, // where next() is only called once at a time var lastPromise = this[kLastPromise]; var promise; if (lastPromise) { promise = new Promise(wrapForNext(lastPromise, this)); } else { // fast path needed to support multiple this.push() // without triggering the next() queue var data = this[kStream].read(); if (data !== null) { return Promise.resolve(createIterResult(data, false)); } promise = new Promise(this[kHandlePromise]); } this[kLastPromise] = promise; return promise; } }, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () { return this; }), _defineProperty(_Object$setPrototypeO, "return", function _return() { var _this2 = this; // destroy(err, cb) is a private API // we can guarantee we have that here, because we control the // Readable class this is attached to return new Promise(function (resolve, reject) { _this2[kStream].destroy(null, function (err) { if (err) { reject(err); return; } resolve(createIterResult(undefined, true)); }); }); }), _Object$setPrototypeO), AsyncIteratorPrototype); var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) { var _Object$create; var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, { value: stream, writable: true }), _defineProperty(_Object$create, kLastResolve, { value: null, writable: true }), _defineProperty(_Object$create, kLastReject, { value: null, writable: true }), _defineProperty(_Object$create, kError, { value: null, writable: true }), _defineProperty(_Object$create, kEnded, { value: stream._readableState.endEmitted, writable: true }), _defineProperty(_Object$create, kHandlePromise, { value: function value(resolve, reject) { var data = iterator[kStream].read(); if (data) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(data, false)); } else { iterator[kLastResolve] = resolve; iterator[kLastReject] = reject; } }, writable: true }), _Object$create)); iterator[kLastPromise] = null; finished(stream, function (err) { if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise // returned by next() and store the error if (reject !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; reject(err); } iterator[kError] = err; return; } var resolve = iterator[kLastResolve]; if (resolve !== null) { iterator[kLastPromise] = null; iterator[kLastResolve] = null; iterator[kLastReject] = null; resolve(createIterResult(undefined, true)); } iterator[kEnded] = true; }); stream.on('readable', onReadable.bind(null, iterator)); return iterator; }; module.exports = createReadableStreamAsyncIterator; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/async_iterator.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,427
```javascript // Ported from path_to_url with // permission from the author, Mathias Buus (@mafintosh). 'use strict'; var eos; function once(callback) { var called = false; return function () { if (called) return; called = true; callback.apply(void 0, arguments); }; } var _require$codes = require('../../../errors').codes, ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS, ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED; function noop(err) { // Rethrow the error if it exists to avoid swallowing it if (err) throw err; } function isRequest(stream) { return stream.setHeader && typeof stream.abort === 'function'; } function destroyer(stream, reading, writing, callback) { callback = once(callback); var closed = false; stream.on('close', function () { closed = true; }); if (eos === undefined) eos = require('./end-of-stream'); eos(stream, { readable: reading, writable: writing }, function (err) { if (err) return callback(err); closed = true; callback(); }); var destroyed = false; return function (err) { if (closed) return; if (destroyed) return; destroyed = true; // request.destroy just do .end - .abort is what we want if (isRequest(stream)) return stream.abort(); if (typeof stream.destroy === 'function') return stream.destroy(); callback(err || new ERR_STREAM_DESTROYED('pipe')); }; } function call(fn) { fn(); } function pipe(from, to) { return from.pipe(to); } function popCallback(streams) { if (!streams.length) return noop; if (typeof streams[streams.length - 1] !== 'function') return noop; return streams.pop(); } function pipeline() { for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) { streams[_key] = arguments[_key]; } var callback = popCallback(streams); if (Array.isArray(streams[0])) streams = streams[0]; if (streams.length < 2) { throw new ERR_MISSING_ARGS('streams'); } var error; var destroys = streams.map(function (stream, i) { var reading = i < streams.length - 1; var writing = i > 0; return destroyer(stream, reading, writing, function (err) { if (!error) error = err; if (err) destroys.forEach(call); if (reading) return; destroys.forEach(call); callback(error); }); }); return streams.reduce(pipe); } module.exports = pipeline; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/pipeline.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
602
```javascript 'use strict'; var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE; function highWaterMarkFrom(options, isDuplex, duplexKey) { return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null; } function getHighWaterMark(state, options, duplexKey, isDuplex) { var hwm = highWaterMarkFrom(options, isDuplex, duplexKey); if (hwm != null) { if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) { var name = isDuplex ? duplexKey : 'highWaterMark'; throw new ERR_INVALID_OPT_VALUE(name, hwm); } return Math.floor(hwm); } // Default value return state.objectMode ? 16 : 16 * 1024; } module.exports = { getHighWaterMark: getHighWaterMark }; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/state.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
209
```javascript 'use strict'; function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var ERR_INVALID_ARG_TYPE = require('../../../errors').codes.ERR_INVALID_ARG_TYPE; function from(Readable, iterable, opts) { var iterator; if (iterable && typeof iterable.next === 'function') { iterator = iterable; } else if (iterable && iterable[Symbol.asyncIterator]) iterator = iterable[Symbol.asyncIterator]();else if (iterable && iterable[Symbol.iterator]) iterator = iterable[Symbol.iterator]();else throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable); var readable = new Readable(_objectSpread({ objectMode: true }, opts)); // Reading boolean to protect against _read // being called before last iteration completion. var reading = false; readable._read = function () { if (!reading) { reading = true; next(); } }; function next() { return _next2.apply(this, arguments); } function _next2() { _next2 = _asyncToGenerator(function* () { try { var _ref = yield iterator.next(), value = _ref.value, done = _ref.done; if (done) { readable.push(null); } else if (readable.push((yield value))) { next(); } else { reading = false; } } catch (err) { readable.destroy(err); } }); return _next2.apply(this, arguments); } return readable; } module.exports = from; ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/from.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
741
```javascript 'use strict'; function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } var _require = require('buffer'), Buffer = _require.Buffer; var _require2 = require('util'), inspect = _require2.inspect; var custom = inspect && inspect.custom || 'inspect'; function copyBuffer(src, target, offset) { Buffer.prototype.copy.call(src, target, offset); } module.exports = /*#__PURE__*/ function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } _createClass(BufferList, [{ key: "push", value: function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; } }, { key: "unshift", value: function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; } }, { key: "shift", value: function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; } }, { key: "clear", value: function clear() { this.head = this.tail = null; this.length = 0; } }, { key: "join", value: function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; } return ret; } }, { key: "concat", value: function concat(n) { if (this.length === 0) return Buffer.alloc(0); var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; } // Consumes a specified amount of bytes or characters from the buffered data. }, { key: "consume", value: function consume(n, hasStrings) { var ret; if (n < this.head.data.length) { // `slice` is the same for buffers and strings. ret = this.head.data.slice(0, n); this.head.data = this.head.data.slice(n); } else if (n === this.head.data.length) { // First chunk is a perfect match. ret = this.shift(); } else { // Result spans more than one buffer. ret = hasStrings ? this._getString(n) : this._getBuffer(n); } return ret; } }, { key: "first", value: function first() { return this.head.data; } // Consumes a specified amount of characters from the buffered data. }, { key: "_getString", value: function _getString(n) { var p = this.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = str.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Consumes a specified amount of bytes from the buffered data. }, { key: "_getBuffer", value: function _getBuffer(n) { var ret = Buffer.allocUnsafe(n); var p = this.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) this.head = p.next;else this.head = this.tail = null; } else { this.head = p; p.data = buf.slice(nb); } break; } ++c; } this.length -= c; return ret; } // Make sure the linked list only shows the minimal necessary information. }, { key: custom, value: function value(_, options) { return inspect(this, _objectSpread({}, options, { // Only inspect one level. depth: 0, // It should not recurse. customInspect: false })); } }]); return BufferList; }(); ```
/content/code_sandbox/node_modules/superagent/node_modules/readable-stream/lib/internal/streams/buffer_list.js
javascript
2016-03-11T09:28:00
2024-08-16T17:55:54
antSword
AntSwordProject/antSword
3,579
1,573