code
stringlengths
501
5.19M
package
stringlengths
2
81
path
stringlengths
9
304
filename
stringlengths
4
145
"use strict"; // Some environments don't have global Buffer (e.g. React Native). // Solution would be installing npm modules "buffer" and "stream" explicitly. var Buffer = require("safer-buffer").Buffer; var bomHandling = require("iconv-lite/lib/bom-handling"), iconv = module.exports; // All codecs and aliases are kept here, keyed by encoding name/alias. // They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. iconv.encodings = null; // Characters emitted in case of error. iconv.defaultCharUnicode = '�'; iconv.defaultCharSingleByte = '?'; // Public API. iconv.encode = function encode(str, encoding, options) { str = "" + (str || ""); // Ensure string. var encoder = iconv.getEncoder(encoding, options); var res = encoder.write(str); var trail = encoder.end(); return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; } iconv.decode = function decode(buf, encoding, options) { if (typeof buf === 'string') { if (!iconv.skipDecodeWarning) { console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); iconv.skipDecodeWarning = true; } buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } var decoder = iconv.getDecoder(encoding, options); var res = decoder.write(buf); var trail = decoder.end(); return trail ? (res + trail) : res; } iconv.encodingExists = function encodingExists(enc) { try { iconv.getCodec(enc); return true; } catch (e) { return false; } } // Legacy aliases to convert functions iconv.toEncoding = iconv.encode; iconv.fromEncoding = iconv.decode; // Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. iconv._codecDataCache = {}; iconv.getCodec = function getCodec(encoding) { if (!iconv.encodings) iconv.encodings = require("iconv-lite/encodings"); // Lazy load all encoding definitions. // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. var enc = iconv._canonicalizeEncoding(encoding); // Traverse iconv.encodings to find actual codec. var codecOptions = {}; while (true) { var codec = iconv._codecDataCache[enc]; if (codec) return codec; var codecDef = iconv.encodings[enc]; switch (typeof codecDef) { case "string": // Direct alias to other encoding. enc = codecDef; break; case "object": // Alias with options. Can be layered. for (var key in codecDef) codecOptions[key] = codecDef[key]; if (!codecOptions.encodingName) codecOptions.encodingName = enc; enc = codecDef.type; break; case "function": // Codec itself. if (!codecOptions.encodingName) codecOptions.encodingName = enc; // The codec function must load all tables and return object with .encoder and .decoder methods. // It'll be called only once (for each different options object). codec = new codecDef(codecOptions, iconv); iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. return codec; default: throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); } } } iconv._canonicalizeEncoding = function(encoding) { // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); } iconv.getEncoder = function getEncoder(encoding, options) { var codec = iconv.getCodec(encoding), encoder = new codec.encoder(options, codec); if (codec.bomAware && options && options.addBOM) encoder = new bomHandling.PrependBOM(encoder, options); return encoder; } iconv.getDecoder = function getDecoder(encoding, options) { var codec = iconv.getCodec(encoding), decoder = new codec.decoder(options, codec); if (codec.bomAware && !(options && options.stripBOM === false)) decoder = new bomHandling.StripBOM(decoder, options); return decoder; } // Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; if (nodeVer) { // Load streaming support in Node v0.10+ var nodeVerArr = nodeVer.split(".").map(Number); if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { require("iconv-lite/lib/streams")(iconv); } // Load Node primitive extensions. require("iconv-lite/lib/extend-node")(iconv); } if ("Ā" != "\u0100") { console.error("iconv-lite warning: javascript files use encoding different from utf-8. See https://github.com/ashtuchkin/iconv-lite/wiki/Javascript-source-file-encodings for more info."); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/lib/index.js
index.js
"use strict"; var Buffer = require("buffer").Buffer; // Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer // == Extend Node primitives to use iconv-lite ================================= module.exports = function (iconv) { var original = undefined; // Place to keep original methods. // Node authors rewrote Buffer internals to make it compatible with // Uint8Array and we cannot patch key functions since then. // Note: this does use older Buffer API on a purpose iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); iconv.extendNodeEncodings = function extendNodeEncodings() { if (original) return; original = {}; if (!iconv.supportsNodeEncodingsExtension) { console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); return; } var nodeNativeEncodings = { 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, }; Buffer.isNativeEncoding = function(enc) { return enc && nodeNativeEncodings[enc.toLowerCase()]; } // -- SlowBuffer ----------------------------------------------------------- var SlowBuffer = require('buffer').SlowBuffer; original.SlowBufferToString = SlowBuffer.prototype.toString; SlowBuffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible if (Buffer.isNativeEncoding(encoding)) return original.SlowBufferToString.call(this, encoding, start, end); // Otherwise, use our decoding method. if (typeof start == 'undefined') start = 0; if (typeof end == 'undefined') end = this.length; return iconv.decode(this.slice(start, end), encoding); } original.SlowBufferWrite = SlowBuffer.prototype.write; SlowBuffer.prototype.write = function(string, offset, length, encoding) { // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible if (Buffer.isNativeEncoding(encoding)) return original.SlowBufferWrite.call(this, string, offset, length, encoding); if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write beyond buffer bounds'); // Otherwise, use our encoding method. var buf = iconv.encode(string, encoding); if (buf.length < length) length = buf.length; buf.copy(this, offset, 0, length); return length; } // -- Buffer --------------------------------------------------------------- original.BufferIsEncoding = Buffer.isEncoding; Buffer.isEncoding = function(encoding) { return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); } original.BufferByteLength = Buffer.byteLength; Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible if (Buffer.isNativeEncoding(encoding)) return original.BufferByteLength.call(this, str, encoding); // Slow, I know, but we don't have a better way yet. return iconv.encode(str, encoding).length; } original.BufferToString = Buffer.prototype.toString; Buffer.prototype.toString = function(encoding, start, end) { encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible if (Buffer.isNativeEncoding(encoding)) return original.BufferToString.call(this, encoding, start, end); // Otherwise, use our decoding method. if (typeof start == 'undefined') start = 0; if (typeof end == 'undefined') end = this.length; return iconv.decode(this.slice(start, end), encoding); } original.BufferWrite = Buffer.prototype.write; Buffer.prototype.write = function(string, offset, length, encoding) { var _offset = offset, _length = length, _encoding = encoding; // Support both (string, offset, length, encoding) // and the legacy (string, encoding, offset, length) if (isFinite(offset)) { if (!isFinite(length)) { encoding = length; length = undefined; } } else { // legacy var swap = encoding; encoding = offset; offset = length; length = swap; } encoding = String(encoding || 'utf8').toLowerCase(); // Use native conversion when possible if (Buffer.isNativeEncoding(encoding)) return original.BufferWrite.call(this, string, _offset, _length, _encoding); offset = +offset || 0; var remaining = this.length - offset; if (!length) { length = remaining; } else { length = +length; if (length > remaining) { length = remaining; } } if (string.length > 0 && (length < 0 || offset < 0)) throw new RangeError('attempt to write beyond buffer bounds'); // Otherwise, use our encoding method. var buf = iconv.encode(string, encoding); if (buf.length < length) length = buf.length; buf.copy(this, offset, 0, length); return length; // TODO: Set _charsWritten. } // -- Readable ------------------------------------------------------------- if (iconv.supportsStreams) { var Readable = require('stream').Readable; original.ReadableSetEncoding = Readable.prototype.setEncoding; Readable.prototype.setEncoding = function setEncoding(enc, options) { // Use our own decoder, it has the same interface. // We cannot use original function as it doesn't handle BOM-s. this._readableState.decoder = iconv.getDecoder(enc, options); this._readableState.encoding = enc; } Readable.prototype.collect = iconv._collect; } } // Remove iconv-lite Node primitive extensions. iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { if (!iconv.supportsNodeEncodingsExtension) return; if (!original) throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") delete Buffer.isNativeEncoding; var SlowBuffer = require('buffer').SlowBuffer; SlowBuffer.prototype.toString = original.SlowBufferToString; SlowBuffer.prototype.write = original.SlowBufferWrite; Buffer.isEncoding = original.BufferIsEncoding; Buffer.byteLength = original.BufferByteLength; Buffer.prototype.toString = original.BufferToString; Buffer.prototype.write = original.BufferWrite; if (iconv.supportsStreams) { var Readable = require('stream').Readable; Readable.prototype.setEncoding = original.ReadableSetEncoding; delete Readable.prototype.collect; } original = undefined; } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/lib/extend-node.js
extend-node.js
"use strict"; var Buffer = require("safer-buffer").Buffer; // Export Node.js internal encodings. module.exports = { // Encodings utf8: { type: "_internal", bomAware: true}, cesu8: { type: "_internal", bomAware: true}, unicode11utf8: "utf8", ucs2: { type: "_internal", bomAware: true}, utf16le: "ucs2", binary: { type: "_internal" }, base64: { type: "_internal" }, hex: { type: "_internal" }, // Codec. _internal: InternalCodec, }; //------------------------------------------------------------------------------ function InternalCodec(codecOptions, iconv) { this.enc = codecOptions.encodingName; this.bomAware = codecOptions.bomAware; if (this.enc === "base64") this.encoder = InternalEncoderBase64; else if (this.enc === "cesu8") { this.enc = "utf8"; // Use utf8 for decoding. this.encoder = InternalEncoderCesu8; // Add decoder for versions of Node not supporting CESU-8 if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { this.decoder = InternalDecoderCesu8; this.defaultCharUnicode = iconv.defaultCharUnicode; } } } InternalCodec.prototype.encoder = InternalEncoder; InternalCodec.prototype.decoder = InternalDecoder; //------------------------------------------------------------------------------ // We use node.js internal decoder. Its signature is the same as ours. var StringDecoder = require('string_decoder').StringDecoder; if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. StringDecoder.prototype.end = function() {}; function InternalDecoder(options, codec) { StringDecoder.call(this, codec.enc); } InternalDecoder.prototype = StringDecoder.prototype; //------------------------------------------------------------------------------ // Encoder is mostly trivial function InternalEncoder(options, codec) { this.enc = codec.enc; } InternalEncoder.prototype.write = function(str) { return Buffer.from(str, this.enc); } InternalEncoder.prototype.end = function() { } //------------------------------------------------------------------------------ // Except base64 encoder, which must keep its state. function InternalEncoderBase64(options, codec) { this.prevStr = ''; } InternalEncoderBase64.prototype.write = function(str) { str = this.prevStr + str; var completeQuads = str.length - (str.length % 4); this.prevStr = str.slice(completeQuads); str = str.slice(0, completeQuads); return Buffer.from(str, "base64"); } InternalEncoderBase64.prototype.end = function() { return Buffer.from(this.prevStr, "base64"); } //------------------------------------------------------------------------------ // CESU-8 encoder is also special. function InternalEncoderCesu8(options, codec) { } InternalEncoderCesu8.prototype.write = function(str) { var buf = Buffer.alloc(str.length * 3), bufIdx = 0; for (var i = 0; i < str.length; i++) { var charCode = str.charCodeAt(i); // Naive implementation, but it works because CESU-8 is especially easy // to convert from UTF-16 (which all JS strings are encoded in). if (charCode < 0x80) buf[bufIdx++] = charCode; else if (charCode < 0x800) { buf[bufIdx++] = 0xC0 + (charCode >>> 6); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } else { // charCode will always be < 0x10000 in javascript. buf[bufIdx++] = 0xE0 + (charCode >>> 12); buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } return buf.slice(0, bufIdx); } InternalEncoderCesu8.prototype.end = function() { } //------------------------------------------------------------------------------ // CESU-8 decoder is not implemented in Node v4.0+ function InternalDecoderCesu8(options, codec) { this.acc = 0; this.contBytes = 0; this.accBytes = 0; this.defaultCharUnicode = codec.defaultCharUnicode; } InternalDecoderCesu8.prototype.write = function(buf) { var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, res = ''; for (var i = 0; i < buf.length; i++) { var curByte = buf[i]; if ((curByte & 0xC0) !== 0x80) { // Leading byte if (contBytes > 0) { // Previous code is invalid res += this.defaultCharUnicode; contBytes = 0; } if (curByte < 0x80) { // Single-byte code res += String.fromCharCode(curByte); } else if (curByte < 0xE0) { // Two-byte code acc = curByte & 0x1F; contBytes = 1; accBytes = 1; } else if (curByte < 0xF0) { // Three-byte code acc = curByte & 0x0F; contBytes = 2; accBytes = 1; } else { // Four or more are not supported for CESU-8. res += this.defaultCharUnicode; } } else { // Continuation byte if (contBytes > 0) { // We're waiting for it. acc = (acc << 6) | (curByte & 0x3f); contBytes--; accBytes++; if (contBytes === 0) { // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) if (accBytes === 2 && acc < 0x80 && acc > 0) res += this.defaultCharUnicode; else if (accBytes === 3 && acc < 0x800) res += this.defaultCharUnicode; else // Actually add character. res += String.fromCharCode(acc); } } else { // Unexpected continuation byte res += this.defaultCharUnicode; } } } this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; return res; } InternalDecoderCesu8.prototype.end = function() { var res = 0; if (this.contBytes > 0) res += this.defaultCharUnicode; return res; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/internal.js
internal.js
"use strict"; var Buffer = require("safer-buffer").Buffer; // Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js // == UTF16-BE codec. ========================================================== exports.utf16be = Utf16BECodec; function Utf16BECodec() { } Utf16BECodec.prototype.encoder = Utf16BEEncoder; Utf16BECodec.prototype.decoder = Utf16BEDecoder; Utf16BECodec.prototype.bomAware = true; // -- Encoding function Utf16BEEncoder() { } Utf16BEEncoder.prototype.write = function(str) { var buf = Buffer.from(str, 'ucs2'); for (var i = 0; i < buf.length; i += 2) { var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } return buf; } Utf16BEEncoder.prototype.end = function() { } // -- Decoding function Utf16BEDecoder() { this.overflowByte = -1; } Utf16BEDecoder.prototype.write = function(buf) { if (buf.length == 0) return ''; var buf2 = Buffer.alloc(buf.length + 1), i = 0, j = 0; if (this.overflowByte !== -1) { buf2[0] = buf[0]; buf2[1] = this.overflowByte; i = 1; j = 2; } for (; i < buf.length-1; i += 2, j+= 2) { buf2[j] = buf[i+1]; buf2[j+1] = buf[i]; } this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; return buf2.slice(0, j).toString('ucs2'); } Utf16BEDecoder.prototype.end = function() { } // == UTF-16 codec ============================================================= // Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. // Defaults to UTF-16LE, as it's prevalent and default in Node. // http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le // Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); // Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). exports.utf16 = Utf16Codec; function Utf16Codec(codecOptions, iconv) { this.iconv = iconv; } Utf16Codec.prototype.encoder = Utf16Encoder; Utf16Codec.prototype.decoder = Utf16Decoder; // -- Encoding (pass-through) function Utf16Encoder(options, codec) { options = options || {}; if (options.addBOM === undefined) options.addBOM = true; this.encoder = codec.iconv.getEncoder('utf-16le', options); } Utf16Encoder.prototype.write = function(str) { return this.encoder.write(str); } Utf16Encoder.prototype.end = function() { return this.encoder.end(); } // -- Decoding function Utf16Decoder(options, codec) { this.decoder = null; this.initialBytes = []; this.initialBytesLen = 0; this.options = options || {}; this.iconv = codec.iconv; } Utf16Decoder.prototype.write = function(buf) { if (!this.decoder) { // Codec is not chosen yet. Accumulate initial bytes. this.initialBytes.push(buf); this.initialBytesLen += buf.length; if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) return ''; // We have enough bytes -> detect endianness. var buf = Buffer.concat(this.initialBytes), encoding = detectEncoding(buf, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); this.initialBytes.length = this.initialBytesLen = 0; } return this.decoder.write(buf); } Utf16Decoder.prototype.end = function() { if (!this.decoder) { var buf = Buffer.concat(this.initialBytes), encoding = detectEncoding(buf, this.options.defaultEncoding); this.decoder = this.iconv.getDecoder(encoding, this.options); var res = this.decoder.write(buf), trail = this.decoder.end(); return trail ? (res + trail) : res; } return this.decoder.end(); } function detectEncoding(buf, defaultEncoding) { var enc = defaultEncoding || 'utf-16le'; if (buf.length >= 2) { // Check BOM. if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM enc = 'utf-16be'; else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM enc = 'utf-16le'; else { // No BOM found. Try to deduce encoding from initial content. // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. // So, we count ASCII as if it was LE or BE, and decide from that. var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. for (var i = 0; i < _len; i += 2) { if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; } if (asciiCharsBE > asciiCharsLE) enc = 'utf-16be'; else if (asciiCharsBE < asciiCharsLE) enc = 'utf-16le'; } } return enc; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/utf16.js
utf16.js
"use strict"; var Buffer = require("safer-buffer").Buffer; // Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that // correspond to encoded bytes (if 128 - then lower half is ASCII). exports._sbcs = SBCSCodec; function SBCSCodec(codecOptions, iconv) { if (!codecOptions) throw new Error("SBCS codec is called without the data.") // Prepare char buffer for decoding. if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); if (codecOptions.chars.length === 128) { var asciiString = ""; for (var i = 0; i < 128; i++) asciiString += String.fromCharCode(i); codecOptions.chars = asciiString + codecOptions.chars; } this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); // Encoding buffer. var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); for (var i = 0; i < codecOptions.chars.length; i++) encodeBuf[codecOptions.chars.charCodeAt(i)] = i; this.encodeBuf = encodeBuf; } SBCSCodec.prototype.encoder = SBCSEncoder; SBCSCodec.prototype.decoder = SBCSDecoder; function SBCSEncoder(options, codec) { this.encodeBuf = codec.encodeBuf; } SBCSEncoder.prototype.write = function(str) { var buf = Buffer.alloc(str.length); for (var i = 0; i < str.length; i++) buf[i] = this.encodeBuf[str.charCodeAt(i)]; return buf; } SBCSEncoder.prototype.end = function() { } function SBCSDecoder(options, codec) { this.decodeBuf = codec.decodeBuf; } SBCSDecoder.prototype.write = function(buf) { // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. var decodeBuf = this.decodeBuf; var newBuf = Buffer.alloc(buf.length*2); var idx1 = 0, idx2 = 0; for (var i = 0; i < buf.length; i++) { idx1 = buf[i]*2; idx2 = i*2; newBuf[idx2] = decodeBuf[idx1]; newBuf[idx2+1] = decodeBuf[idx1+1]; } return newBuf.toString('ucs2'); } SBCSDecoder.prototype.end = function() { }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/sbcs-codec.js
sbcs-codec.js
"use strict"; var Buffer = require("safer-buffer").Buffer; // Multibyte codec. In this scheme, a character is represented by 1 or more bytes. // Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. // To save memory and loading time, we read table files only when requested. exports._dbcs = DBCSCodec; var UNASSIGNED = -1, GB18030_CODE = -2, SEQ_START = -10, NODE_START = -1000, UNASSIGNED_NODE = new Array(0x100), DEF_CHAR = -1; for (var i = 0; i < 0x100; i++) UNASSIGNED_NODE[i] = UNASSIGNED; // Class DBCSCodec reads and initializes mapping tables. function DBCSCodec(codecOptions, iconv) { this.encodingName = codecOptions.encodingName; if (!codecOptions) throw new Error("DBCS codec is called without the data.") if (!codecOptions.table) throw new Error("Encoding '" + this.encodingName + "' has no data."); // Load tables. var mappingTable = codecOptions.table(); // Decode tables: MBCS -> Unicode. // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. // Trie root is decodeTables[0]. // Values: >= 0 -> unicode character code. can be > 0xFFFF // == UNASSIGNED -> unknown/unassigned sequence. // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. // <= NODE_START -> index of the next node in our trie to process next byte. // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. this.decodeTables = []; this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. this.decodeTableSeq = []; // Actual mapping tables consist of chunks. Use them to fill up decode tables. for (var i = 0; i < mappingTable.length; i++) this._addDecodeChunk(mappingTable[i]); this.defaultCharUnicode = iconv.defaultCharUnicode; // Encode tables: Unicode -> DBCS. // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). // == UNASSIGNED -> no conversion found. Output a default char. // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. this.encodeTable = []; // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key // means end of sequence (needed when one sequence is a strict subsequence of another). // Objects are kept separately from encodeTable to increase performance. this.encodeTableSeq = []; // Some chars can be decoded, but need not be encoded. var skipEncodeChars = {}; if (codecOptions.encodeSkipVals) for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { var val = codecOptions.encodeSkipVals[i]; if (typeof val === 'number') skipEncodeChars[val] = true; else for (var j = val.from; j <= val.to; j++) skipEncodeChars[j] = true; } // Use decode trie to recursively fill out encode tables. this._fillEncodeTable(0, 0, skipEncodeChars); // Add more encoding pairs when needed. if (codecOptions.encodeAdd) { for (var uChar in codecOptions.encodeAdd) if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); // Load & create GB18030 tables when needed. if (typeof codecOptions.gb18030 === 'function') { this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. // Add GB18030 decode tables. var thirdByteNodeIdx = this.decodeTables.length; var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); var fourthByteNodeIdx = this.decodeTables.length; var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); for (var i = 0x81; i <= 0xFE; i++) { var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; var secondByteNode = this.decodeTables[secondByteNodeIdx]; for (var j = 0x30; j <= 0x39; j++) secondByteNode[j] = NODE_START - thirdByteNodeIdx; } for (var i = 0x81; i <= 0xFE; i++) thirdByteNode[i] = NODE_START - fourthByteNodeIdx; for (var i = 0x30; i <= 0x39; i++) fourthByteNode[i] = GB18030_CODE } } DBCSCodec.prototype.encoder = DBCSEncoder; DBCSCodec.prototype.decoder = DBCSDecoder; // Decoder helpers DBCSCodec.prototype._getDecodeTrieNode = function(addr) { var bytes = []; for (; addr > 0; addr >>= 8) bytes.push(addr & 0xFF); if (bytes.length == 0) bytes.push(0); var node = this.decodeTables[0]; for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. var val = node[bytes[i]]; if (val == UNASSIGNED) { // Create new node. node[bytes[i]] = NODE_START - this.decodeTables.length; this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } else if (val <= NODE_START) { // Existing node. node = this.decodeTables[NODE_START - val]; } else throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } return node; } DBCSCodec.prototype._addDecodeChunk = function(chunk) { // First element of chunk is the hex mbcs code where we start. var curAddr = parseInt(chunk[0], 16); // Choose the decoding node where we'll write our chars. var writeTable = this._getDecodeTrieNode(curAddr); curAddr = curAddr & 0xFF; // Write all other elements of the chunk to the table. for (var k = 1; k < chunk.length; k++) { var part = chunk[k]; if (typeof part === "string") { // String, write as-is. for (var l = 0; l < part.length;) { var code = part.charCodeAt(l++); if (0xD800 <= code && code < 0xDC00) { // Decode surrogate var codeTrail = part.charCodeAt(l++); if (0xDC00 <= codeTrail && codeTrail < 0xE000) writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); else throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); } else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) var len = 0xFFF - code + 2; var seq = []; for (var m = 0; m < len; m++) seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; this.decodeTableSeq.push(seq); } else writeTable[curAddr++] = code; // Basic char } } else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. var charCode = writeTable[curAddr - 1] + 1; for (var l = 0; l < part; l++) writeTable[curAddr++] = charCode++; } else throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } if (curAddr > 0xFF) throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); } // Encoder helpers DBCSCodec.prototype._getEncodeBucket = function(uCode) { var high = uCode >> 8; // This could be > 0xFF because of astral characters. if (this.encodeTable[high] === undefined) this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. return this.encodeTable[high]; } DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; if (bucket[low] <= SEQ_START) this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. else if (bucket[low] == UNASSIGNED) bucket[low] = dbcsCode; } DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { // Get the root of character tree according to first character of the sequence. var uCode = seq[0]; var bucket = this._getEncodeBucket(uCode); var low = uCode & 0xFF; var node; if (bucket[low] <= SEQ_START) { // There's already a sequence with - use it. node = this.encodeTableSeq[SEQ_START-bucket[low]]; } else { // There was no sequence object - allocate a new one. node = {}; if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. bucket[low] = SEQ_START - this.encodeTableSeq.length; this.encodeTableSeq.push(node); } // Traverse the character tree, allocating new nodes as needed. for (var j = 1; j < seq.length-1; j++) { var oldVal = node[uCode]; if (typeof oldVal === 'object') node = oldVal; else { node = node[uCode] = {} if (oldVal !== undefined) node[DEF_CHAR] = oldVal } } // Set the leaf to given dbcsCode. uCode = seq[seq.length-1]; node[uCode] = dbcsCode; } DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { var node = this.decodeTables[nodeIdx]; for (var i = 0; i < 0x100; i++) { var uCode = node[i]; var mbCode = prefix + i; if (skipEncodeChars[mbCode]) continue; if (uCode >= 0) this._setEncodeChar(uCode, mbCode); else if (uCode <= NODE_START) this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); else if (uCode <= SEQ_START) this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); } } // == Encoder ================================================================== function DBCSEncoder(options, codec) { // Encoder state this.leadSurrogate = -1; this.seqObj = undefined; // Static data this.encodeTable = codec.encodeTable; this.encodeTableSeq = codec.encodeTableSeq; this.defaultCharSingleByte = codec.defCharSB; this.gb18030 = codec.gb18030; } DBCSEncoder.prototype.write = function(str) { var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), leadSurrogate = this.leadSurrogate, seqObj = this.seqObj, nextChar = -1, i = 0, j = 0; while (true) { // 0. Get next character. if (nextChar === -1) { if (i == str.length) break; var uCode = str.charCodeAt(i++); } else { var uCode = nextChar; nextChar = -1; } // 1. Handle surrogates. if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. if (uCode < 0xDC00) { // We've got lead surrogate. if (leadSurrogate === -1) { leadSurrogate = uCode; continue; } else { leadSurrogate = uCode; // Double lead surrogate found. uCode = UNASSIGNED; } } else { // We've got trail surrogate. if (leadSurrogate !== -1) { uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); leadSurrogate = -1; } else { // Incomplete surrogate pair - only trail surrogate found. uCode = UNASSIGNED; } } } else if (leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. leadSurrogate = -1; } // 2. Convert uCode character. var dbcsCode = UNASSIGNED; if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence var resCode = seqObj[uCode]; if (typeof resCode === 'object') { // Sequence continues. seqObj = resCode; continue; } else if (typeof resCode == 'number') { // Sequence finished. Write it. dbcsCode = resCode; } else if (resCode == undefined) { // Current character is not part of the sequence. // Try default character for this sequence resCode = seqObj[DEF_CHAR]; if (resCode !== undefined) { dbcsCode = resCode; // Found. Write it. nextChar = uCode; // Current character will be written too in the next iteration. } else { // TODO: What if we have no default? (resCode == undefined) // Then, we should write first char of the sequence as-is and try the rest recursively. // Didn't do it for now because no encoding has this situation yet. // Currently, just skip the sequence and write current char. } } seqObj = undefined; } else if (uCode >= 0) { // Regular character var subtable = this.encodeTable[uCode >> 8]; if (subtable !== undefined) dbcsCode = subtable[uCode & 0xFF]; if (dbcsCode <= SEQ_START) { // Sequence start seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; continue; } if (dbcsCode == UNASSIGNED && this.gb18030) { // Use GB18030 algorithm to find character(s) to write. var idx = findIdx(this.gb18030.uChars, uCode); if (idx != -1) { var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; newBuf[j++] = 0x30 + dbcsCode; continue; } } } // 3. Write dbcsCode character. if (dbcsCode === UNASSIGNED) dbcsCode = this.defaultCharSingleByte; if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else if (dbcsCode < 0x10000) { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } else { newBuf[j++] = dbcsCode >> 16; newBuf[j++] = (dbcsCode >> 8) & 0xFF; newBuf[j++] = dbcsCode & 0xFF; } } this.seqObj = seqObj; this.leadSurrogate = leadSurrogate; return newBuf.slice(0, j); } DBCSEncoder.prototype.end = function() { if (this.leadSurrogate === -1 && this.seqObj === undefined) return; // All clean. Most often case. var newBuf = Buffer.alloc(10), j = 0; if (this.seqObj) { // We're in the sequence. var dbcsCode = this.seqObj[DEF_CHAR]; if (dbcsCode !== undefined) { // Write beginning of the sequence. if (dbcsCode < 0x100) { newBuf[j++] = dbcsCode; } else { newBuf[j++] = dbcsCode >> 8; // high byte newBuf[j++] = dbcsCode & 0xFF; // low byte } } else { // See todo above. } this.seqObj = undefined; } if (this.leadSurrogate !== -1) { // Incomplete surrogate pair - only lead surrogate found. newBuf[j++] = this.defaultCharSingleByte; this.leadSurrogate = -1; } return newBuf.slice(0, j); } // Export for testing DBCSEncoder.prototype.findIdx = findIdx; // == Decoder ================================================================== function DBCSDecoder(options, codec) { // Decoder state this.nodeIdx = 0; this.prevBuf = Buffer.alloc(0); // Static data this.decodeTables = codec.decodeTables; this.decodeTableSeq = codec.decodeTableSeq; this.defaultCharUnicode = codec.defaultCharUnicode; this.gb18030 = codec.gb18030; } DBCSDecoder.prototype.write = function(buf) { var newBuf = Buffer.alloc(buf.length*2), nodeIdx = this.nodeIdx, prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. uCode; if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); for (var i = 0, j = 0; i < buf.length; i++) { var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; // Lookup in current trie node. var uCode = this.decodeTables[nodeIdx][curByte]; if (uCode >= 0) { // Normal character, just use it. } else if (uCode === UNASSIGNED) { // Unknown char. // TODO: Callback with seq. //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). uCode = this.defaultCharUnicode.charCodeAt(0); } else if (uCode === GB18030_CODE) { var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); var idx = findIdx(this.gb18030.gbChars, ptr); uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; } else if (uCode <= NODE_START) { // Go to next trie node. nodeIdx = NODE_START - uCode; continue; } else if (uCode <= SEQ_START) { // Output a sequence of chars. var seq = this.decodeTableSeq[SEQ_START - uCode]; for (var k = 0; k < seq.length - 1; k++) { uCode = seq[k]; newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; } uCode = seq[seq.length-1]; } else throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); // Write the character to buffer, handling higher planes using surrogate pair. if (uCode > 0xFFFF) { uCode -= 0x10000; var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); newBuf[j++] = uCodeLead & 0xFF; newBuf[j++] = uCodeLead >> 8; uCode = 0xDC00 + uCode % 0x400; } newBuf[j++] = uCode & 0xFF; newBuf[j++] = uCode >> 8; // Reset trie node. nodeIdx = 0; seqStart = i+1; } this.nodeIdx = nodeIdx; this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); return newBuf.slice(0, j).toString('ucs2'); } DBCSDecoder.prototype.end = function() { var ret = ''; // Try to parse all remaining chars. while (this.prevBuf.length > 0) { // Skip 1 character in the buffer. ret += this.defaultCharUnicode; var buf = this.prevBuf.slice(1); // Parse remaining as usual. this.prevBuf = Buffer.alloc(0); this.nodeIdx = 0; if (buf.length > 0) ret += this.write(buf); } this.nodeIdx = 0; return ret; } // Binary search for GB18030. Returns largest i such that table[i] <= val. function findIdx(table, val) { if (table[0] > val) return -1; var l = 0, r = table.length; while (l < r-1) { // always table[l] <= val < table[r] var mid = l + Math.floor((r-l+1)/2); if (table[mid] <= val) l = mid; else r = mid; } return l; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/dbcs-codec.js
dbcs-codec.js
"use strict"; // Description of supported double byte encodings and aliases. // Tables are not require()-d until they are needed to speed up library load. // require()-s are direct to support Browserify. module.exports = { // == Japanese/ShiftJIS ==================================================== // All japanese encodings are based on JIS X set of standards: // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. // Has several variations in 1978, 1983, 1990 and 1997. // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. // 2 planes, first is superset of 0208, second - revised 0212. // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) // Byte encodings are: // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. // 0x00-0x7F - lower part of 0201 // 0x8E, 0xA1-0xDF - upper part of 0201 // (0xA1-0xFE)x2 - 0208 plane (94x94). // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. // Used as-is in ISO2022 family. // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, // 0201-1976 Roman, 0208-1978, 0208-1983. // * ISO2022-JP-1: Adds esc seq for 0212-1990. // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. // // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. // // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html 'shiftjis': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/shiftjis.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, encodeSkipVals: [{from: 0xED40, to: 0xF940}], }, 'csshiftjis': 'shiftjis', 'mskanji': 'shiftjis', 'sjis': 'shiftjis', 'windows31j': 'shiftjis', 'ms31j': 'shiftjis', 'xsjis': 'shiftjis', 'windows932': 'shiftjis', 'ms932': 'shiftjis', '932': 'shiftjis', 'cp932': 'shiftjis', 'eucjp': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/eucjp.json') }, encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, }, // TODO: KDDI extension to Shift_JIS // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. // == Chinese/GBK ========================================================== // http://en.wikipedia.org/wiki/GBK // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 'gb2312': 'cp936', 'gb231280': 'cp936', 'gb23121980': 'cp936', 'csgb2312': 'cp936', 'csiso58gb231280': 'cp936', 'euccn': 'cp936', // Microsoft's CP936 is a subset and approximation of GBK. 'windows936': 'cp936', 'ms936': 'cp936', '936': 'cp936', 'cp936': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp936.json') }, }, // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. 'gbk': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp936.json').concat(require('iconv-lite/encodings/tables/gbk-added.json')) }, }, 'xgbk': 'gbk', 'isoir58': 'gbk', // GB18030 is an algorithmic extension of GBK. // Main source: https://www.w3.org/TR/encoding/#gbk-encoder // http://icu-project.org/docs/papers/gb18030.html // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 'gb18030': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp936.json').concat(require('iconv-lite/encodings/tables/gbk-added.json')) }, gb18030: function() { return require('iconv-lite/encodings/tables/gb18030-ranges.json') }, encodeSkipVals: [0x80], encodeAdd: {'€': 0xA2E3}, }, 'chinese': 'gb18030', // == Korean =============================================================== // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. 'windows949': 'cp949', 'ms949': 'cp949', '949': 'cp949', 'cp949': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp949.json') }, }, 'cseuckr': 'cp949', 'csksc56011987': 'cp949', 'euckr': 'cp949', 'isoir149': 'cp949', 'korean': 'cp949', 'ksc56011987': 'cp949', 'ksc56011989': 'cp949', 'ksc5601': 'cp949', // == Big5/Taiwan/Hong Kong ================================================ // There are lots of tables for Big5 and cp950. Please see the following links for history: // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html // Variations, in roughly number of defined chars: // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ // * Big5-2003 (Taiwan standard) almost superset of cp950. // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. // Plus, it has 4 combining sequences. // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. // Implementations are not consistent within browsers; sometimes labeled as just big5. // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt // // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. 'windows950': 'cp950', 'ms950': 'cp950', '950': 'cp950', 'cp950': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp950.json') }, }, // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. 'big5': 'big5hkscs', 'big5hkscs': { type: '_dbcs', table: function() { return require('iconv-lite/encodings/tables/cp950.json').concat(require('iconv-lite/encodings/tables/big5-added.json')) }, encodeSkipVals: [0xa2cc], }, 'cnbig5': 'big5hkscs', 'csbig5': 'big5hkscs', 'xxbig5': 'big5hkscs', };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/dbcs-data.js
dbcs-data.js
"use strict"; var Buffer = require("safer-buffer").Buffer; // UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 // See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 exports.utf7 = Utf7Codec; exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 function Utf7Codec(codecOptions, iconv) { this.iconv = iconv; }; Utf7Codec.prototype.encoder = Utf7Encoder; Utf7Codec.prototype.decoder = Utf7Decoder; Utf7Codec.prototype.bomAware = true; // -- Encoding var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; function Utf7Encoder(options, codec) { this.iconv = codec.iconv; } Utf7Encoder.prototype.write = function(str) { // Naive implementation. // Non-direct chars are encoded as "+<base64>-"; single "+" char is encoded as "+-". return Buffer.from(str.replace(nonDirectChars, function(chunk) { return "+" + (chunk === '+' ? '' : this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + "-"; }.bind(this))); } Utf7Encoder.prototype.end = function() { } // -- Decoding function Utf7Decoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64Regex = /[A-Za-z0-9\/+]/; var base64Chars = []; for (var i = 0; i < 256; i++) base64Chars[i] = base64Regex.test(String.fromCharCode(i)); var plusChar = '+'.charCodeAt(0), minusChar = '-'.charCodeAt(0), andChar = '&'.charCodeAt(0); Utf7Decoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '+' if (buf[i] == plusChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64Chars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" res += "+"; } else { var b64str = base64Accum + buf.slice(lastI, i).toString(); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus is absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + buf.slice(lastI).toString(); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7Decoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; } // UTF-7-IMAP codec. // RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) // Differences: // * Base64 part is started by "&" instead of "+" // * Direct characters are 0x20-0x7E, except "&" (0x26) // * In Base64, "," is used instead of "/" // * Base64 must not be used to represent direct characters. // * No implicit shift back from Base64 (should always end with '-') // * String must end in non-shifted position. // * "-&" while in base64 is not allowed. exports.utf7imap = Utf7IMAPCodec; function Utf7IMAPCodec(codecOptions, iconv) { this.iconv = iconv; }; Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; Utf7IMAPCodec.prototype.bomAware = true; // -- Encoding function Utf7IMAPEncoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = Buffer.alloc(6); this.base64AccumIdx = 0; } Utf7IMAPEncoder.prototype.write = function(str) { var inBase64 = this.inBase64, base64Accum = this.base64Accum, base64AccumIdx = this.base64AccumIdx, buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; for (var i = 0; i < str.length; i++) { var uChar = str.charCodeAt(i); if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. if (inBase64) { if (base64AccumIdx > 0) { bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. inBase64 = false; } if (!inBase64) { buf[bufIdx++] = uChar; // Write direct character if (uChar === andChar) // Ampersand -> '&-' buf[bufIdx++] = minusChar; } } else { // Non-direct character if (!inBase64) { buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. inBase64 = true; } if (inBase64) { base64Accum[base64AccumIdx++] = uChar >> 8; base64Accum[base64AccumIdx++] = uChar & 0xFF; if (base64AccumIdx == base64Accum.length) { bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); base64AccumIdx = 0; } } } } this.inBase64 = inBase64; this.base64AccumIdx = base64AccumIdx; return buf.slice(0, bufIdx); } Utf7IMAPEncoder.prototype.end = function() { var buf = Buffer.alloc(10), bufIdx = 0; if (this.inBase64) { if (this.base64AccumIdx > 0) { bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); this.base64AccumIdx = 0; } buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. this.inBase64 = false; } return buf.slice(0, bufIdx); } // -- Decoding function Utf7IMAPDecoder(options, codec) { this.iconv = codec.iconv; this.inBase64 = false; this.base64Accum = ''; } var base64IMAPChars = base64Chars.slice(); base64IMAPChars[','.charCodeAt(0)] = true; Utf7IMAPDecoder.prototype.write = function(buf) { var res = "", lastI = 0, inBase64 = this.inBase64, base64Accum = this.base64Accum; // The decoder is more involved as we must handle chunks in stream. // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). for (var i = 0; i < buf.length; i++) { if (!inBase64) { // We're in direct mode. // Write direct chars until '&' if (buf[i] == andChar) { res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. lastI = i+1; inBase64 = true; } } else { // We decode base64. if (!base64IMAPChars[buf[i]]) { // Base64 ended. if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" res += "&"; } else { var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } if (buf[i] != minusChar) // Minus may be absorbed after base64. i--; lastI = i+1; inBase64 = false; base64Accum = ''; } } } if (!inBase64) { res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. } else { var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. b64str = b64str.slice(0, canBeDecoded); res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } this.inBase64 = inBase64; this.base64Accum = base64Accum; return res; } Utf7IMAPDecoder.prototype.end = function() { var res = ""; if (this.inBase64 && this.base64Accum.length > 0) res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); this.inBase64 = false; this.base64Accum = ''; return res; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/iconv-lite/encodings/utf7.js
utf7.js
The MIT License (MIT) Copyright (c) 2016 Sebastian Mayr 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.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tr46/LICENSE.md
LICENSE.md
# tr46 An JavaScript implementation of [Unicode Technical Standard #46: Unicode IDNA Compatibility Processing](https://unicode.org/reports/tr46/). ## Installation [Node.js](http://nodejs.org) ≥ 8 is required. To install, type this at the command line: ```shell npm install tr46 # or yarn add tr46 ``` ## API ### `toASCII(domainName[, options])` Converts a string of Unicode symbols to a case-folded Punycode string of ASCII symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) * [`verifyDNSLength`](#verifyDNSLength) ### `toUnicode(domainName[, options])` Converts a case-folded Punycode string of ASCII symbols to a string of Unicode symbols. Available options: * [`checkBidi`](#checkBidi) * [`checkHyphens`](#checkHyphens) * [`checkJoiners`](#checkJoiners) * [`processingOption`](#processingOption) * [`useSTD3ASCIIRules`](#useSTD3ASCIIRules) ## Options ### `checkBidi` Type: `Boolean` Default value: `false` When set to `true`, any bi-directional text within the input will be checked for validation. ### `checkHyphens` Type: `Boolean` Default value: `false` When set to `true`, the positions of any hyphen characters within the input will be checked for validation. ### `checkJoiners` Type: `Boolean` Default value: `false` When set to `true`, any word joiner characters within the input will be checked for validation. ### `processingOption` Type: `String` Default value: `"nontransitional"` When set to `"transitional"`, symbols within the input will be validated according to the older IDNA2003 protocol. When set to `"nontransitional"`, the current IDNA2008 protocol will be used. ### `useSTD3ASCIIRules` Type: `Boolean` Default value: `false` When set to `true`, input will be validated according to [STD3 Rules](http://unicode.org/reports/tr46/#STD3_Rules). ### `verifyDNSLength` Type: `Boolean` Default value: `false` When set to `true`, the length of each DNS label within the input will be checked for validation.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tr46/README.md
README.md
"use strict"; const punycode = require("punycode"); const regexes = require("tr46/lib/regexes.js"); const mappingTable = require("tr46/lib/mappingTable.json"); const { STATUS_MAPPING } = require("tr46/lib/statusMapping.js"); function containsNonASCII(str) { return /[^\x00-\x7F]/.test(str); } function findStatus(val, { useSTD3ASCIIRules }) { let start = 0; let end = mappingTable.length - 1; while (start <= end) { const mid = Math.floor((start + end) / 2); const target = mappingTable[mid]; const min = Array.isArray(target[0]) ? target[0][0] : target[0]; const max = Array.isArray(target[0]) ? target[0][1] : target[0]; if (min <= val && max >= val) { if (useSTD3ASCIIRules && (target[1] === STATUS_MAPPING.disallowed_STD3_valid || target[1] === STATUS_MAPPING.disallowed_STD3_mapped)) { return [STATUS_MAPPING.disallowed, ...target.slice(2)]; } else if (target[1] === STATUS_MAPPING.disallowed_STD3_valid) { return [STATUS_MAPPING.valid, ...target.slice(2)]; } else if (target[1] === STATUS_MAPPING.disallowed_STD3_mapped) { return [STATUS_MAPPING.mapped, ...target.slice(2)]; } return target.slice(1); } else if (min > val) { end = mid - 1; } else { start = mid + 1; } } return null; } function mapChars(domainName, { useSTD3ASCIIRules, processingOption }) { let hasError = false; let processed = ""; for (const ch of domainName) { const [status, mapping] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); switch (status) { case STATUS_MAPPING.disallowed: hasError = true; processed += ch; break; case STATUS_MAPPING.ignored: break; case STATUS_MAPPING.mapped: processed += mapping; break; case STATUS_MAPPING.deviation: if (processingOption === "transitional") { processed += mapping; } else { processed += ch; } break; case STATUS_MAPPING.valid: processed += ch; break; } } return { string: processed, error: hasError }; } function validateLabel(label, { checkHyphens, checkBidi, checkJoiners, processingOption, useSTD3ASCIIRules }) { if (label.normalize("NFC") !== label) { return false; } const codePoints = Array.from(label); if (checkHyphens) { if ((codePoints[2] === "-" && codePoints[3] === "-") || (label.startsWith("-") || label.endsWith("-"))) { return false; } } if (label.includes(".") || (codePoints.length > 0 && regexes.combiningMarks.test(codePoints[0]))) { return false; } for (const ch of codePoints) { const [status] = findStatus(ch.codePointAt(0), { useSTD3ASCIIRules }); if ((processingOption === "transitional" && status !== STATUS_MAPPING.valid) || (processingOption === "nontransitional" && status !== STATUS_MAPPING.valid && status !== STATUS_MAPPING.deviation)) { return false; } } // https://tools.ietf.org/html/rfc5892#appendix-A if (checkJoiners) { let last = 0; for (const [i, ch] of codePoints.entries()) { if (ch === "\u200C" || ch === "\u200D") { if (i > 0) { if (regexes.combiningClassVirama.test(codePoints[i - 1])) { continue; } if (ch === "\u200C") { // TODO: make this more efficient const next = codePoints.indexOf("\u200C", i + 1); const test = next < 0 ? codePoints.slice(last) : codePoints.slice(last, next); if (regexes.validZWNJ.test(test.join(""))) { last = i + 1; continue; } } } return false; } } } // https://tools.ietf.org/html/rfc5893#section-2 if (checkBidi) { let rtl; // 1 if (regexes.bidiS1LTR.test(codePoints[0])) { rtl = false; } else if (regexes.bidiS1RTL.test(codePoints[0])) { rtl = true; } else { return false; } if (rtl) { // 2-4 if (!regexes.bidiS2.test(label) || !regexes.bidiS3.test(label) || (regexes.bidiS4EN.test(label) && regexes.bidiS4AN.test(label))) { return false; } } else if (!regexes.bidiS5.test(label) || !regexes.bidiS6.test(label)) { // 5-6 return false; } } return true; } function isBidiDomain(labels) { const domain = labels.map(label => { if (label.startsWith("xn--")) { try { return punycode.decode(label.substring(4)); } catch (err) { return ""; } } return label; }).join("."); return regexes.bidiDomain.test(domain); } function processing(domainName, options) { const { processingOption } = options; // 1. Map. let { string, error } = mapChars(domainName, options); // 2. Normalize. string = string.normalize("NFC"); // 3. Break. const labels = string.split("."); const isBidi = isBidiDomain(labels); // 4. Convert/Validate. for (const [i, origLabel] of labels.entries()) { let label = origLabel; let curProcessing = processingOption; if (label.startsWith("xn--")) { try { label = punycode.decode(label.substring(4)); labels[i] = label; } catch (err) { error = true; continue; } curProcessing = "nontransitional"; } // No need to validate if we already know there is an error. if (error) { continue; } const validation = validateLabel(label, Object.assign({}, options, { processingOption: curProcessing, checkBidi: options.checkBidi && isBidi })); if (!validation) { error = true; } } return { string: labels.join("."), error }; } function toASCII(domainName, { checkHyphens = false, checkBidi = false, checkJoiners = false, useSTD3ASCIIRules = false, processingOption = "nontransitional", verifyDNSLength = false } = {}) { if (processingOption !== "transitional" && processingOption !== "nontransitional") { throw new RangeError("processingOption must be either transitional or nontransitional"); } const result = processing(domainName, { processingOption, checkHyphens, checkBidi, checkJoiners, useSTD3ASCIIRules }); let labels = result.string.split("."); labels = labels.map(l => { if (containsNonASCII(l)) { try { return "xn--" + punycode.encode(l); } catch (e) { result.error = true; } } return l; }); if (verifyDNSLength) { const total = labels.join(".").length; if (total > 253 || total === 0) { result.error = true; } for (let i = 0; i < labels.length; ++i) { if (labels[i].length > 63 || labels[i].length === 0) { result.error = true; break; } } } if (result.error) { return null; } return labels.join("."); } function toUnicode(domainName, { checkHyphens = false, checkBidi = false, checkJoiners = false, useSTD3ASCIIRules = false, processingOption = "nontransitional" } = {}) { const result = processing(domainName, { processingOption, checkHyphens, checkBidi, checkJoiners, useSTD3ASCIIRules }); return { domain: result.string, error: result.error }; } module.exports = { toASCII, toUnicode };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tr46/index.js
index.js
"use strict"; const combiningMarks = /[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11000}-\u{11002}\u{11038}-\u{11046}\u{1107F}-\u{11082}\u{110B0}-\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{11134}\u{11145}\u{11146}\u{11173}\u{11180}-\u{11182}\u{111B3}-\u{111C0}\u{111C9}-\u{111CC}\u{1122C}-\u{11237}\u{1123E}\u{112DF}-\u{112EA}\u{11300}-\u{11303}\u{1133B}\u{1133C}\u{1133E}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11357}\u{11362}\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11435}-\u{11446}\u{1145E}\u{114B0}-\u{114C3}\u{115AF}-\u{115B5}\u{115B8}-\u{115C0}\u{115DC}\u{115DD}\u{11630}-\u{11640}\u{116AB}-\u{116B7}\u{1171D}-\u{1172B}\u{1182C}-\u{1183A}\u{119D1}-\u{119D7}\u{119DA}-\u{119E0}\u{119E4}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A39}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A5B}\u{11A8A}-\u{11A99}\u{11C2F}-\u{11C36}\u{11C38}-\u{11C3F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D8A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D97}\u{11EF3}-\u{11EF6}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F51}-\u{16F87}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D165}-\u{1D169}\u{1D16D}-\u{1D172}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]/u; const combiningClassVirama = /[\u094D\u09CD\u0A4D\u0ACD\u0B4D\u0BCD\u0C4D\u0CCD\u0D3B\u0D3C\u0D4D\u0DCA\u0E3A\u0EBA\u0F84\u1039\u103A\u1714\u1734\u17D2\u1A60\u1B44\u1BAA\u1BAB\u1BF2\u1BF3\u2D7F\uA806\uA8C4\uA953\uA9C0\uAAF6\uABED\u{10A3F}\u{11046}\u{1107F}\u{110B9}\u{11133}\u{11134}\u{111C0}\u{11235}\u{112EA}\u{1134D}\u{11442}\u{114C2}\u{115BF}\u{1163F}\u{116B6}\u{1172B}\u{11839}\u{119E0}\u{11A34}\u{11A47}\u{11A99}\u{11C3F}\u{11D44}\u{11D45}\u{11D97}]/u; const validZWNJ = /[\u0620\u0626\u0628\u062A-\u062E\u0633-\u063F\u0641-\u0647\u0649\u064A\u066E\u066F\u0678-\u0687\u069A-\u06BF\u06C1\u06C2\u06CC\u06CE\u06D0\u06D1\u06FA-\u06FC\u06FF\u0712-\u0714\u071A-\u071D\u071F-\u0727\u0729\u072B\u072D\u072E\u074E-\u0758\u075C-\u076A\u076D-\u0770\u0772\u0775-\u0777\u077A-\u077F\u07CA-\u07EA\u0841-\u0845\u0848\u084A-\u0853\u0855\u0860\u0862-\u0865\u0868\u08A0-\u08A9\u08AF\u08B0\u08B3\u08B4\u08B6-\u08B8\u08BA-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA872\u{10AC0}-\u{10AC4}\u{10ACD}\u{10AD3}-\u{10ADC}\u{10ADE}-\u{10AE0}\u{10AEB}-\u{10AEE}\u{10B80}\u{10B82}\u{10B86}-\u{10B88}\u{10B8A}\u{10B8B}\u{10B8D}\u{10B90}\u{10BAD}\u{10BAE}\u{10D00}-\u{10D21}\u{10D23}\u{10F30}-\u{10F32}\u{10F34}-\u{10F44}\u{10F51}-\u{10F53}\u{1E900}-\u{1E943}][\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*\u200C[\xAD\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u061C\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u070F\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CBF\u0CC6\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u200B\u200E\u200F\u202A-\u202E\u2060-\u2064\u206A-\u206F\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\uFEFF\uFFF9-\uFFFB\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C3F}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{13430}-\u{13438}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94B}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*[\u0620\u0622-\u063F\u0641-\u064A\u066E\u066F\u0671-\u0673\u0675-\u06D3\u06D5\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u077F\u07CA-\u07EA\u0840-\u0855\u0860\u0862-\u0865\u0867-\u086A\u08A0-\u08AC\u08AE-\u08B4\u08B6-\u08BD\u1807\u1820-\u1878\u1887-\u18A8\u18AA\uA840-\uA871\u{10AC0}-\u{10AC5}\u{10AC7}\u{10AC9}\u{10ACA}\u{10ACE}-\u{10AD6}\u{10AD8}-\u{10AE1}\u{10AE4}\u{10AEB}-\u{10AEF}\u{10B80}-\u{10B91}\u{10BA9}-\u{10BAE}\u{10D01}-\u{10D23}\u{10F30}-\u{10F44}\u{10F51}-\u{10F54}\u{1E900}-\u{1E943}]/u; const bidiDomain = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; const bidiS1LTR = /[A-Za-z\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u249C-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB67\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11146}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{1145F}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{17000}-\u{187F7}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D800}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]/u; const bidiS1RTL = /[\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u066D-\u066F\u0671-\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u200F\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FE0}-\u{10FF6}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}]/u; const bidiS2 = /^[\0-\x08\x0E-\x1B!-@\[-`\{-\x84\x86-\xA9\xAB-\xB4\xB6-\xB9\xBB-\xBF\xD7\xF7\u02B9\u02BA\u02C2-\u02CF\u02D2-\u02DF\u02E5-\u02ED\u02EF-\u036F\u0374\u0375\u037E\u0384\u0385\u0387\u03F6\u0483-\u0489\u058A\u058D-\u058F\u0591-\u05C7\u05D0-\u05EA\u05EF-\u05F4\u0600-\u061C\u061E-\u070D\u070F-\u074A\u074D-\u07B1\u07C0-\u07FA\u07FD-\u082D\u0830-\u083E\u0840-\u085B\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08D3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09F2\u09F3\u09FB\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AF1\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0BF3-\u0BFA\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C78-\u0C7E\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E3F\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39-\u0F3D\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1390-\u1399\u1400\u169B\u169C\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DB\u17DD\u17F0-\u17F9\u1800-\u180E\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1940\u1944\u1945\u19DE-\u19FF\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u200B-\u200D\u200F-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2070\u2074-\u207E\u2080-\u208E\u20A0-\u20BF\u20D0-\u20F0\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u2150-\u215F\u2189-\u218B\u2190-\u2335\u237B-\u2394\u2396-\u2426\u2440-\u244A\u2460-\u249B\u24EA-\u26AB\u26AD-\u27FF\u2900-\u2B73\u2B76-\u2B95\u2B98-\u2BFF\u2CE5-\u2CEA\u2CEF-\u2CF1\u2CF9-\u2CFF\u2D7F\u2DE0-\u2E4F\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u3004\u3008-\u3020\u302A-\u302D\u3030\u3036\u3037\u303D-\u303F\u3099-\u309C\u30A0\u30FB\u31C0-\u31E3\u321D\u321E\u3250-\u325F\u327C-\u327E\u32B1-\u32BF\u32CC-\u32CF\u3377-\u337A\u33DE\u33DF\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA60D-\uA60F\uA66F-\uA67F\uA69E\uA69F\uA6F0\uA6F1\uA700-\uA721\uA788\uA802\uA806\uA80B\uA825\uA826\uA828-\uA82B\uA838\uA839\uA874-\uA877\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1D-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3F\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFE70-\uFE74\uFE76-\uFEFC\uFEFF\uFF01-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10101}\u{10140}-\u{1018C}\u{10190}-\u{1019B}\u{101A0}\u{101FD}\u{102E0}-\u{102FB}\u{10376}-\u{1037A}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{1091F}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A38}-\u{10A3A}\u{10A3F}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE6}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B39}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D27}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10F00}-\u{10F27}\u{10F30}-\u{10F59}\u{10FE0}-\u{10FF6}\u{11001}\u{11038}-\u{11046}\u{11052}-\u{11065}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{11660}-\u{1166C}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{11FD5}-\u{11FF1}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{16FE2}\u{1BC9D}\u{1BC9E}\u{1BCA0}-\u{1BCA3}\u{1D167}-\u{1D169}\u{1D173}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D200}-\u{1D245}\u{1D300}-\u{1D356}\u{1D6DB}\u{1D715}\u{1D74F}\u{1D789}\u{1D7C3}\u{1D7CE}-\u{1D7FF}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E2FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8D6}\u{1E900}-\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F12F}\u{1F16A}-\u{1F16C}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D5}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6FA}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F90D}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}]*$/u; const bidiS3 = /[0-9\xB2\xB3\xB9\u05BE\u05C0\u05C3\u05C6\u05D0-\u05EA\u05EF-\u05F4\u0600-\u0605\u0608\u060B\u060D\u061B\u061C\u061E-\u064A\u0660-\u0669\u066B-\u066F\u0671-\u06D5\u06DD\u06E5\u06E6\u06EE-\u070D\u070F\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07C0-\u07EA\u07F4\u07F5\u07FA\u07FE-\u0815\u081A\u0824\u0828\u0830-\u083E\u0840-\u0858\u085E\u0860-\u086A\u08A0-\u08B4\u08B6-\u08BD\u08E2\u200F\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBC1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFC\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\u{102E1}-\u{102FB}\u{10800}-\u{10805}\u{10808}\u{1080A}-\u{10835}\u{10837}\u{10838}\u{1083C}\u{1083F}-\u{10855}\u{10857}-\u{1089E}\u{108A7}-\u{108AF}\u{108E0}-\u{108F2}\u{108F4}\u{108F5}\u{108FB}-\u{1091B}\u{10920}-\u{10939}\u{1093F}\u{10980}-\u{109B7}\u{109BC}-\u{109CF}\u{109D2}-\u{10A00}\u{10A10}-\u{10A13}\u{10A15}-\u{10A17}\u{10A19}-\u{10A35}\u{10A40}-\u{10A48}\u{10A50}-\u{10A58}\u{10A60}-\u{10A9F}\u{10AC0}-\u{10AE4}\u{10AEB}-\u{10AF6}\u{10B00}-\u{10B35}\u{10B40}-\u{10B55}\u{10B58}-\u{10B72}\u{10B78}-\u{10B91}\u{10B99}-\u{10B9C}\u{10BA9}-\u{10BAF}\u{10C00}-\u{10C48}\u{10C80}-\u{10CB2}\u{10CC0}-\u{10CF2}\u{10CFA}-\u{10D23}\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}\u{10F00}-\u{10F27}\u{10F30}-\u{10F45}\u{10F51}-\u{10F59}\u{10FE0}-\u{10FF6}\u{1D7CE}-\u{1D7FF}\u{1E800}-\u{1E8C4}\u{1E8C7}-\u{1E8CF}\u{1E900}-\u{1E943}\u{1E94B}\u{1E950}-\u{1E959}\u{1E95E}\u{1E95F}\u{1EC71}-\u{1ECB4}\u{1ED01}-\u{1ED3D}\u{1EE00}-\u{1EE03}\u{1EE05}-\u{1EE1F}\u{1EE21}\u{1EE22}\u{1EE24}\u{1EE27}\u{1EE29}-\u{1EE32}\u{1EE34}-\u{1EE37}\u{1EE39}\u{1EE3B}\u{1EE42}\u{1EE47}\u{1EE49}\u{1EE4B}\u{1EE4D}-\u{1EE4F}\u{1EE51}\u{1EE52}\u{1EE54}\u{1EE57}\u{1EE59}\u{1EE5B}\u{1EE5D}\u{1EE5F}\u{1EE61}\u{1EE62}\u{1EE64}\u{1EE67}-\u{1EE6A}\u{1EE6C}-\u{1EE72}\u{1EE74}-\u{1EE77}\u{1EE79}-\u{1EE7C}\u{1EE7E}\u{1EE80}-\u{1EE89}\u{1EE8B}-\u{1EE9B}\u{1EEA1}-\u{1EEA3}\u{1EEA5}-\u{1EEA9}\u{1EEAB}-\u{1EEBB}\u{1F100}-\u{1F10A}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; const bidiS4EN = /[0-9\xB2\xB3\xB9\u06F0-\u06F9\u2070\u2074-\u2079\u2080-\u2089\u2488-\u249B\uFF10-\uFF19\u{102E1}-\u{102FB}\u{1D7CE}-\u{1D7FF}\u{1F100}-\u{1F10A}]/u; const bidiS4AN = /[\u0600-\u0605\u0660-\u0669\u066B\u066C\u06DD\u08E2\u{10D30}-\u{10D39}\u{10E60}-\u{10E7E}]/u; const bidiS5 = /^[\0-\x08\x0E-\x1B!-\x84\x86-\u0377\u037A-\u037F\u0384-\u038A\u038C\u038E-\u03A1\u03A3-\u052F\u0531-\u0556\u0559-\u058A\u058D-\u058F\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0606\u0607\u0609\u060A\u060C\u060E-\u061A\u064B-\u065F\u066A\u0670\u06D6-\u06DC\u06DE-\u06E4\u06E7-\u06ED\u06F0-\u06F9\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07F6-\u07F9\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09FE\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A76\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AF1\u0AF9-\u0AFF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B77\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BFA\u0C00-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C77-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D00-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D44\u0D46-\u0D48\u0D4A-\u0D4F\u0D54-\u0D63\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E3A\u0E3F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F47\u0F49-\u0F6C\u0F71-\u0F97\u0F99-\u0FBC\u0FBE-\u0FCC\u0FCE-\u0FDA\u1000-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u137C\u1380-\u1399\u13A0-\u13F5\u13F8-\u13FD\u1400-\u167F\u1681-\u169C\u16A0-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1736\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17DD\u17E0-\u17E9\u17F0-\u17F9\u1800-\u180E\u1810-\u1819\u1820-\u1878\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1940\u1944-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u19DE-\u1A1B\u1A1E-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1AB0-\u1ABE\u1B00-\u1B4B\u1B50-\u1B7C\u1B80-\u1BF3\u1BFC-\u1C37\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD0-\u1CFA\u1D00-\u1DF9\u1DFB-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FC4\u1FC6-\u1FD3\u1FD6-\u1FDB\u1FDD-\u1FEF\u1FF2-\u1FF4\u1FF6-\u1FFE\u200B-\u200E\u2010-\u2027\u202F-\u205E\u2060-\u2064\u206A-\u2071\u2074-\u208E\u2090-\u209C\u20A0-\u20BF\u20D0-\u20F0\u2100-\u218B\u2190-\u2426\u2440-\u244A\u2460-\u2B73\u2B76-\u2B95\u2B98-\u2C2E\u2C30-\u2C5E\u2C60-\u2CF3\u2CF9-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2E4F\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3001-\u303F\u3041-\u3096\u3099-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u4DB5\u4DC0-\u9FEF\uA000-\uA48C\uA490-\uA4C6\uA4D0-\uA62B\uA640-\uA6F7\uA700-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA82B\uA830-\uA839\uA840-\uA877\uA880-\uA8C5\uA8CE-\uA8D9\uA8E0-\uA953\uA95F-\uA97C\uA980-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA5C-\uAAC2\uAADB-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB67\uAB70-\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1E\uFB29\uFD3E\uFD3F\uFDFD\uFE00-\uFE19\uFE20-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFEFF\uFF01-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFF9-\uFFFD\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}-\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1018E}\u{10190}-\u{1019B}\u{101A0}\u{101D0}-\u{101FD}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E0}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{1037A}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{1091F}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10B39}-\u{10B3F}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11000}-\u{1104D}\u{11052}-\u{1106F}\u{1107F}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11100}-\u{11134}\u{11136}-\u{11146}\u{11150}-\u{11176}\u{11180}-\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1123E}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112EA}\u{112F0}-\u{112F9}\u{11300}-\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133B}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11400}-\u{11459}\u{1145B}\u{1145D}-\u{1145F}\u{11480}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B5}\u{115B8}-\u{115DD}\u{11600}-\u{11644}\u{11650}-\u{11659}\u{11660}-\u{1166C}\u{11680}-\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{1171D}-\u{1172B}\u{11730}-\u{1173F}\u{11800}-\u{1183B}\u{118A0}-\u{118F2}\u{118FF}\u{119A0}-\u{119A7}\u{119AA}-\u{119D7}\u{119DA}-\u{119E4}\u{11A00}-\u{11A47}\u{11A50}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C36}\u{11C38}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11C92}-\u{11CA7}\u{11CA9}-\u{11CB6}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D47}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D90}\u{11D91}\u{11D93}-\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF8}\u{11FC0}-\u{11FF1}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF0}-\u{16AF5}\u{16B00}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F4F}-\u{16F87}\u{16F8F}-\u{16F9F}\u{16FE0}-\u{16FE3}\u{17000}-\u{187F7}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}-\u{1BCA3}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D1E8}\u{1D200}-\u{1D245}\u{1D2E0}-\u{1D2F3}\u{1D300}-\u{1D356}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D7CB}\u{1D7CE}-\u{1DA8B}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E100}-\u{1E12C}\u{1E130}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2F9}\u{1E2FF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{1EEF0}\u{1EEF1}\u{1F000}-\u{1F02B}\u{1F030}-\u{1F093}\u{1F0A0}-\u{1F0AE}\u{1F0B1}-\u{1F0BF}\u{1F0C1}-\u{1F0CF}\u{1F0D1}-\u{1F0F5}\u{1F100}-\u{1F10C}\u{1F110}-\u{1F16C}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{1F260}-\u{1F265}\u{1F300}-\u{1F6D5}\u{1F6E0}-\u{1F6EC}\u{1F6F0}-\u{1F6FA}\u{1F700}-\u{1F773}\u{1F780}-\u{1F7D8}\u{1F7E0}-\u{1F7EB}\u{1F800}-\u{1F80B}\u{1F810}-\u{1F847}\u{1F850}-\u{1F859}\u{1F860}-\u{1F887}\u{1F890}-\u{1F8AD}\u{1F900}-\u{1F90B}\u{1F90D}-\u{1F971}\u{1F973}-\u{1F976}\u{1F97A}-\u{1F9A2}\u{1F9A5}-\u{1F9AA}\u{1F9AE}-\u{1F9CA}\u{1F9CD}-\u{1FA53}\u{1FA60}-\u{1FA6D}\u{1FA70}-\u{1FA73}\u{1FA78}-\u{1FA7A}\u{1FA80}-\u{1FA82}\u{1FA90}-\u{1FA95}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{E0001}\u{E0020}-\u{E007F}\u{E0100}-\u{E01EF}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}]*$/u; const bidiS6 = /[0-9A-Za-z\xAA\xB2\xB3\xB5\xB9\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u02BB-\u02C1\u02D0\u02D1\u02E0-\u02E4\u02EE\u0370-\u0373\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0482\u048A-\u052F\u0531-\u0556\u0559-\u0589\u06F0-\u06F9\u0903-\u0939\u093B\u093D-\u0940\u0949-\u094C\u094E-\u0950\u0958-\u0961\u0964-\u0980\u0982\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD-\u09C0\u09C7\u09C8\u09CB\u09CC\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E1\u09E6-\u09F1\u09F4-\u09FA\u09FC\u09FD\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3E-\u0A40\u0A59-\u0A5C\u0A5E\u0A66-\u0A6F\u0A72-\u0A74\u0A76\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD-\u0AC0\u0AC9\u0ACB\u0ACC\u0AD0\u0AE0\u0AE1\u0AE6-\u0AF0\u0AF9\u0B02\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B3E\u0B40\u0B47\u0B48\u0B4B\u0B4C\u0B57\u0B5C\u0B5D\u0B5F-\u0B61\u0B66-\u0B77\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE\u0BBF\u0BC1\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCC\u0BD0\u0BD7\u0BE6-\u0BF2\u0C01-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C41-\u0C44\u0C58-\u0C5A\u0C60\u0C61\u0C66-\u0C6F\u0C77\u0C7F\u0C80\u0C82-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD-\u0CC4\u0CC6-\u0CC8\u0CCA\u0CCB\u0CD5\u0CD6\u0CDE\u0CE0\u0CE1\u0CE6-\u0CEF\u0CF1\u0CF2\u0D02\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D40\u0D46-\u0D48\u0D4A-\u0D4C\u0D4E\u0D4F\u0D54-\u0D61\u0D66-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCF-\u0DD1\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2-\u0DF4\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E4F-\u0E5B\u0E81\u0E82\u0E84\u0E86-\u0E8A\u0E8C-\u0EA3\u0EA5\u0EA7-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00-\u0F17\u0F1A-\u0F34\u0F36\u0F38\u0F3E-\u0F47\u0F49-\u0F6C\u0F7F\u0F85\u0F88-\u0F8C\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE-\u0FDA\u1000-\u102C\u1031\u1038\u103B\u103C\u103F-\u1057\u105A-\u105D\u1061-\u1070\u1075-\u1081\u1083\u1084\u1087-\u108C\u108E-\u109C\u109E-\u10C5\u10C7\u10CD\u10D0-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1360-\u137C\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u167F\u1681-\u169A\u16A0-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1735\u1736\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17B6\u17BE-\u17C5\u17C7\u17C8\u17D4-\u17DA\u17DC\u17E0-\u17E9\u1810-\u1819\u1820-\u1878\u1880-\u1884\u1887-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1923-\u1926\u1929-\u192B\u1930\u1931\u1933-\u1938\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A16\u1A19\u1A1A\u1A1E-\u1A55\u1A57\u1A61\u1A63\u1A64\u1A6D-\u1A72\u1A80-\u1A89\u1A90-\u1A99\u1AA0-\u1AAD\u1B04-\u1B33\u1B35\u1B3B\u1B3D-\u1B41\u1B43-\u1B4B\u1B50-\u1B6A\u1B74-\u1B7C\u1B82-\u1BA1\u1BA6\u1BA7\u1BAA\u1BAE-\u1BE5\u1BE7\u1BEA-\u1BEC\u1BEE\u1BF2\u1BF3\u1BFC-\u1C2B\u1C34\u1C35\u1C3B-\u1C49\u1C4D-\u1C88\u1C90-\u1CBA\u1CBD-\u1CC7\u1CD3\u1CE1\u1CE9-\u1CEC\u1CEE-\u1CF3\u1CF5-\u1CF7\u1CFA\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200E\u2070\u2071\u2074-\u2079\u207F-\u2089\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u214F\u2160-\u2188\u2336-\u237A\u2395\u2488-\u24E9\u26AC\u2800-\u28FF\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D70\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u302E\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312F\u3131-\u318E\u3190-\u31BA\u31F0-\u321C\u3220-\u324F\u3260-\u327B\u327F-\u32B0\u32C0-\u32CB\u32D0-\u3376\u337B-\u33DD\u33E0-\u33FE\u3400-\u4DB5\u4E00-\u9FEF\uA000-\uA48C\uA4D0-\uA60C\uA610-\uA62B\uA640-\uA66E\uA680-\uA69D\uA6A0-\uA6EF\uA6F2-\uA6F7\uA722-\uA787\uA789-\uA7BF\uA7C2-\uA7C6\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA824\uA827\uA830-\uA837\uA840-\uA873\uA880-\uA8C3\uA8CE-\uA8D9\uA8F2-\uA8FE\uA900-\uA925\uA92E-\uA946\uA952\uA953\uA95F-\uA97C\uA983-\uA9B2\uA9B4\uA9B5\uA9BA\uA9BB\uA9BE-\uA9CD\uA9CF-\uA9D9\uA9DE-\uA9E4\uA9E6-\uA9FE\uAA00-\uAA28\uAA2F\uAA30\uAA33\uAA34\uAA40-\uAA42\uAA44-\uAA4B\uAA4D\uAA50-\uAA59\uAA5C-\uAA7B\uAA7D-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAAEB\uAAEE-\uAAF5\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB67\uAB70-\uABE4\uABE6\uABE7\uABE9-\uABEC\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uD800-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFF10-\uFF19\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC\u{10000}-\u{1000B}\u{1000D}-\u{10026}\u{10028}-\u{1003A}\u{1003C}\u{1003D}\u{1003F}-\u{1004D}\u{10050}-\u{1005D}\u{10080}-\u{100FA}\u{10100}\u{10102}\u{10107}-\u{10133}\u{10137}-\u{1013F}\u{1018D}\u{1018E}\u{101D0}-\u{101FC}\u{10280}-\u{1029C}\u{102A0}-\u{102D0}\u{102E1}-\u{102FB}\u{10300}-\u{10323}\u{1032D}-\u{1034A}\u{10350}-\u{10375}\u{10380}-\u{1039D}\u{1039F}-\u{103C3}\u{103C8}-\u{103D5}\u{10400}-\u{1049D}\u{104A0}-\u{104A9}\u{104B0}-\u{104D3}\u{104D8}-\u{104FB}\u{10500}-\u{10527}\u{10530}-\u{10563}\u{1056F}\u{10600}-\u{10736}\u{10740}-\u{10755}\u{10760}-\u{10767}\u{11000}\u{11002}-\u{11037}\u{11047}-\u{1104D}\u{11066}-\u{1106F}\u{11082}-\u{110B2}\u{110B7}\u{110B8}\u{110BB}-\u{110C1}\u{110CD}\u{110D0}-\u{110E8}\u{110F0}-\u{110F9}\u{11103}-\u{11126}\u{1112C}\u{11136}-\u{11146}\u{11150}-\u{11172}\u{11174}-\u{11176}\u{11182}-\u{111B5}\u{111BF}-\u{111C8}\u{111CD}\u{111D0}-\u{111DF}\u{111E1}-\u{111F4}\u{11200}-\u{11211}\u{11213}-\u{1122E}\u{11232}\u{11233}\u{11235}\u{11238}-\u{1123D}\u{11280}-\u{11286}\u{11288}\u{1128A}-\u{1128D}\u{1128F}-\u{1129D}\u{1129F}-\u{112A9}\u{112B0}-\u{112DE}\u{112E0}-\u{112E2}\u{112F0}-\u{112F9}\u{11302}\u{11303}\u{11305}-\u{1130C}\u{1130F}\u{11310}\u{11313}-\u{11328}\u{1132A}-\u{11330}\u{11332}\u{11333}\u{11335}-\u{11339}\u{1133D}-\u{1133F}\u{11341}-\u{11344}\u{11347}\u{11348}\u{1134B}-\u{1134D}\u{11350}\u{11357}\u{1135D}-\u{11363}\u{11400}-\u{11437}\u{11440}\u{11441}\u{11445}\u{11447}-\u{11459}\u{1145B}\u{1145D}\u{1145F}\u{11480}-\u{114B2}\u{114B9}\u{114BB}-\u{114BE}\u{114C1}\u{114C4}-\u{114C7}\u{114D0}-\u{114D9}\u{11580}-\u{115B1}\u{115B8}-\u{115BB}\u{115BE}\u{115C1}-\u{115DB}\u{11600}-\u{11632}\u{1163B}\u{1163C}\u{1163E}\u{11641}-\u{11644}\u{11650}-\u{11659}\u{11680}-\u{116AA}\u{116AC}\u{116AE}\u{116AF}\u{116B6}\u{116B8}\u{116C0}-\u{116C9}\u{11700}-\u{1171A}\u{11720}\u{11721}\u{11726}\u{11730}-\u{1173F}\u{11800}-\u{1182E}\u{11838}\u{1183B}\u{118A0}-\u{118F2}\u{118FF}\u{119A0}-\u{119A7}\u{119AA}-\u{119D3}\u{119DC}-\u{119DF}\u{119E1}-\u{119E4}\u{11A00}\u{11A07}\u{11A08}\u{11A0B}-\u{11A32}\u{11A39}\u{11A3A}\u{11A3F}-\u{11A46}\u{11A50}\u{11A57}\u{11A58}\u{11A5C}-\u{11A89}\u{11A97}\u{11A9A}-\u{11AA2}\u{11AC0}-\u{11AF8}\u{11C00}-\u{11C08}\u{11C0A}-\u{11C2F}\u{11C3E}-\u{11C45}\u{11C50}-\u{11C6C}\u{11C70}-\u{11C8F}\u{11CA9}\u{11CB1}\u{11CB4}\u{11D00}-\u{11D06}\u{11D08}\u{11D09}\u{11D0B}-\u{11D30}\u{11D46}\u{11D50}-\u{11D59}\u{11D60}-\u{11D65}\u{11D67}\u{11D68}\u{11D6A}-\u{11D8E}\u{11D93}\u{11D94}\u{11D96}\u{11D98}\u{11DA0}-\u{11DA9}\u{11EE0}-\u{11EF2}\u{11EF5}-\u{11EF8}\u{11FC0}-\u{11FD4}\u{11FFF}-\u{12399}\u{12400}-\u{1246E}\u{12470}-\u{12474}\u{12480}-\u{12543}\u{13000}-\u{1342E}\u{13430}-\u{13438}\u{14400}-\u{14646}\u{16800}-\u{16A38}\u{16A40}-\u{16A5E}\u{16A60}-\u{16A69}\u{16A6E}\u{16A6F}\u{16AD0}-\u{16AED}\u{16AF5}\u{16B00}-\u{16B2F}\u{16B37}-\u{16B45}\u{16B50}-\u{16B59}\u{16B5B}-\u{16B61}\u{16B63}-\u{16B77}\u{16B7D}-\u{16B8F}\u{16E40}-\u{16E9A}\u{16F00}-\u{16F4A}\u{16F50}-\u{16F87}\u{16F93}-\u{16F9F}\u{16FE0}\u{16FE1}\u{16FE3}\u{17000}-\u{187F7}\u{18800}-\u{18AF2}\u{1B000}-\u{1B11E}\u{1B150}-\u{1B152}\u{1B164}-\u{1B167}\u{1B170}-\u{1B2FB}\u{1BC00}-\u{1BC6A}\u{1BC70}-\u{1BC7C}\u{1BC80}-\u{1BC88}\u{1BC90}-\u{1BC99}\u{1BC9C}\u{1BC9F}\u{1D000}-\u{1D0F5}\u{1D100}-\u{1D126}\u{1D129}-\u{1D166}\u{1D16A}-\u{1D172}\u{1D183}\u{1D184}\u{1D18C}-\u{1D1A9}\u{1D1AE}-\u{1D1E8}\u{1D2E0}-\u{1D2F3}\u{1D360}-\u{1D378}\u{1D400}-\u{1D454}\u{1D456}-\u{1D49C}\u{1D49E}\u{1D49F}\u{1D4A2}\u{1D4A5}\u{1D4A6}\u{1D4A9}-\u{1D4AC}\u{1D4AE}-\u{1D4B9}\u{1D4BB}\u{1D4BD}-\u{1D4C3}\u{1D4C5}-\u{1D505}\u{1D507}-\u{1D50A}\u{1D50D}-\u{1D514}\u{1D516}-\u{1D51C}\u{1D51E}-\u{1D539}\u{1D53B}-\u{1D53E}\u{1D540}-\u{1D544}\u{1D546}\u{1D54A}-\u{1D550}\u{1D552}-\u{1D6A5}\u{1D6A8}-\u{1D6DA}\u{1D6DC}-\u{1D714}\u{1D716}-\u{1D74E}\u{1D750}-\u{1D788}\u{1D78A}-\u{1D7C2}\u{1D7C4}-\u{1D7CB}\u{1D7CE}-\u{1D9FF}\u{1DA37}-\u{1DA3A}\u{1DA6D}-\u{1DA74}\u{1DA76}-\u{1DA83}\u{1DA85}-\u{1DA8B}\u{1E100}-\u{1E12C}\u{1E137}-\u{1E13D}\u{1E140}-\u{1E149}\u{1E14E}\u{1E14F}\u{1E2C0}-\u{1E2EB}\u{1E2F0}-\u{1E2F9}\u{1F100}-\u{1F10A}\u{1F110}-\u{1F12E}\u{1F130}-\u{1F169}\u{1F170}-\u{1F1AC}\u{1F1E6}-\u{1F202}\u{1F210}-\u{1F23B}\u{1F240}-\u{1F248}\u{1F250}\u{1F251}\u{20000}-\u{2A6D6}\u{2A700}-\u{2B734}\u{2B740}-\u{2B81D}\u{2B820}-\u{2CEA1}\u{2CEB0}-\u{2EBE0}\u{2F800}-\u{2FA1D}\u{F0000}-\u{FFFFD}\u{100000}-\u{10FFFD}][\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0902\u093A\u093C\u0941-\u0948\u094D\u0951-\u0957\u0962\u0963\u0981\u09BC\u09C1-\u09C4\u09CD\u09E2\u09E3\u09FE\u0A01\u0A02\u0A3C\u0A41\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81\u0A82\u0ABC\u0AC1-\u0AC5\u0AC7\u0AC8\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01\u0B3C\u0B3F\u0B41-\u0B44\u0B4D\u0B56\u0B62\u0B63\u0B82\u0BC0\u0BCD\u0C00\u0C04\u0C3E-\u0C40\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81\u0CBC\u0CCC\u0CCD\u0CE2\u0CE3\u0D00\u0D01\u0D3B\u0D3C\u0D41-\u0D44\u0D4D\u0D62\u0D63\u0DCA\u0DD2-\u0DD4\u0DD6\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F71-\u0F7E\u0F80-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102D-\u1030\u1032-\u1037\u1039\u103A\u103D\u103E\u1058\u1059\u105E-\u1060\u1071-\u1074\u1082\u1085\u1086\u108D\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4\u17B5\u17B7-\u17BD\u17C6\u17C9-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193B\u1A17\u1A18\u1A1B\u1A56\u1A58-\u1A5E\u1A60\u1A62\u1A65-\u1A6C\u1A73-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B03\u1B34\u1B36-\u1B3A\u1B3C\u1B42\u1B6B-\u1B73\u1B80\u1B81\u1BA2-\u1BA5\u1BA8\u1BA9\u1BAB-\u1BAD\u1BE6\u1BE8\u1BE9\u1BED\u1BEF-\u1BF1\u1C2C-\u1C33\u1C36\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE0\u1CE2-\u1CE8\u1CED\u1CF4\u1CF8\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302D\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA825\uA826\uA8C4\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA951\uA980-\uA982\uA9B3\uA9B6-\uA9B9\uA9BC\uA9BD\uA9E5\uAA29-\uAA2E\uAA31\uAA32\uAA35\uAA36\uAA43\uAA4C\uAA7C\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEC\uAAED\uAAF6\uABE5\uABE8\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F\u{101FD}\u{102E0}\u{10376}-\u{1037A}\u{10A01}-\u{10A03}\u{10A05}\u{10A06}\u{10A0C}-\u{10A0F}\u{10A38}-\u{10A3A}\u{10A3F}\u{10AE5}\u{10AE6}\u{10D24}-\u{10D27}\u{10F46}-\u{10F50}\u{11001}\u{11038}-\u{11046}\u{1107F}-\u{11081}\u{110B3}-\u{110B6}\u{110B9}\u{110BA}\u{11100}-\u{11102}\u{11127}-\u{1112B}\u{1112D}-\u{11134}\u{11173}\u{11180}\u{11181}\u{111B6}-\u{111BE}\u{111C9}-\u{111CC}\u{1122F}-\u{11231}\u{11234}\u{11236}\u{11237}\u{1123E}\u{112DF}\u{112E3}-\u{112EA}\u{11300}\u{11301}\u{1133B}\u{1133C}\u{11340}\u{11366}-\u{1136C}\u{11370}-\u{11374}\u{11438}-\u{1143F}\u{11442}-\u{11444}\u{11446}\u{1145E}\u{114B3}-\u{114B8}\u{114BA}\u{114BF}\u{114C0}\u{114C2}\u{114C3}\u{115B2}-\u{115B5}\u{115BC}\u{115BD}\u{115BF}\u{115C0}\u{115DC}\u{115DD}\u{11633}-\u{1163A}\u{1163D}\u{1163F}\u{11640}\u{116AB}\u{116AD}\u{116B0}-\u{116B5}\u{116B7}\u{1171D}-\u{1171F}\u{11722}-\u{11725}\u{11727}-\u{1172B}\u{1182F}-\u{11837}\u{11839}\u{1183A}\u{119D4}-\u{119D7}\u{119DA}\u{119DB}\u{119E0}\u{11A01}-\u{11A06}\u{11A09}\u{11A0A}\u{11A33}-\u{11A38}\u{11A3B}-\u{11A3E}\u{11A47}\u{11A51}-\u{11A56}\u{11A59}-\u{11A5B}\u{11A8A}-\u{11A96}\u{11A98}\u{11A99}\u{11C30}-\u{11C36}\u{11C38}-\u{11C3D}\u{11C92}-\u{11CA7}\u{11CAA}-\u{11CB0}\u{11CB2}\u{11CB3}\u{11CB5}\u{11CB6}\u{11D31}-\u{11D36}\u{11D3A}\u{11D3C}\u{11D3D}\u{11D3F}-\u{11D45}\u{11D47}\u{11D90}\u{11D91}\u{11D95}\u{11D97}\u{11EF3}\u{11EF4}\u{16AF0}-\u{16AF4}\u{16B30}-\u{16B36}\u{16F4F}\u{16F8F}-\u{16F92}\u{1BC9D}\u{1BC9E}\u{1D167}-\u{1D169}\u{1D17B}-\u{1D182}\u{1D185}-\u{1D18B}\u{1D1AA}-\u{1D1AD}\u{1D242}-\u{1D244}\u{1DA00}-\u{1DA36}\u{1DA3B}-\u{1DA6C}\u{1DA75}\u{1DA84}\u{1DA9B}-\u{1DA9F}\u{1DAA1}-\u{1DAAF}\u{1E000}-\u{1E006}\u{1E008}-\u{1E018}\u{1E01B}-\u{1E021}\u{1E023}\u{1E024}\u{1E026}-\u{1E02A}\u{1E130}-\u{1E136}\u{1E2EC}-\u{1E2EF}\u{1E8D0}-\u{1E8D6}\u{1E944}-\u{1E94A}\u{E0100}-\u{E01EF}]*$/u; module.exports = { combiningMarks, combiningClassVirama, validZWNJ, bidiDomain, bidiS1LTR, bidiS1RTL, bidiS2, bidiS3, bidiS4EN, bidiS4AN, bidiS5, bidiS6 };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tr46/lib/regexes.js
regexes.js
# Stealthy-Require [![Build Status](https://img.shields.io/travis/analog-nico/stealthy-require/master.svg?style=flat-square)](https://travis-ci.org/analog-nico/stealthy-require) [![Coverage Status](https://img.shields.io/coveralls/analog-nico/stealthy-require.svg?style=flat-square)](https://coveralls.io/r/analog-nico/stealthy-require) [![Dependency Status](https://img.shields.io/david/analog-nico/stealthy-require.svg?style=flat-square)](https://david-dm.org/analog-nico/stealthy-require) This is probably the closest you can currently get to require something in node.js with completely bypassing the require cache. `stealthy-require` works like this: 1. It clears the require cache. 2. It calls a callback in which you require your module(s) without the cache kicking in. 3. It clears the cache again and restores its old state. The restrictions are: - [Native modules cannot be required twice.](https://github.com/nodejs/node/issues/5016) Thus this module bypasses the require cache only for non-native (e.g. JS) modules. - The require cache is only bypassed for all operations that happen synchronously when a module is required. If a module lazy loads another module at a later time that require call will not bypass the cache anymore. This means you should have a close look at all internal require calls before you decide to use this library. ## Installation [![NPM Stats](https://nodei.co/npm/stealthy-require.png?downloads=true)](https://npmjs.org/package/stealthy-require) This is a module for node.js and is installed via npm: ``` bash npm install stealthy-require --save ``` ## Usage Let's say you want to bypass the require cache for this require call: ``` js var request = require('request'); ``` With `stealthy-require` you can do that like this: ``` js var stealthyRequire = require('stealthy-require'); var requestFresh = stealthyRequire(require.cache, function () { return require('request'); }); ``` The require cache is bypassed for the module you require (i.e. `request`) as well as all modules the module requires (i.e. `http` and many more). Sometimes the require cache shall not be bypassed for specific modules. E.g. `request` is required but `tough-cookie` – on which `request` depends on – shall be required using the regular cache. For that you can pass two extra arguments to `stealthyRequire(...)`: - A callback that requires the modules that shall be required without bypassing the cache - The `module` variable ``` js var stealthyRequire = require('stealthy-require'); var requestFresh = stealthyRequire(require.cache, function () { return require('request'); }, function () { require('tough-cookie'); // No return needed // You can require multiple modules here }, module); ``` ## Usage with Module Bundlers - [Webpack](https://webpack.github.io) works out-of-the-box like described in the [Usage section](#usage) above. - [Browserify](http://browserify.org) does not expose `require.cache`. However, as of `[email protected]` the cache is passed as the 6th argument to CommonJS modules. Thus you can pass this argument instead: ``` js // Tweak for Browserify - using arguments[5] instead of require.cache var requestFresh = stealthyRequire(arguments[5], function () { return require('request'); }); ``` ## Preventing a Memory Leak When Repeatedly Requiring Fresh Module Instances in Node.js If you are using `stealthy-require` in node.js and repeatedly require fresh module instances the `module.children` array will hold all module instances which prevents unneeded instances to be garbage collected. Assume your code calls `doSomething()` repeatedly. ``` js var stealthyRequire = require('stealthy-require'); function doSomething() { var freshInstance = stealthyRequire(require.cache, function () { return require('some-module'); }); return freshInstance.calc(); } ``` After `doSomething()` returns `freshInstance` is not used anymore but won’t be garbage collected because `module.children` still holds a reference. The solution is to truncate `module.children` accordingly: ``` js var stealthyRequire = require('stealthy-require'); function doSomething() { var initialChildren = module.children.slice(); // Creates a shallow copy of the array var freshInstance = stealthyRequire(require.cache, function () { return require('some-module'); }); module.children = initialChildren; return freshInstance.calc(); } ``` The `slice` operation removes all new `module.children` entries created during the `stealthyRequire(...)` call and thus `freshInstance` gets garbage collected after `doSomething()` returns. ## Technical Walkthrough ``` js // 1. Load stealthy-require var stealthyRequire = require('stealthy-require'); // This does nothing but loading the code. // It has no side-effects like patching the module loader or anything. // Any regular require works as always. var request1 = require('request'); // 2. Call stealthyRequire with passing the require cache and a callback. var requestFresh = stealthyRequire(require.cache, function () { // 2a. Before this callback gets called the require cache is cleared. // 2b. Any require taking place here takes place on a clean require cache. // Since the require call is part of the user's code it also works with module bundlers. return require('request'); // Anything returned here will be returned by stealthyRequire(...). // 2c. After this callback gets called the require cache is // - cleared again and // - restored to its old state before step 2. }); // Any regular require again works as always. // In this case require returns the cached request module instance. var request2 = require('request'); // And voilà: request1 === request2 // -> true request1 === requestFresh // -> false ``` ## Contributing To set up your development environment for `stealthy-require`: 1. Clone this repo to your desktop, 2. in the shell `cd` to the main folder, 3. hit `npm install`, 4. hit `npm install gulp -g` if you haven't installed gulp globally yet, and 5. run `gulp dev`. (Or run `node ./node_modules/.bin/gulp dev` if you don't want to install gulp globally.) `gulp dev` watches all source files and if you save some changes it will lint the code and execute all tests. The test coverage report can be viewed from `./coverage/lcov-report/index.html`. If you want to debug a test you should use `gulp test-without-coverage` to run all tests without obscuring the code by the test coverage instrumentation. ## Change History - v1.1.1 (2017-05-08) - Fix that stops `undefined` entries from appearing in `require.cache` *(Thanks to @jasperjn from reporting this in [issue #4](https://github.com/analog-nico/stealthy-require/issues/4))* - v1.1.0 (2017-04-25) - Added ability to disable bypassing the cache for certain modules *(Thanks to @novemberborn for suggesting this in [issue #3](https://github.com/analog-nico/stealthy-require/issues/3))* - Added section in README about a [potential memory leak](#preventing-a-memory-leak-when-repeatedly-requiring-fresh-module-instances-in-nodejs) *(Thanks to @Flarna and @novemberborn for bringing that up in [issue #2](https://github.com/analog-nico/stealthy-require/issues/2))* - Performance optimizations *(Thanks to @jcready for [pull request #1](https://github.com/analog-nico/stealthy-require/pull/1))* - v1.0.0 (2016-07-18) - **Breaking Change:** API completely changed. Please read the [Usage section](#usage) again. - Redesigned library to support module bundlers like [Webpack](https://webpack.github.io) and [Browserify](http://browserify.org) - v0.1.0 (2016-05-26) - Initial version ## License (ISC) In case you never heard about the [ISC license](http://en.wikipedia.org/wiki/ISC_license) it is functionally equivalent to the MIT license. See the [LICENSE file](LICENSE) for details.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/stealthy-require/README.md
README.md
'use strict'; var isNative = /\.node$/; function forEach(obj, callback) { for ( var key in obj ) { if (!Object.prototype.hasOwnProperty.call(obj, key)) { continue; } callback(key); } } function assign(target, source) { forEach(source, function (key) { target[key] = source[key]; }); return target; } function clearCache(requireCache) { forEach(requireCache, function (resolvedPath) { if (!isNative.test(resolvedPath)) { delete requireCache[resolvedPath]; } }); } module.exports = function (requireCache, callback, callbackForModulesToKeep, module) { var originalCache = assign({}, requireCache); clearCache(requireCache); if (callbackForModulesToKeep) { var originalModuleChildren = module.children ? module.children.slice() : false; // Creates a shallow copy of module.children callbackForModulesToKeep(); // Lists the cache entries made by callbackForModulesToKeep() var modulesToKeep = []; forEach(requireCache, function (key) { modulesToKeep.push(key); }); // Discards the modules required in callbackForModulesToKeep() clearCache(requireCache); if (module.children) { // Only true for node.js module.children = originalModuleChildren; // Removes last references to modules required in callbackForModulesToKeep() -> No memory leak } // Takes the cache entries of the original cache in case the modules where required before for ( var i = 0; i < modulesToKeep.length; i+=1 ) { if (originalCache[modulesToKeep[i]]) { requireCache[modulesToKeep[i]] = originalCache[modulesToKeep[i]]; } } } var freshModule = callback(); var stealthCache = callbackForModulesToKeep ? assign({}, requireCache) : false; clearCache(requireCache); if (callbackForModulesToKeep) { // In case modules to keep were required inside the stealthy require for the first time, copy them to the restored cache for ( var k = 0; k < modulesToKeep.length; k+=1 ) { if (stealthCache[modulesToKeep[k]]) { requireCache[modulesToKeep[k]] = stealthCache[modulesToKeep[k]]; } } } assign(requireCache, originalCache); return freshModule; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/stealthy-require/lib/index.js
index.js
# mime-types [![NPM Version][npm-version-image]][npm-url] [![NPM Downloads][npm-downloads-image]][npm-url] [![Node.js Version][node-version-image]][node-version-url] [![Build Status][travis-image]][travis-url] [![Test Coverage][coveralls-image]][coveralls-url] The ultimate javascript content-type utility. Similar to [the `[email protected]` module](https://www.npmjs.com/package/mime), except: - __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`. - No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`. - No `.define()` functionality - Bug fixes for `.lookup(path)` Otherwise, the API is compatible with `mime` 1.x. ## Install This is a [Node.js](https://nodejs.org/en/) module available through the [npm registry](https://www.npmjs.com/). Installation is done using the [`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally): ```sh $ npm install mime-types ``` ## Adding Types All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db), so open a PR there if you'd like to add mime types. ## API <!-- eslint-disable no-unused-vars --> ```js var mime = require('mime-types') ``` All functions return `false` if input is invalid or not found. ### mime.lookup(path) Lookup the content-type associated with a file. <!-- eslint-disable no-undef --> ```js mime.lookup('json') // 'application/json' mime.lookup('.md') // 'text/markdown' mime.lookup('file.html') // 'text/html' mime.lookup('folder/file.js') // 'application/javascript' mime.lookup('folder/.htaccess') // false mime.lookup('cats') // false ``` ### mime.contentType(type) Create a full content-type header given a content-type or extension. When given an extension, `mime.lookup` is used to get the matching content-type, otherwise the given content-type is used. Then if the content-type does not already have a `charset` parameter, `mime.charset` is used to get the default charset and add to the returned content-type. <!-- eslint-disable no-undef --> ```js mime.contentType('markdown') // 'text/x-markdown; charset=utf-8' mime.contentType('file.json') // 'application/json; charset=utf-8' mime.contentType('text/html') // 'text/html; charset=utf-8' mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1' // from a full path mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8' ``` ### mime.extension(type) Get the default extension for a content-type. <!-- eslint-disable no-undef --> ```js mime.extension('application/octet-stream') // 'bin' ``` ### mime.charset(type) Lookup the implied default charset of a content-type. <!-- eslint-disable no-undef --> ```js mime.charset('text/markdown') // 'UTF-8' ``` ### var type = mime.types[extension] A map of content-types by extension. ### [extensions...] = mime.extensions[type] A map of extensions by content-type. ## License [MIT](LICENSE) [coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master [coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master [node-version-image]: https://badgen.net/npm/node/mime-types [node-version-url]: https://nodejs.org/en/download [npm-downloads-image]: https://badgen.net/npm/dm/mime-types [npm-url]: https://npmjs.org/package/mime-types [npm-version-image]: https://badgen.net/npm/v/mime-types [travis-image]: https://badgen.net/travis/jshttp/mime-types/master [travis-url]: https://travis-ci.org/jshttp/mime-types
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/mime-types/README.md
README.md
'use strict' /** * Module dependencies. * @private */ var db = require('mime-db') var extname = require('path').extname /** * Module variables. * @private */ var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ var TEXT_TYPE_REGEXP = /^text\//i /** * Module exports. * @public */ exports.charset = charset exports.charsets = { lookup: charset } exports.contentType = contentType exports.extension = extension exports.extensions = Object.create(null) exports.lookup = lookup exports.types = Object.create(null) // Populate the extensions/types maps populateMaps(exports.extensions, exports.types) /** * Get the default charset for a MIME type. * * @param {string} type * @return {boolean|string} */ function charset (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) var mime = match && db[match[1].toLowerCase()] if (mime && mime.charset) { return mime.charset } // default text/* to utf-8 if (match && TEXT_TYPE_REGEXP.test(match[1])) { return 'UTF-8' } return false } /** * Create a full Content-Type header given a MIME type or extension. * * @param {string} str * @return {boolean|string} */ function contentType (str) { // TODO: should this even be in this module? if (!str || typeof str !== 'string') { return false } var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str if (!mime) { return false } // TODO: use content-type or other module if (mime.indexOf('charset') === -1) { var charset = exports.charset(mime) if (charset) mime += '; charset=' + charset.toLowerCase() } return mime } /** * Get the default extension for a MIME type. * * @param {string} type * @return {boolean|string} */ function extension (type) { if (!type || typeof type !== 'string') { return false } // TODO: use media-typer var match = EXTRACT_TYPE_REGEXP.exec(type) // get extensions var exts = match && exports.extensions[match[1].toLowerCase()] if (!exts || !exts.length) { return false } return exts[0] } /** * Lookup the MIME type for a file path/extension. * * @param {string} path * @return {boolean|string} */ function lookup (path) { if (!path || typeof path !== 'string') { return false } // get the extension ("ext" or ".ext" or full path) var extension = extname('x.' + path) .toLowerCase() .substr(1) if (!extension) { return false } return exports.types[extension] || false } /** * Populate the extensions and types maps. * @private */ function populateMaps (extensions, types) { // source preference (least -> most) var preference = ['nginx', 'apache', undefined, 'iana'] Object.keys(db).forEach(function forEachMimeType (type) { var mime = db[type] var exts = mime.extensions if (!exts || !exts.length) { return } // mime -> extensions extensions[type] = exts // extension -> mime for (var i = 0; i < exts.length; i++) { var extension = exts[i] if (types[extension]) { var from = preference.indexOf(db[types[extension]].source) var to = preference.indexOf(mime.source) if (types[extension] !== 'application/octet-stream' && (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { // skip the remapping continue } } // set the extension -> mime types[extension] = type } }) }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/mime-types/index.js
index.js
2.1.27 / 2020-04-23 =================== * deps: [email protected] - Add charsets from IANA - Add extension `.cjs` to `application/node` - Add new upstream MIME types 2.1.26 / 2020-01-05 =================== * deps: [email protected] - Add `application/x-keepass2` with extension `.kdbx` - Add extension `.mxmf` to `audio/mobile-xmf` - Add extensions from IANA for `application/*+xml` types - Add new upstream MIME types 2.1.25 / 2019-11-12 =================== * deps: [email protected] - Add new upstream MIME types - Add `application/toml` with extension `.toml` - Add `image/vnd.ms-dds` with extension `.dds` 2.1.24 / 2019-04-20 =================== * deps: [email protected] - Add extensions from IANA for `model/*` types - Add `text/mdx` with extension `.mdx` 2.1.23 / 2019-04-17 =================== * deps: mime-db@~1.39.0 - Add extensions `.siv` and `.sieve` to `application/sieve` - Add new upstream MIME types 2.1.22 / 2019-02-14 =================== * deps: mime-db@~1.38.0 - Add extension `.nq` to `application/n-quads` - Add extension `.nt` to `application/n-triples` - Add new upstream MIME types - Mark `text/less` as compressible 2.1.21 / 2018-10-19 =================== * deps: mime-db@~1.37.0 - Add extensions to HEIC image types - Add new upstream MIME types 2.1.20 / 2018-08-26 =================== * deps: mime-db@~1.36.0 - Add Apple file extensions from IANA - Add extensions from IANA for `image/*` types - Add new upstream MIME types 2.1.19 / 2018-07-17 =================== * deps: mime-db@~1.35.0 - Add extension `.csl` to `application/vnd.citationstyles.style+xml` - Add extension `.es` to `application/ecmascript` - Add extension `.owl` to `application/rdf+xml` - Add new upstream MIME types - Add UTF-8 as default charset for `text/turtle` 2.1.18 / 2018-02-16 =================== * deps: mime-db@~1.33.0 - Add `application/raml+yaml` with extension `.raml` - Add `application/wasm` with extension `.wasm` - Add `text/shex` with extension `.shex` - Add extensions for JPEG-2000 images - Add extensions from IANA for `message/*` types - Add new upstream MIME types - Update font MIME types - Update `text/hjson` to registered `application/hjson` 2.1.17 / 2017-09-01 =================== * deps: mime-db@~1.30.0 - Add `application/vnd.ms-outlook` - Add `application/x-arj` - Add extension `.mjs` to `application/javascript` - Add glTF types and extensions - Add new upstream MIME types - Add `text/x-org` - Add VirtualBox MIME types - Fix `source` records for `video/*` types that are IANA - Update `font/opentype` to registered `font/otf` 2.1.16 / 2017-07-24 =================== * deps: mime-db@~1.29.0 - Add `application/fido.trusted-apps+json` - Add extension `.wadl` to `application/vnd.sun.wadl+xml` - Add extension `.gz` to `application/gzip` - Add new upstream MIME types - Update extensions `.md` and `.markdown` to be `text/markdown` 2.1.15 / 2017-03-23 =================== * deps: mime-db@~1.27.0 - Add new mime types - Add `image/apng` 2.1.14 / 2017-01-14 =================== * deps: mime-db@~1.26.0 - Add new mime types 2.1.13 / 2016-11-18 =================== * deps: mime-db@~1.25.0 - Add new mime types 2.1.12 / 2016-09-18 =================== * deps: mime-db@~1.24.0 - Add new mime types - Add `audio/mp3` 2.1.11 / 2016-05-01 =================== * deps: mime-db@~1.23.0 - Add new mime types 2.1.10 / 2016-02-15 =================== * deps: mime-db@~1.22.0 - Add new mime types - Fix extension of `application/dash+xml` - Update primary extension for `audio/mp4` 2.1.9 / 2016-01-06 ================== * deps: mime-db@~1.21.0 - Add new mime types 2.1.8 / 2015-11-30 ================== * deps: mime-db@~1.20.0 - Add new mime types 2.1.7 / 2015-09-20 ================== * deps: mime-db@~1.19.0 - Add new mime types 2.1.6 / 2015-09-03 ================== * deps: mime-db@~1.18.0 - Add new mime types 2.1.5 / 2015-08-20 ================== * deps: mime-db@~1.17.0 - Add new mime types 2.1.4 / 2015-07-30 ================== * deps: mime-db@~1.16.0 - Add new mime types 2.1.3 / 2015-07-13 ================== * deps: mime-db@~1.15.0 - Add new mime types 2.1.2 / 2015-06-25 ================== * deps: mime-db@~1.14.0 - Add new mime types 2.1.1 / 2015-06-08 ================== * perf: fix deopt during mapping 2.1.0 / 2015-06-07 ================== * Fix incorrectly treating extension-less file name as extension - i.e. `'path/to/json'` will no longer return `application/json` * Fix `.charset(type)` to accept parameters * Fix `.charset(type)` to match case-insensitive * Improve generation of extension to MIME mapping * Refactor internals for readability and no argument reassignment * Prefer `application/*` MIME types from the same source * Prefer any type over `application/octet-stream` * deps: mime-db@~1.13.0 - Add nginx as a source - Add new mime types 2.0.14 / 2015-06-06 =================== * deps: mime-db@~1.12.0 - Add new mime types 2.0.13 / 2015-05-31 =================== * deps: mime-db@~1.11.0 - Add new mime types 2.0.12 / 2015-05-19 =================== * deps: mime-db@~1.10.0 - Add new mime types 2.0.11 / 2015-05-05 =================== * deps: mime-db@~1.9.1 - Add new mime types 2.0.10 / 2015-03-13 =================== * deps: mime-db@~1.8.0 - Add new mime types 2.0.9 / 2015-02-09 ================== * deps: mime-db@~1.7.0 - Add new mime types - Community extensions ownership transferred from `node-mime` 2.0.8 / 2015-01-29 ================== * deps: mime-db@~1.6.0 - Add new mime types 2.0.7 / 2014-12-30 ================== * deps: mime-db@~1.5.0 - Add new mime types - Fix various invalid MIME type entries 2.0.6 / 2014-12-30 ================== * deps: mime-db@~1.4.0 - Add new mime types - Fix various invalid MIME type entries - Remove example template MIME types 2.0.5 / 2014-12-29 ================== * deps: mime-db@~1.3.1 - Fix missing extensions 2.0.4 / 2014-12-10 ================== * deps: mime-db@~1.3.0 - Add new mime types 2.0.3 / 2014-11-09 ================== * deps: mime-db@~1.2.0 - Add new mime types 2.0.2 / 2014-09-28 ================== * deps: mime-db@~1.1.0 - Add new mime types - Add additional compressible - Update charsets 2.0.1 / 2014-09-07 ================== * Support Node.js 0.6 2.0.0 / 2014-09-02 ================== * Use `mime-db` * Remove `.define()` 1.0.2 / 2014-08-04 ================== * Set charset=utf-8 for `text/javascript` 1.0.1 / 2014-06-24 ================== * Add `text/jsx` type 1.0.0 / 2014-05-12 ================== * Return `false` for unknown types * Set charset=utf-8 for `application/json` 0.1.0 / 2014-05-02 ================== * Initial release
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/mime-types/HISTORY.md
HISTORY.md
Copyright © 2019 W3C and Jeff Carpenter \<[email protected]\> Both the original source code and new contributions in this repository are released under the [3-Clause BSD license](https://opensource.org/licenses/BSD-3-Clause). # The 3-Clause BSD License 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 the copyright holder 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.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/abab/LICENSE.md
LICENSE.md
# abab [![npm version](https://badge.fury.io/js/abab.svg)](https://www.npmjs.com/package/abab) [![Build Status](https://travis-ci.org/jsdom/abab.svg?branch=master)](https://travis-ci.org/jsdom/abab) A JavaScript module that implements `window.atob` and `window.btoa` according the forgiving-base64 algorithm in the [Infra Standard](https://infra.spec.whatwg.org/#forgiving-base64). The original code was forked from [w3c/web-platform-tests](https://github.com/w3c/web-platform-tests/blob/master/html/webappapis/atob/base64.html). Compatibility: Node.js version 3+ and all major browsers. Install with `npm`: ```sh npm install abab ``` ## API ### `btoa` (base64 encode) ```js const { btoa } = require('abab'); btoa('Hello, world!'); // 'SGVsbG8sIHdvcmxkIQ==' ``` ### `atob` (base64 decode) ```js const { atob } = require('abab'); atob('SGVsbG8sIHdvcmxkIQ=='); // 'Hello, world!' ``` #### Valid characters [Per the spec](https://html.spec.whatwg.org/multipage/webappapis.html#atob:dom-windowbase64-btoa-3), `btoa` will accept strings "containing only characters in the range `U+0000` to `U+00FF`." If passed a string with characters above `U+00FF`, `btoa` will return `null`. If `atob` is passed a string that is not base64-valid, it will also return `null`. In both cases when `null` is returned, the spec calls for throwing a `DOMException` of type `InvalidCharacterError`. ## Browsers If you want to include just one of the methods to save bytes in your client-side code, you can `require` the desired module directly. ```js const atob = require('abab/lib/atob'); const btoa = require('abab/lib/btoa'); ``` ----- ### Checklists If you're **submitting a PR** or **deploying to npm**, please use the [checklists in CONTRIBUTING.md](https://github.com/jsdom/abab/blob/master/CONTRIBUTING.md#checklists) ### Remembering `atob` vs. `btoa` Here's a mnemonic that might be useful: if you have a plain string and want to base64 encode it, then decode it, `btoa` is what you run before (**b**efore - **b**toa), and `atob` is what you run after (**a**fter - **a**tob).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/abab/README.md
README.md
## 2.0.3 - Use standard wording for BSD-3-Clause license (@PhilippWendler) ## 2.0.2 - Correct license in `package.json` (@Haegin) ## 2.0.1 - Add TypeScript type definitions, thanks to @LinusU ## 2.0.0 Modernization updates thanks to @TimothyGu: - Use jsdom's eslint config, remove jscs - Move syntax to ES6 - Remove Babel - Via: https://github.com/jsdom/abab/pull/26 ## 1.0.4 - Added license file ## 1.0.3 - Replaced `let` with `var` in `lib/btoa.js` - Follow up from `1.0.2` - Resolves https://github.com/jsdom/abab/issues/18 ## 1.0.2 - Replaced `const` with `var` in `index.js` - Allows use of `abab` in the browser without a transpilation step - Resolves https://github.com/jsdom/abab/issues/15
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/abab/CHANGELOG.md
CHANGELOG.md
"use strict"; /** * Implementation of atob() according to the HTML and Infra specs, except that * instead of throwing INVALID_CHARACTER_ERR we return null. */ function atob(data) { // Web IDL requires DOMStrings to just be converted using ECMAScript // ToString, which in our case amounts to using a template literal. data = `${data}`; // "Remove all ASCII whitespace from data." data = data.replace(/[ \t\n\f\r]/g, ""); // "If data's length divides by 4 leaving no remainder, then: if data ends // with one or two U+003D (=) code points, then remove them from data." if (data.length % 4 === 0) { data = data.replace(/==?$/, ""); } // "If data's length divides by 4 leaving a remainder of 1, then return // failure." // // "If data contains a code point that is not one of // // U+002B (+) // U+002F (/) // ASCII alphanumeric // // then return failure." if (data.length % 4 === 1 || /[^+/0-9A-Za-z]/.test(data)) { return null; } // "Let output be an empty byte sequence." let output = ""; // "Let buffer be an empty buffer that can have bits appended to it." // // We append bits via left-shift and or. accumulatedBits is used to track // when we've gotten to 24 bits. let buffer = 0; let accumulatedBits = 0; // "Let position be a position variable for data, initially pointing at the // start of data." // // "While position does not point past the end of data:" for (let i = 0; i < data.length; i++) { // "Find the code point pointed to by position in the second column of // Table 1: The Base 64 Alphabet of RFC 4648. Let n be the number given in // the first cell of the same row. // // "Append to buffer the six bits corresponding to n, most significant bit // first." // // atobLookup() implements the table from RFC 4648. buffer <<= 6; buffer |= atobLookup(data[i]); accumulatedBits += 6; // "If buffer has accumulated 24 bits, interpret them as three 8-bit // big-endian numbers. Append three bytes with values equal to those // numbers to output, in the same order, and then empty buffer." if (accumulatedBits === 24) { output += String.fromCharCode((buffer & 0xff0000) >> 16); output += String.fromCharCode((buffer & 0xff00) >> 8); output += String.fromCharCode(buffer & 0xff); buffer = accumulatedBits = 0; } // "Advance position by 1." } // "If buffer is not empty, it contains either 12 or 18 bits. If it contains // 12 bits, then discard the last four and interpret the remaining eight as // an 8-bit big-endian number. If it contains 18 bits, then discard the last // two and interpret the remaining 16 as two 8-bit big-endian numbers. Append // the one or two bytes with values equal to those one or two numbers to // output, in the same order." if (accumulatedBits === 12) { buffer >>= 4; output += String.fromCharCode(buffer); } else if (accumulatedBits === 18) { buffer >>= 2; output += String.fromCharCode((buffer & 0xff00) >> 8); output += String.fromCharCode(buffer & 0xff); } // "Return output." return output; } /** * A lookup table for atob(), which converts an ASCII character to the * corresponding six-bit number. */ function atobLookup(chr) { if (/[A-Z]/.test(chr)) { return chr.charCodeAt(0) - "A".charCodeAt(0); } if (/[a-z]/.test(chr)) { return chr.charCodeAt(0) - "a".charCodeAt(0) + 26; } if (/[0-9]/.test(chr)) { return chr.charCodeAt(0) - "0".charCodeAt(0) + 52; } if (chr === "+") { return 62; } if (chr === "/") { return 63; } // Throw exception; should not be hit in tests return undefined; } module.exports = atob;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/abab/lib/atob.js
atob.js
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define([], function () { return factory(); }); } else if (typeof module === 'object' && module.exports) { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals root.jsonSchema = factory(); } }(this, function () {// setup primitive classes to be JSON Schema types var exports = validate exports.Integer = {type:"integer"}; var primitiveConstructors = { String: String, Boolean: Boolean, Number: Number, Object: Object, Array: Array, Date: Date } exports.validate = validate; function validate(/*Any*/instance,/*Object*/schema) { // Summary: // To use the validator call JSONSchema.validate with an instance object and an optional schema object. // If a schema is provided, it will be used to validate. If the instance object refers to a schema (self-validating), // that schema will be used to validate and the schema parameter is not necessary (if both exist, // both validations will occur). // The validate method will return an object with two properties: // valid: A boolean indicating if the instance is valid by the schema // errors: An array of validation errors. If there are no errors, then an // empty list will be returned. A validation error will have two properties: // property: which indicates which property had the error // message: which indicates what the error was // return validate(instance, schema, {changing: false});//, coerce: false, existingOnly: false}); }; exports.checkPropertyChange = function(/*Any*/value,/*Object*/schema, /*String*/property) { // Summary: // The checkPropertyChange method will check to see if an value can legally be in property with the given schema // This is slightly different than the validate method in that it will fail if the schema is readonly and it will // not check for self-validation, it is assumed that the passed in value is already internally valid. // The checkPropertyChange method will return the same object type as validate, see JSONSchema.validate for // information. // return validate(value, schema, {changing: property || "property"}); }; var validate = exports._validate = function(/*Any*/instance,/*Object*/schema,/*Object*/options) { if (!options) options = {}; var _changing = options.changing; function getType(schema){ return schema.type || (primitiveConstructors[schema.name] == schema && schema.name.toLowerCase()); } var errors = []; // validate a value against a property definition function checkProp(value, schema, path,i){ var l; path += path ? typeof i == 'number' ? '[' + i + ']' : typeof i == 'undefined' ? '' : '.' + i : i; function addError(message){ errors.push({property:path,message:message}); } if((typeof schema != 'object' || schema instanceof Array) && (path || typeof schema != 'function') && !(schema && getType(schema))){ if(typeof schema == 'function'){ if(!(value instanceof schema)){ addError("is not an instance of the class/constructor " + schema.name); } }else if(schema){ addError("Invalid schema/property definition " + schema); } return null; } if(_changing && schema.readonly){ addError("is a readonly field, it can not be changed"); } if(schema['extends']){ // if it extends another schema, it must pass that schema as well checkProp(value,schema['extends'],path,i); } // validate a value against a type definition function checkType(type,value){ if(type){ if(typeof type == 'string' && type != 'any' && (type == 'null' ? value !== null : typeof value != type) && !(value instanceof Array && type == 'array') && !(value instanceof Date && type == 'date') && !(type == 'integer' && value%1===0)){ return [{property:path,message:(typeof value) + " value found, but a " + type + " is required"}]; } if(type instanceof Array){ var unionErrors=[]; for(var j = 0; j < type.length; j++){ // a union type if(!(unionErrors=checkType(type[j],value)).length){ break; } } if(unionErrors.length){ return unionErrors; } }else if(typeof type == 'object'){ var priorErrors = errors; errors = []; checkProp(value,type,path); var theseErrors = errors; errors = priorErrors; return theseErrors; } } return []; } if(value === undefined){ if(schema.required){ addError("is missing and it is required"); } }else{ errors = errors.concat(checkType(getType(schema),value)); if(schema.disallow && !checkType(schema.disallow,value).length){ addError(" disallowed value was matched"); } if(value !== null){ if(value instanceof Array){ if(schema.items){ var itemsIsArray = schema.items instanceof Array; var propDef = schema.items; for (i = 0, l = value.length; i < l; i += 1) { if (itemsIsArray) propDef = schema.items[i]; if (options.coerce) value[i] = options.coerce(value[i], propDef); errors.concat(checkProp(value[i],propDef,path,i)); } } if(schema.minItems && value.length < schema.minItems){ addError("There must be a minimum of " + schema.minItems + " in the array"); } if(schema.maxItems && value.length > schema.maxItems){ addError("There must be a maximum of " + schema.maxItems + " in the array"); } }else if(schema.properties || schema.additionalProperties){ errors.concat(checkObj(value, schema.properties, path, schema.additionalProperties)); } if(schema.pattern && typeof value == 'string' && !value.match(schema.pattern)){ addError("does not match the regex pattern " + schema.pattern); } if(schema.maxLength && typeof value == 'string' && value.length > schema.maxLength){ addError("may only be " + schema.maxLength + " characters long"); } if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){ addError("must be at least " + schema.minLength + " characters long"); } if(typeof schema.minimum !== undefined && typeof value == typeof schema.minimum && schema.minimum > value){ addError("must have a minimum value of " + schema.minimum); } if(typeof schema.maximum !== undefined && typeof value == typeof schema.maximum && schema.maximum < value){ addError("must have a maximum value of " + schema.maximum); } if(schema['enum']){ var enumer = schema['enum']; l = enumer.length; var found; for(var j = 0; j < l; j++){ if(enumer[j]===value){ found=1; break; } } if(!found){ addError("does not have a value in the enumeration " + enumer.join(", ")); } } if(typeof schema.maxDecimal == 'number' && (value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){ addError("may only have " + schema.maxDecimal + " digits of decimal places"); } } } return null; } // validate an object against a schema function checkObj(instance,objTypeDef,path,additionalProp){ if(typeof objTypeDef =='object'){ if(typeof instance != 'object' || instance instanceof Array){ errors.push({property:path,message:"an object is required"}); } for(var i in objTypeDef){ if(objTypeDef.hasOwnProperty(i)){ var value = instance[i]; // skip _not_ specified properties if (value === undefined && options.existingOnly) continue; var propDef = objTypeDef[i]; // set default if(value === undefined && propDef["default"]){ value = instance[i] = propDef["default"]; } if(options.coerce && i in instance){ value = instance[i] = options.coerce(value, propDef); } checkProp(value,propDef,path,i); } } } for(i in instance){ if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){ if (options.filter) { delete instance[i]; continue; } else { errors.push({property:path,message:(typeof value) + "The property " + i + " is not defined in the schema and the schema does not allow additional properties"}); } } var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires; if(requires && !(requires in instance)){ errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"}); } value = instance[i]; if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){ if(options.coerce){ value = instance[i] = options.coerce(value, additionalProp); } checkProp(value,additionalProp,path,i); } if(!_changing && value && value.$schema){ errors = errors.concat(checkProp(value,value.$schema,path,i)); } } return errors; } if(schema){ checkProp(instance,schema,'',_changing || ''); } if(!_changing && instance && instance.$schema){ checkProp(instance,instance.$schema,'',''); } return {valid:!errors.length,errors:errors}; }; exports.mustBeValid = function(result){ // summary: // This checks to ensure that the result is valid and will throw an appropriate error message if it is not // result: the result returned from checkPropertyChange or validate if(!result.valid){ throw new TypeError(result.errors.map(function(error){return "for property " + error.property + ': ' + error.message;}).join(", \n")); } } return exports; }));
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/json-schema/lib/validate.js
validate.js
'use strict' var http = require('http') var https = require('https') var url = require('url') var util = require('util') var stream = require('stream') var zlib = require('zlib') var aws2 = require('aws-sign2') var aws4 = require('aws4') var httpSignature = require('http-signature') var mime = require('mime-types') var caseless = require('caseless') var ForeverAgent = require('forever-agent') var FormData = require('form-data') var extend = require('extend') var isstream = require('isstream') var isTypedArray = require('is-typedarray').strict var helpers = require('request/lib/helpers') var cookies = require('request/lib/cookies') var getProxyFromURI = require('request/lib/getProxyFromURI') var Querystring = require('request/lib/querystring').Querystring var Har = require('request/lib/har').Har var Auth = require('request/lib/auth').Auth var OAuth = require('request/lib/oauth').OAuth var hawk = require('request/lib/hawk') var Multipart = require('request/lib/multipart').Multipart var Redirect = require('request/lib/redirect').Redirect var Tunnel = require('request/lib/tunnel').Tunnel var now = require('performance-now') var Buffer = require('safe-buffer').Buffer var safeStringify = helpers.safeStringify var isReadStream = helpers.isReadStream var toBase64 = helpers.toBase64 var defer = helpers.defer var copy = helpers.copy var version = helpers.version var globalCookieJar = cookies.jar() var globalPool = {} function filterForNonReserved (reserved, options) { // Filter out properties that are not reserved. // Reserved values are passed in at call site. var object = {} for (var i in options) { var notReserved = (reserved.indexOf(i) === -1) if (notReserved) { object[i] = options[i] } } return object } function filterOutReservedFunctions (reserved, options) { // Filter out properties that are functions and are reserved. // Reserved values are passed in at call site. var object = {} for (var i in options) { var isReserved = !(reserved.indexOf(i) === -1) var isFunction = (typeof options[i] === 'function') if (!(isReserved && isFunction)) { object[i] = options[i] } } return object } // Return a simpler request object to allow serialization function requestToJSON () { var self = this return { uri: self.uri, method: self.method, headers: self.headers } } // Return a simpler response object to allow serialization function responseToJSON () { var self = this return { statusCode: self.statusCode, body: self.body, headers: self.headers, request: requestToJSON.call(self.request) } } function Request (options) { // if given the method property in options, set property explicitMethod to true // extend the Request instance with any non-reserved properties // remove any reserved functions from the options object // set Request instance to be readable and writable // call init var self = this // start with HAR, then override with additional options if (options.har) { self._har = new Har(self) options = self._har.options(options) } stream.Stream.call(self) var reserved = Object.keys(Request.prototype) var nonReserved = filterForNonReserved(reserved, options) extend(self, nonReserved) options = filterOutReservedFunctions(reserved, options) self.readable = true self.writable = true if (options.method) { self.explicitMethod = true } self._qs = new Querystring(self) self._auth = new Auth(self) self._oauth = new OAuth(self) self._multipart = new Multipart(self) self._redirect = new Redirect(self) self._tunnel = new Tunnel(self) self.init(options) } util.inherits(Request, stream.Stream) // Debugging Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG) function debug () { if (Request.debug) { console.error('REQUEST %s', util.format.apply(util, arguments)) } } Request.prototype.debug = debug Request.prototype.init = function (options) { // init() contains all the code to setup the request object. // the actual outgoing request is not started until start() is called // this function is called from both the constructor and on redirect. var self = this if (!options) { options = {} } self.headers = self.headers ? copy(self.headers) : {} // Delete headers with value undefined since they break // ClientRequest.OutgoingMessage.setHeader in node 0.12 for (var headerName in self.headers) { if (typeof self.headers[headerName] === 'undefined') { delete self.headers[headerName] } } caseless.httpify(self, self.headers) if (!self.method) { self.method = options.method || 'GET' } if (!self.localAddress) { self.localAddress = options.localAddress } self._qs.init(options) debug(options) if (!self.pool && self.pool !== false) { self.pool = globalPool } self.dests = self.dests || [] self.__isRequestRequest = true // Protect against double callback if (!self._callback && self.callback) { self._callback = self.callback self.callback = function () { if (self._callbackCalled) { return // Print a warning maybe? } self._callbackCalled = true self._callback.apply(self, arguments) } self.on('error', self.callback.bind()) self.on('complete', self.callback.bind(self, null)) } // People use this property instead all the time, so support it if (!self.uri && self.url) { self.uri = self.url delete self.url } // If there's a baseUrl, then use it as the base URL (i.e. uri must be // specified as a relative path and is appended to baseUrl). if (self.baseUrl) { if (typeof self.baseUrl !== 'string') { return self.emit('error', new Error('options.baseUrl must be a string')) } if (typeof self.uri !== 'string') { return self.emit('error', new Error('options.uri must be a string when using options.baseUrl')) } if (self.uri.indexOf('//') === 0 || self.uri.indexOf('://') !== -1) { return self.emit('error', new Error('options.uri must be a path when using options.baseUrl')) } // Handle all cases to make sure that there's only one slash between // baseUrl and uri. var baseUrlEndsWithSlash = self.baseUrl.lastIndexOf('/') === self.baseUrl.length - 1 var uriStartsWithSlash = self.uri.indexOf('/') === 0 if (baseUrlEndsWithSlash && uriStartsWithSlash) { self.uri = self.baseUrl + self.uri.slice(1) } else if (baseUrlEndsWithSlash || uriStartsWithSlash) { self.uri = self.baseUrl + self.uri } else if (self.uri === '') { self.uri = self.baseUrl } else { self.uri = self.baseUrl + '/' + self.uri } delete self.baseUrl } // A URI is needed by this point, emit error if we haven't been able to get one if (!self.uri) { return self.emit('error', new Error('options.uri is a required argument')) } // If a string URI/URL was given, parse it into a URL object if (typeof self.uri === 'string') { self.uri = url.parse(self.uri) } // Some URL objects are not from a URL parsed string and need href added if (!self.uri.href) { self.uri.href = url.format(self.uri) } // DEPRECATED: Warning for users of the old Unix Sockets URL Scheme if (self.uri.protocol === 'unix:') { return self.emit('error', new Error('`unix://` URL scheme is no longer supported. Please use the format `http://unix:SOCKET:PATH`')) } // Support Unix Sockets if (self.uri.host === 'unix') { self.enableUnixSocket() } if (self.strictSSL === false) { self.rejectUnauthorized = false } if (!self.uri.pathname) { self.uri.pathname = '/' } if (!(self.uri.host || (self.uri.hostname && self.uri.port)) && !self.uri.isUnix) { // Invalid URI: it may generate lot of bad errors, like 'TypeError: Cannot call method `indexOf` of undefined' in CookieJar // Detect and reject it as soon as possible var faultyUri = url.format(self.uri) var message = 'Invalid URI "' + faultyUri + '"' if (Object.keys(options).length === 0) { // No option ? This can be the sign of a redirect // As this is a case where the user cannot do anything (they didn't call request directly with this URL) // they should be warned that it can be caused by a redirection (can save some hair) message += '. This can be caused by a crappy redirection.' } // This error was fatal self.abort() return self.emit('error', new Error(message)) } if (!self.hasOwnProperty('proxy')) { self.proxy = getProxyFromURI(self.uri) } self.tunnel = self._tunnel.isEnabled() if (self.proxy) { self._tunnel.setup(options) } self._redirect.onRequest(options) self.setHost = false if (!self.hasHeader('host')) { var hostHeaderName = self.originalHostHeaderName || 'host' self.setHeader(hostHeaderName, self.uri.host) // Drop :port suffix from Host header if known protocol. if (self.uri.port) { if ((self.uri.port === '80' && self.uri.protocol === 'http:') || (self.uri.port === '443' && self.uri.protocol === 'https:')) { self.setHeader(hostHeaderName, self.uri.hostname) } } self.setHost = true } self.jar(self._jar || options.jar) if (!self.uri.port) { if (self.uri.protocol === 'http:') { self.uri.port = 80 } else if (self.uri.protocol === 'https:') { self.uri.port = 443 } } if (self.proxy && !self.tunnel) { self.port = self.proxy.port self.host = self.proxy.hostname } else { self.port = self.uri.port self.host = self.uri.hostname } if (options.form) { self.form(options.form) } if (options.formData) { var formData = options.formData var requestForm = self.form() var appendFormValue = function (key, value) { if (value && value.hasOwnProperty('value') && value.hasOwnProperty('options')) { requestForm.append(key, value.value, value.options) } else { requestForm.append(key, value) } } for (var formKey in formData) { if (formData.hasOwnProperty(formKey)) { var formValue = formData[formKey] if (formValue instanceof Array) { for (var j = 0; j < formValue.length; j++) { appendFormValue(formKey, formValue[j]) } } else { appendFormValue(formKey, formValue) } } } } if (options.qs) { self.qs(options.qs) } if (self.uri.path) { self.path = self.uri.path } else { self.path = self.uri.pathname + (self.uri.search || '') } if (self.path.length === 0) { self.path = '/' } // Auth must happen last in case signing is dependent on other headers if (options.aws) { self.aws(options.aws) } if (options.hawk) { self.hawk(options.hawk) } if (options.httpSignature) { self.httpSignature(options.httpSignature) } if (options.auth) { if (Object.prototype.hasOwnProperty.call(options.auth, 'username')) { options.auth.user = options.auth.username } if (Object.prototype.hasOwnProperty.call(options.auth, 'password')) { options.auth.pass = options.auth.password } self.auth( options.auth.user, options.auth.pass, options.auth.sendImmediately, options.auth.bearer ) } if (self.gzip && !self.hasHeader('accept-encoding')) { self.setHeader('accept-encoding', 'gzip, deflate') } if (self.uri.auth && !self.hasHeader('authorization')) { var uriAuthPieces = self.uri.auth.split(':').map(function (item) { return self._qs.unescape(item) }) self.auth(uriAuthPieces[0], uriAuthPieces.slice(1).join(':'), true) } if (!self.tunnel && self.proxy && self.proxy.auth && !self.hasHeader('proxy-authorization')) { var proxyAuthPieces = self.proxy.auth.split(':').map(function (item) { return self._qs.unescape(item) }) var authHeader = 'Basic ' + toBase64(proxyAuthPieces.join(':')) self.setHeader('proxy-authorization', authHeader) } if (self.proxy && !self.tunnel) { self.path = (self.uri.protocol + '//' + self.uri.host + self.path) } if (options.json) { self.json(options.json) } if (options.multipart) { self.multipart(options.multipart) } if (options.time) { self.timing = true // NOTE: elapsedTime is deprecated in favor of .timings self.elapsedTime = self.elapsedTime || 0 } function setContentLength () { if (isTypedArray(self.body)) { self.body = Buffer.from(self.body) } if (!self.hasHeader('content-length')) { var length if (typeof self.body === 'string') { length = Buffer.byteLength(self.body) } else if (Array.isArray(self.body)) { length = self.body.reduce(function (a, b) { return a + b.length }, 0) } else { length = self.body.length } if (length) { self.setHeader('content-length', length) } else { self.emit('error', new Error('Argument error, options.body.')) } } } if (self.body && !isstream(self.body)) { setContentLength() } if (options.oauth) { self.oauth(options.oauth) } else if (self._oauth.params && self.hasHeader('authorization')) { self.oauth(self._oauth.params) } var protocol = self.proxy && !self.tunnel ? self.proxy.protocol : self.uri.protocol var defaultModules = {'http:': http, 'https:': https} var httpModules = self.httpModules || {} self.httpModule = httpModules[protocol] || defaultModules[protocol] if (!self.httpModule) { return self.emit('error', new Error('Invalid protocol: ' + protocol)) } if (options.ca) { self.ca = options.ca } if (!self.agent) { if (options.agentOptions) { self.agentOptions = options.agentOptions } if (options.agentClass) { self.agentClass = options.agentClass } else if (options.forever) { var v = version() // use ForeverAgent in node 0.10- only if (v.major === 0 && v.minor <= 10) { self.agentClass = protocol === 'http:' ? ForeverAgent : ForeverAgent.SSL } else { self.agentClass = self.httpModule.Agent self.agentOptions = self.agentOptions || {} self.agentOptions.keepAlive = true } } else { self.agentClass = self.httpModule.Agent } } if (self.pool === false) { self.agent = false } else { self.agent = self.agent || self.getNewAgent() } self.on('pipe', function (src) { if (self.ntick && self._started) { self.emit('error', new Error('You cannot pipe to this stream after the outbound request has started.')) } self.src = src if (isReadStream(src)) { if (!self.hasHeader('content-type')) { self.setHeader('content-type', mime.lookup(src.path)) } } else { if (src.headers) { for (var i in src.headers) { if (!self.hasHeader(i)) { self.setHeader(i, src.headers[i]) } } } if (self._json && !self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } if (src.method && !self.explicitMethod) { self.method = src.method } } // self.on('pipe', function () { // console.error('You have already piped to this stream. Pipeing twice is likely to break the request.') // }) }) defer(function () { if (self._aborted) { return } var end = function () { if (self._form) { if (!self._auth.hasAuth) { self._form.pipe(self) } else if (self._auth.hasAuth && self._auth.sentAuth) { self._form.pipe(self) } } if (self._multipart && self._multipart.chunked) { self._multipart.body.pipe(self) } if (self.body) { if (isstream(self.body)) { self.body.pipe(self) } else { setContentLength() if (Array.isArray(self.body)) { self.body.forEach(function (part) { self.write(part) }) } else { self.write(self.body) } self.end() } } else if (self.requestBodyStream) { console.warn('options.requestBodyStream is deprecated, please pass the request object to stream.pipe.') self.requestBodyStream.pipe(self) } else if (!self.src) { if (self._auth.hasAuth && !self._auth.sentAuth) { self.end() return } if (self.method !== 'GET' && typeof self.method !== 'undefined') { self.setHeader('content-length', 0) } self.end() } } if (self._form && !self.hasHeader('content-length')) { // Before ending the request, we had to compute the length of the whole form, asyncly self.setHeader(self._form.getHeaders(), true) self._form.getLength(function (err, length) { if (!err && !isNaN(length)) { self.setHeader('content-length', length) } end() }) } else { end() } self.ntick = true }) } Request.prototype.getNewAgent = function () { var self = this var Agent = self.agentClass var options = {} if (self.agentOptions) { for (var i in self.agentOptions) { options[i] = self.agentOptions[i] } } if (self.ca) { options.ca = self.ca } if (self.ciphers) { options.ciphers = self.ciphers } if (self.secureProtocol) { options.secureProtocol = self.secureProtocol } if (self.secureOptions) { options.secureOptions = self.secureOptions } if (typeof self.rejectUnauthorized !== 'undefined') { options.rejectUnauthorized = self.rejectUnauthorized } if (self.cert && self.key) { options.key = self.key options.cert = self.cert } if (self.pfx) { options.pfx = self.pfx } if (self.passphrase) { options.passphrase = self.passphrase } var poolKey = '' // different types of agents are in different pools if (Agent !== self.httpModule.Agent) { poolKey += Agent.name } // ca option is only relevant if proxy or destination are https var proxy = self.proxy if (typeof proxy === 'string') { proxy = url.parse(proxy) } var isHttps = (proxy && proxy.protocol === 'https:') || this.uri.protocol === 'https:' if (isHttps) { if (options.ca) { if (poolKey) { poolKey += ':' } poolKey += options.ca } if (typeof options.rejectUnauthorized !== 'undefined') { if (poolKey) { poolKey += ':' } poolKey += options.rejectUnauthorized } if (options.cert) { if (poolKey) { poolKey += ':' } poolKey += options.cert.toString('ascii') + options.key.toString('ascii') } if (options.pfx) { if (poolKey) { poolKey += ':' } poolKey += options.pfx.toString('ascii') } if (options.ciphers) { if (poolKey) { poolKey += ':' } poolKey += options.ciphers } if (options.secureProtocol) { if (poolKey) { poolKey += ':' } poolKey += options.secureProtocol } if (options.secureOptions) { if (poolKey) { poolKey += ':' } poolKey += options.secureOptions } } if (self.pool === globalPool && !poolKey && Object.keys(options).length === 0 && self.httpModule.globalAgent) { // not doing anything special. Use the globalAgent return self.httpModule.globalAgent } // we're using a stored agent. Make sure it's protocol-specific poolKey = self.uri.protocol + poolKey // generate a new agent for this setting if none yet exists if (!self.pool[poolKey]) { self.pool[poolKey] = new Agent(options) // properly set maxSockets on new agents if (self.pool.maxSockets) { self.pool[poolKey].maxSockets = self.pool.maxSockets } } return self.pool[poolKey] } Request.prototype.start = function () { // start() is called once we are ready to send the outgoing HTTP request. // this is usually called on the first write(), end() or on nextTick() var self = this if (self.timing) { // All timings will be relative to this request's startTime. In order to do this, // we need to capture the wall-clock start time (via Date), immediately followed // by the high-resolution timer (via now()). While these two won't be set // at the _exact_ same time, they should be close enough to be able to calculate // high-resolution, monotonically non-decreasing timestamps relative to startTime. var startTime = new Date().getTime() var startTimeNow = now() } if (self._aborted) { return } self._started = true self.method = self.method || 'GET' self.href = self.uri.href if (self.src && self.src.stat && self.src.stat.size && !self.hasHeader('content-length')) { self.setHeader('content-length', self.src.stat.size) } if (self._aws) { self.aws(self._aws, true) } // We have a method named auth, which is completely different from the http.request // auth option. If we don't remove it, we're gonna have a bad time. var reqOptions = copy(self) delete reqOptions.auth debug('make request', self.uri.href) // node v6.8.0 now supports a `timeout` value in `http.request()`, but we // should delete it for now since we handle timeouts manually for better // consistency with node versions before v6.8.0 delete reqOptions.timeout try { self.req = self.httpModule.request(reqOptions) } catch (err) { self.emit('error', err) return } if (self.timing) { self.startTime = startTime self.startTimeNow = startTimeNow // Timing values will all be relative to startTime (by comparing to startTimeNow // so we have an accurate clock) self.timings = {} } var timeout if (self.timeout && !self.timeoutTimer) { if (self.timeout < 0) { timeout = 0 } else if (typeof self.timeout === 'number' && isFinite(self.timeout)) { timeout = self.timeout } } self.req.on('response', self.onRequestResponse.bind(self)) self.req.on('error', self.onRequestError.bind(self)) self.req.on('drain', function () { self.emit('drain') }) self.req.on('socket', function (socket) { // `._connecting` was the old property which was made public in node v6.1.0 var isConnecting = socket._connecting || socket.connecting if (self.timing) { self.timings.socket = now() - self.startTimeNow if (isConnecting) { var onLookupTiming = function () { self.timings.lookup = now() - self.startTimeNow } var onConnectTiming = function () { self.timings.connect = now() - self.startTimeNow } socket.once('lookup', onLookupTiming) socket.once('connect', onConnectTiming) // clean up timing event listeners if needed on error self.req.once('error', function () { socket.removeListener('lookup', onLookupTiming) socket.removeListener('connect', onConnectTiming) }) } } var setReqTimeout = function () { // This timeout sets the amount of time to wait *between* bytes sent // from the server once connected. // // In particular, it's useful for erroring if the server fails to send // data halfway through streaming a response. self.req.setTimeout(timeout, function () { if (self.req) { self.abort() var e = new Error('ESOCKETTIMEDOUT') e.code = 'ESOCKETTIMEDOUT' e.connect = false self.emit('error', e) } }) } if (timeout !== undefined) { // Only start the connection timer if we're actually connecting a new // socket, otherwise if we're already connected (because this is a // keep-alive connection) do not bother. This is important since we won't // get a 'connect' event for an already connected socket. if (isConnecting) { var onReqSockConnect = function () { socket.removeListener('connect', onReqSockConnect) self.clearTimeout() setReqTimeout() } socket.on('connect', onReqSockConnect) self.req.on('error', function (err) { // eslint-disable-line handle-callback-err socket.removeListener('connect', onReqSockConnect) }) // Set a timeout in memory - this block will throw if the server takes more // than `timeout` to write the HTTP status and headers (corresponding to // the on('response') event on the client). NB: this measures wall-clock // time, not the time between bytes sent by the server. self.timeoutTimer = setTimeout(function () { socket.removeListener('connect', onReqSockConnect) self.abort() var e = new Error('ETIMEDOUT') e.code = 'ETIMEDOUT' e.connect = true self.emit('error', e) }, timeout) } else { // We're already connected setReqTimeout() } } self.emit('socket', socket) }) self.emit('request', self.req) } Request.prototype.onRequestError = function (error) { var self = this if (self._aborted) { return } if (self.req && self.req._reusedSocket && error.code === 'ECONNRESET' && self.agent.addRequestNoreuse) { self.agent = { addRequest: self.agent.addRequestNoreuse.bind(self.agent) } self.start() self.req.end() return } self.clearTimeout() self.emit('error', error) } Request.prototype.onRequestResponse = function (response) { var self = this if (self.timing) { self.timings.response = now() - self.startTimeNow } debug('onRequestResponse', self.uri.href, response.statusCode, response.headers) response.on('end', function () { if (self.timing) { self.timings.end = now() - self.startTimeNow response.timingStart = self.startTime // fill in the blanks for any periods that didn't trigger, such as // no lookup or connect due to keep alive if (!self.timings.socket) { self.timings.socket = 0 } if (!self.timings.lookup) { self.timings.lookup = self.timings.socket } if (!self.timings.connect) { self.timings.connect = self.timings.lookup } if (!self.timings.response) { self.timings.response = self.timings.connect } debug('elapsed time', self.timings.end) // elapsedTime includes all redirects self.elapsedTime += Math.round(self.timings.end) // NOTE: elapsedTime is deprecated in favor of .timings response.elapsedTime = self.elapsedTime // timings is just for the final fetch response.timings = self.timings // pre-calculate phase timings as well response.timingPhases = { wait: self.timings.socket, dns: self.timings.lookup - self.timings.socket, tcp: self.timings.connect - self.timings.lookup, firstByte: self.timings.response - self.timings.connect, download: self.timings.end - self.timings.response, total: self.timings.end } } debug('response end', self.uri.href, response.statusCode, response.headers) }) if (self._aborted) { debug('aborted', self.uri.href) response.resume() return } self.response = response response.request = self response.toJSON = responseToJSON // XXX This is different on 0.10, because SSL is strict by default if (self.httpModule === https && self.strictSSL && (!response.hasOwnProperty('socket') || !response.socket.authorized)) { debug('strict ssl error', self.uri.href) var sslErr = response.hasOwnProperty('socket') ? response.socket.authorizationError : self.uri.href + ' does not support SSL' self.emit('error', new Error('SSL Error: ' + sslErr)) return } // Save the original host before any redirect (if it changes, we need to // remove any authorization headers). Also remember the case of the header // name because lots of broken servers expect Host instead of host and we // want the caller to be able to specify this. self.originalHost = self.getHeader('host') if (!self.originalHostHeaderName) { self.originalHostHeaderName = self.hasHeader('host') } if (self.setHost) { self.removeHeader('host') } self.clearTimeout() var targetCookieJar = (self._jar && self._jar.setCookie) ? self._jar : globalCookieJar var addCookie = function (cookie) { // set the cookie if it's domain in the href's domain. try { targetCookieJar.setCookie(cookie, self.uri.href, {ignoreError: true}) } catch (e) { self.emit('error', e) } } response.caseless = caseless(response.headers) if (response.caseless.has('set-cookie') && (!self._disableCookies)) { var headerName = response.caseless.has('set-cookie') if (Array.isArray(response.headers[headerName])) { response.headers[headerName].forEach(addCookie) } else { addCookie(response.headers[headerName]) } } if (self._redirect.onResponse(response)) { return // Ignore the rest of the response } else { // Be a good stream and emit end when the response is finished. // Hack to emit end on close because of a core bug that never fires end response.on('close', function () { if (!self._ended) { self.response.emit('end') } }) response.once('end', function () { self._ended = true }) var noBody = function (code) { return ( self.method === 'HEAD' || // Informational (code >= 100 && code < 200) || // No Content code === 204 || // Not Modified code === 304 ) } var responseContent if (self.gzip && !noBody(response.statusCode)) { var contentEncoding = response.headers['content-encoding'] || 'identity' contentEncoding = contentEncoding.trim().toLowerCase() // Be more lenient with decoding compressed responses, since (very rarely) // servers send slightly invalid gzip responses that are still accepted // by common browsers. // Always using Z_SYNC_FLUSH is what cURL does. var zlibOptions = { flush: zlib.Z_SYNC_FLUSH, finishFlush: zlib.Z_SYNC_FLUSH } if (contentEncoding === 'gzip') { responseContent = zlib.createGunzip(zlibOptions) response.pipe(responseContent) } else if (contentEncoding === 'deflate') { responseContent = zlib.createInflate(zlibOptions) response.pipe(responseContent) } else { // Since previous versions didn't check for Content-Encoding header, // ignore any invalid values to preserve backwards-compatibility if (contentEncoding !== 'identity') { debug('ignoring unrecognized Content-Encoding ' + contentEncoding) } responseContent = response } } else { responseContent = response } if (self.encoding) { if (self.dests.length !== 0) { console.error('Ignoring encoding parameter as this stream is being piped to another stream which makes the encoding option invalid.') } else { responseContent.setEncoding(self.encoding) } } if (self._paused) { responseContent.pause() } self.responseContent = responseContent self.emit('response', response) self.dests.forEach(function (dest) { self.pipeDest(dest) }) responseContent.on('data', function (chunk) { if (self.timing && !self.responseStarted) { self.responseStartTime = (new Date()).getTime() // NOTE: responseStartTime is deprecated in favor of .timings response.responseStartTime = self.responseStartTime } self._destdata = true self.emit('data', chunk) }) responseContent.once('end', function (chunk) { self.emit('end', chunk) }) responseContent.on('error', function (error) { self.emit('error', error) }) responseContent.on('close', function () { self.emit('close') }) if (self.callback) { self.readResponseBody(response) } else { // if no callback self.on('end', function () { if (self._aborted) { debug('aborted', self.uri.href) return } self.emit('complete', response) }) } } debug('finish init function', self.uri.href) } Request.prototype.readResponseBody = function (response) { var self = this debug("reading response's body") var buffers = [] var bufferLength = 0 var strings = [] self.on('data', function (chunk) { if (!Buffer.isBuffer(chunk)) { strings.push(chunk) } else if (chunk.length) { bufferLength += chunk.length buffers.push(chunk) } }) self.on('end', function () { debug('end event', self.uri.href) if (self._aborted) { debug('aborted', self.uri.href) // `buffer` is defined in the parent scope and used in a closure it exists for the life of the request. // This can lead to leaky behavior if the user retains a reference to the request object. buffers = [] bufferLength = 0 return } if (bufferLength) { debug('has body', self.uri.href, bufferLength) response.body = Buffer.concat(buffers, bufferLength) if (self.encoding !== null) { response.body = response.body.toString(self.encoding) } // `buffer` is defined in the parent scope and used in a closure it exists for the life of the Request. // This can lead to leaky behavior if the user retains a reference to the request object. buffers = [] bufferLength = 0 } else if (strings.length) { // The UTF8 BOM [0xEF,0xBB,0xBF] is converted to [0xFE,0xFF] in the JS UTC16/UCS2 representation. // Strip this value out when the encoding is set to 'utf8', as upstream consumers won't expect it and it breaks JSON.parse(). if (self.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === '\uFEFF') { strings[0] = strings[0].substring(1) } response.body = strings.join('') } if (self._json) { try { response.body = JSON.parse(response.body, self._jsonReviver) } catch (e) { debug('invalid JSON received', self.uri.href) } } debug('emitting complete', self.uri.href) if (typeof response.body === 'undefined' && !self._json) { response.body = self.encoding === null ? Buffer.alloc(0) : '' } self.emit('complete', response, response.body) }) } Request.prototype.abort = function () { var self = this self._aborted = true if (self.req) { self.req.abort() } else if (self.response) { self.response.destroy() } self.clearTimeout() self.emit('abort') } Request.prototype.pipeDest = function (dest) { var self = this var response = self.response // Called after the response is received if (dest.headers && !dest.headersSent) { if (response.caseless.has('content-type')) { var ctname = response.caseless.has('content-type') if (dest.setHeader) { dest.setHeader(ctname, response.headers[ctname]) } else { dest.headers[ctname] = response.headers[ctname] } } if (response.caseless.has('content-length')) { var clname = response.caseless.has('content-length') if (dest.setHeader) { dest.setHeader(clname, response.headers[clname]) } else { dest.headers[clname] = response.headers[clname] } } } if (dest.setHeader && !dest.headersSent) { for (var i in response.headers) { // If the response content is being decoded, the Content-Encoding header // of the response doesn't represent the piped content, so don't pass it. if (!self.gzip || i !== 'content-encoding') { dest.setHeader(i, response.headers[i]) } } dest.statusCode = response.statusCode } if (self.pipefilter) { self.pipefilter(response, dest) } } Request.prototype.qs = function (q, clobber) { var self = this var base if (!clobber && self.uri.query) { base = self._qs.parse(self.uri.query) } else { base = {} } for (var i in q) { base[i] = q[i] } var qs = self._qs.stringify(base) if (qs === '') { return self } self.uri = url.parse(self.uri.href.split('?')[0] + '?' + qs) self.url = self.uri self.path = self.uri.path if (self.uri.host === 'unix') { self.enableUnixSocket() } return self } Request.prototype.form = function (form) { var self = this if (form) { if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { self.setHeader('content-type', 'application/x-www-form-urlencoded') } self.body = (typeof form === 'string') ? self._qs.rfc3986(form.toString('utf8')) : self._qs.stringify(form).toString('utf8') return self } // create form-data object self._form = new FormData() self._form.on('error', function (err) { err.message = 'form-data: ' + err.message self.emit('error', err) self.abort() }) return self._form } Request.prototype.multipart = function (multipart) { var self = this self._multipart.onRequest(multipart) if (!self._multipart.chunked) { self.body = self._multipart.body } return self } Request.prototype.json = function (val) { var self = this if (!self.hasHeader('accept')) { self.setHeader('accept', 'application/json') } if (typeof self.jsonReplacer === 'function') { self._jsonReplacer = self.jsonReplacer } self._json = true if (typeof val === 'boolean') { if (self.body !== undefined) { if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) { self.body = safeStringify(self.body, self._jsonReplacer) } else { self.body = self._qs.rfc3986(self.body) } if (!self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } } } else { self.body = safeStringify(val, self._jsonReplacer) if (!self.hasHeader('content-type')) { self.setHeader('content-type', 'application/json') } } if (typeof self.jsonReviver === 'function') { self._jsonReviver = self.jsonReviver } return self } Request.prototype.getHeader = function (name, headers) { var self = this var result, re, match if (!headers) { headers = self.headers } Object.keys(headers).forEach(function (key) { if (key.length !== name.length) { return } re = new RegExp(name, 'i') match = key.match(re) if (match) { result = headers[key] } }) return result } Request.prototype.enableUnixSocket = function () { // Get the socket & request paths from the URL var unixParts = this.uri.path.split(':') var host = unixParts[0] var path = unixParts[1] // Apply unix properties to request this.socketPath = host this.uri.pathname = path this.uri.path = path this.uri.host = host this.uri.hostname = host this.uri.isUnix = true } Request.prototype.auth = function (user, pass, sendImmediately, bearer) { var self = this self._auth.onRequest(user, pass, sendImmediately, bearer) return self } Request.prototype.aws = function (opts, now) { var self = this if (!now) { self._aws = opts return self } if (opts.sign_version === 4 || opts.sign_version === '4') { // use aws4 var options = { host: self.uri.host, path: self.uri.path, method: self.method, headers: self.headers, body: self.body } if (opts.service) { options.service = opts.service } var signRes = aws4.sign(options, { accessKeyId: opts.key, secretAccessKey: opts.secret, sessionToken: opts.session }) self.setHeader('authorization', signRes.headers.Authorization) self.setHeader('x-amz-date', signRes.headers['X-Amz-Date']) if (signRes.headers['X-Amz-Security-Token']) { self.setHeader('x-amz-security-token', signRes.headers['X-Amz-Security-Token']) } } else { // default: use aws-sign2 var date = new Date() self.setHeader('date', date.toUTCString()) var auth = { key: opts.key, secret: opts.secret, verb: self.method.toUpperCase(), date: date, contentType: self.getHeader('content-type') || '', md5: self.getHeader('content-md5') || '', amazonHeaders: aws2.canonicalizeHeaders(self.headers) } var path = self.uri.path if (opts.bucket && path) { auth.resource = '/' + opts.bucket + path } else if (opts.bucket && !path) { auth.resource = '/' + opts.bucket } else if (!opts.bucket && path) { auth.resource = path } else if (!opts.bucket && !path) { auth.resource = '/' } auth.resource = aws2.canonicalizeResource(auth.resource) self.setHeader('authorization', aws2.authorization(auth)) } return self } Request.prototype.httpSignature = function (opts) { var self = this httpSignature.signRequest({ getHeader: function (header) { return self.getHeader(header, self.headers) }, setHeader: function (header, value) { self.setHeader(header, value) }, method: self.method, path: self.path }, opts) debug('httpSignature authorization', self.getHeader('authorization')) return self } Request.prototype.hawk = function (opts) { var self = this self.setHeader('Authorization', hawk.header(self.uri, self.method, opts)) } Request.prototype.oauth = function (_oauth) { var self = this self._oauth.onRequest(_oauth) return self } Request.prototype.jar = function (jar) { var self = this var cookies if (self._redirect.redirectsFollowed === 0) { self.originalCookieHeader = self.getHeader('cookie') } if (!jar) { // disable cookies cookies = false self._disableCookies = true } else { var targetCookieJar = jar.getCookieString ? jar : globalCookieJar var urihref = self.uri.href // fetch cookie in the Specified host if (targetCookieJar) { cookies = targetCookieJar.getCookieString(urihref) } } // if need cookie and cookie is not empty if (cookies && cookies.length) { if (self.originalCookieHeader) { // Don't overwrite existing Cookie header self.setHeader('cookie', self.originalCookieHeader + '; ' + cookies) } else { self.setHeader('cookie', cookies) } } self._jar = jar return self } // Stream API Request.prototype.pipe = function (dest, opts) { var self = this if (self.response) { if (self._destdata) { self.emit('error', new Error('You cannot pipe after data has been emitted from the response.')) } else if (self._ended) { self.emit('error', new Error('You cannot pipe after the response has been ended.')) } else { stream.Stream.prototype.pipe.call(self, dest, opts) self.pipeDest(dest) return dest } } else { self.dests.push(dest) stream.Stream.prototype.pipe.call(self, dest, opts) return dest } } Request.prototype.write = function () { var self = this if (self._aborted) { return } if (!self._started) { self.start() } if (self.req) { return self.req.write.apply(self.req, arguments) } } Request.prototype.end = function (chunk) { var self = this if (self._aborted) { return } if (chunk) { self.write(chunk) } if (!self._started) { self.start() } if (self.req) { self.req.end() } } Request.prototype.pause = function () { var self = this if (!self.responseContent) { self._paused = true } else { self.responseContent.pause.apply(self.responseContent, arguments) } } Request.prototype.resume = function () { var self = this if (!self.responseContent) { self._paused = false } else { self.responseContent.resume.apply(self.responseContent, arguments) } } Request.prototype.destroy = function () { var self = this this.clearTimeout() if (!self._ended) { self.end() } else if (self.response) { self.response.destroy() } } Request.prototype.clearTimeout = function () { if (this.timeoutTimer) { clearTimeout(this.timeoutTimer) this.timeoutTimer = null } } Request.defaultProxyHeaderWhiteList = Tunnel.defaultProxyHeaderWhiteList.slice() Request.defaultProxyHeaderExclusiveList = Tunnel.defaultProxyHeaderExclusiveList.slice() // Exports Request.prototype.toJSON = requestToJSON module.exports = Request
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/request.js
request.js
# Deprecated! As of Feb 11th 2020, request is fully deprecated. No new changes are expected land. In fact, none have landed for some time. For more information about why request is deprecated and possible alternatives refer to [this issue](https://github.com/request/request/issues/3142). # Request - Simplified HTTP client [![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/) [![Build status](https://img.shields.io/travis/request/request/master.svg?style=flat-square)](https://travis-ci.org/request/request) [![Coverage](https://img.shields.io/codecov/c/github/request/request.svg?style=flat-square)](https://codecov.io/github/request/request?branch=master) [![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat-square)](https://coveralls.io/r/request/request) [![Dependency Status](https://img.shields.io/david/request/request.svg?style=flat-square)](https://david-dm.org/request/request) [![Known Vulnerabilities](https://snyk.io/test/npm/request/badge.svg?style=flat-square)](https://snyk.io/test/npm/request) [![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat-square)](https://gitter.im/request/request?utm_source=badge) ## Super simple to use Request is designed to be the simplest way possible to make http calls. It supports HTTPS and follows redirects by default. ```js const request = require('request'); request('http://www.google.com', function (error, response, body) { console.error('error:', error); // Print the error if one occurred console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received console.log('body:', body); // Print the HTML for the Google homepage. }); ``` ## Table of contents - [Streaming](#streaming) - [Promises & Async/Await](#promises--asyncawait) - [Forms](#forms) - [HTTP Authentication](#http-authentication) - [Custom HTTP Headers](#custom-http-headers) - [OAuth Signing](#oauth-signing) - [Proxies](#proxies) - [Unix Domain Sockets](#unix-domain-sockets) - [TLS/SSL Protocol](#tlsssl-protocol) - [Support for HAR 1.2](#support-for-har-12) - [**All Available Options**](#requestoptions-callback) Request also offers [convenience methods](#convenience-methods) like `request.defaults` and `request.post`, and there are lots of [usage examples](#examples) and several [debugging techniques](#debugging). --- ## Streaming You can stream any response to a file stream. ```js request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png')) ``` You can also stream a file to a PUT or POST request. This method will also check the file extension against a mapping of file extensions to content-types (in this case `application/json`) and use the proper `content-type` in the PUT request (if the headers don’t already provide one). ```js fs.createReadStream('file.json').pipe(request.put('http://mysite.com/obj.json')) ``` Request can also `pipe` to itself. When doing so, `content-type` and `content-length` are preserved in the PUT headers. ```js request.get('http://google.com/img.png').pipe(request.put('http://mysite.com/img.png')) ``` Request emits a "response" event when a response is received. The `response` argument will be an instance of [http.IncomingMessage](https://nodejs.org/api/http.html#http_class_http_incomingmessage). ```js request .get('http://google.com/img.png') .on('response', function(response) { console.log(response.statusCode) // 200 console.log(response.headers['content-type']) // 'image/png' }) .pipe(request.put('http://mysite.com/img.png')) ``` To easily handle errors when streaming requests, listen to the `error` event before piping: ```js request .get('http://mysite.com/doodle.png') .on('error', function(err) { console.error(err) }) .pipe(fs.createWriteStream('doodle.png')) ``` Now let’s get fancy. ```js http.createServer(function (req, resp) { if (req.url === '/doodle.png') { if (req.method === 'PUT') { req.pipe(request.put('http://mysite.com/doodle.png')) } else if (req.method === 'GET' || req.method === 'HEAD') { request.get('http://mysite.com/doodle.png').pipe(resp) } } }) ``` You can also `pipe()` from `http.ServerRequest` instances, as well as to `http.ServerResponse` instances. The HTTP method, headers, and entity-body data will be sent. Which means that, if you don't really care about security, you can do: ```js http.createServer(function (req, resp) { if (req.url === '/doodle.png') { const x = request('http://mysite.com/doodle.png') req.pipe(x) x.pipe(resp) } }) ``` And since `pipe()` returns the destination stream in ≥ Node 0.5.x you can do one line proxying. :) ```js req.pipe(request('http://mysite.com/doodle.png')).pipe(resp) ``` Also, none of this new functionality conflicts with requests previous features, it just expands them. ```js const r = request.defaults({'proxy':'http://localproxy.com'}) http.createServer(function (req, resp) { if (req.url === '/doodle.png') { r.get('http://google.com/doodle.png').pipe(resp) } }) ``` You can still use intermediate proxies, the requests will still follow HTTP forwards, etc. [back to top](#table-of-contents) --- ## Promises & Async/Await `request` supports both streaming and callback interfaces natively. If you'd like `request` to return a Promise instead, you can use an alternative interface wrapper for `request`. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use `async`/`await` in ES2017. Several alternative interfaces are provided by the request team, including: - [`request-promise`](https://github.com/request/request-promise) (uses [Bluebird](https://github.com/petkaantonov/bluebird) Promises) - [`request-promise-native`](https://github.com/request/request-promise-native) (uses native Promises) - [`request-promise-any`](https://github.com/request/request-promise-any) (uses [any-promise](https://www.npmjs.com/package/any-promise) Promises) Also, [`util.promisify`](https://nodejs.org/api/util.html#util_util_promisify_original), which is available from Node.js v8.0 can be used to convert a regular function that takes a callback to return a promise instead. [back to top](#table-of-contents) --- ## Forms `request` supports `application/x-www-form-urlencoded` and `multipart/form-data` form uploads. For `multipart/related` refer to the `multipart` API. #### application/x-www-form-urlencoded (URL-Encoded Forms) URL-encoded forms are simple. ```js request.post('http://service.com/upload', {form:{key:'value'}}) // or request.post('http://service.com/upload').form({key:'value'}) // or request.post({url:'http://service.com/upload', form: {key:'value'}}, function(err,httpResponse,body){ /* ... */ }) ``` #### multipart/form-data (Multipart Form Uploads) For `multipart/form-data` we use the [form-data](https://github.com/form-data/form-data) library by [@felixge](https://github.com/felixge). For the most cases, you can pass your upload form data via the `formData` option. ```js const formData = { // Pass a simple key-value pair my_field: 'my_value', // Pass data via Buffers my_buffer: Buffer.from([1, 2, 3]), // Pass data via Streams my_file: fs.createReadStream(__dirname + '/unicycle.jpg'), // Pass multiple values /w an Array attachments: [ fs.createReadStream(__dirname + '/attachment1.jpg'), fs.createReadStream(__dirname + '/attachment2.jpg') ], // Pass optional meta-data with an 'options' object with style: {value: DATA, options: OPTIONS} // Use case: for some types of streams, you'll need to provide "file"-related information manually. // See the `form-data` README for more information about options: https://github.com/form-data/form-data custom_file: { value: fs.createReadStream('/dev/urandom'), options: { filename: 'topsecret.jpg', contentType: 'image/jpeg' } } }; request.post({url:'http://service.com/upload', formData: formData}, function optionalCallback(err, httpResponse, body) { if (err) { return console.error('upload failed:', err); } console.log('Upload successful! Server responded with:', body); }); ``` For advanced cases, you can access the form-data object itself via `r.form()`. This can be modified until the request is fired on the next cycle of the event-loop. (Note that this calling `form()` will clear the currently set form data for that request.) ```js // NOTE: Advanced use-case, for normal use see 'formData' usage above const r = request.post('http://service.com/upload', function optionalCallback(err, httpResponse, body) {...}) const form = r.form(); form.append('my_field', 'my_value'); form.append('my_buffer', Buffer.from([1, 2, 3])); form.append('custom_file', fs.createReadStream(__dirname + '/unicycle.jpg'), {filename: 'unicycle.jpg'}); ``` See the [form-data README](https://github.com/form-data/form-data) for more information & examples. #### multipart/related Some variations in different HTTP implementations require a newline/CRLF before, after, or both before and after the boundary of a `multipart/related` request (using the multipart option). This has been observed in the .NET WebAPI version 4.0. You can turn on a boundary preambleCRLF or postamble by passing them as `true` to your request options. ```js request({ method: 'PUT', preambleCRLF: true, postambleCRLF: true, uri: 'http://service.com/upload', multipart: [ { 'content-type': 'application/json', body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) }, { body: 'I am an attachment' }, { body: fs.createReadStream('image.png') } ], // alternatively pass an object containing additional options multipart: { chunked: false, data: [ { 'content-type': 'application/json', body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) }, { body: 'I am an attachment' } ] } }, function (error, response, body) { if (error) { return console.error('upload failed:', error); } console.log('Upload successful! Server responded with:', body); }) ``` [back to top](#table-of-contents) --- ## HTTP Authentication ```js request.get('http://some.server.com/').auth('username', 'password', false); // or request.get('http://some.server.com/', { 'auth': { 'user': 'username', 'pass': 'password', 'sendImmediately': false } }); // or request.get('http://some.server.com/').auth(null, null, true, 'bearerToken'); // or request.get('http://some.server.com/', { 'auth': { 'bearer': 'bearerToken' } }); ``` If passed as an option, `auth` should be a hash containing values: - `user` || `username` - `pass` || `password` - `sendImmediately` (optional) - `bearer` (optional) The method form takes parameters `auth(username, password, sendImmediately, bearer)`. `sendImmediately` defaults to `true`, which causes a basic or bearer authentication header to be sent. If `sendImmediately` is `false`, then `request` will retry with a proper authentication header after receiving a `401` response from the server (which must contain a `WWW-Authenticate` header indicating the required authentication method). Note that you can also specify basic authentication using the URL itself, as detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the `user:password` before the host with an `@` sign: ```js const username = 'username', password = 'password', url = 'http://' + username + ':' + password + '@some.server.com'; request({url}, function (error, response, body) { // Do more stuff with 'body' here }); ``` Digest authentication is supported, but it only works with `sendImmediately` set to `false`; otherwise `request` will send basic authentication on the initial request, which will probably cause the request to fail. Bearer authentication is supported, and is activated when the `bearer` value is available. The value may be either a `String` or a `Function` returning a `String`. Using a function to supply the bearer token is particularly useful if used in conjunction with `defaults` to allow a single function to supply the last known token at the time of sending a request, or to compute one on the fly. [back to top](#table-of-contents) --- ## Custom HTTP Headers HTTP Headers, such as `User-Agent`, can be set in the `options` object. In the example below, we call the github API to find out the number of stars and forks for the request repository. This requires a custom `User-Agent` header as well as https. ```js const request = require('request'); const options = { url: 'https://api.github.com/repos/request/request', headers: { 'User-Agent': 'request' } }; function callback(error, response, body) { if (!error && response.statusCode == 200) { const info = JSON.parse(body); console.log(info.stargazers_count + " Stars"); console.log(info.forks_count + " Forks"); } } request(options, callback); ``` [back to top](#table-of-contents) --- ## OAuth Signing [OAuth version 1.0](https://tools.ietf.org/html/rfc5849) is supported. The default signing algorithm is [HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2): ```js // OAuth1.0 - 3-legged server side flow (Twitter example) // step 1 const qs = require('querystring') , oauth = { callback: 'http://mysite.com/callback/' , consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET } , url = 'https://api.twitter.com/oauth/request_token' ; request.post({url:url, oauth:oauth}, function (e, r, body) { // Ideally, you would take the body in the response // and construct a URL that a user clicks on (like a sign in button). // The verifier is only available in the response after a user has // verified with twitter that they are authorizing your app. // step 2 const req_data = qs.parse(body) const uri = 'https://api.twitter.com/oauth/authenticate' + '?' + qs.stringify({oauth_token: req_data.oauth_token}) // redirect the user to the authorize uri // step 3 // after the user is redirected back to your server const auth_data = qs.parse(body) , oauth = { consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET , token: auth_data.oauth_token , token_secret: req_data.oauth_token_secret , verifier: auth_data.oauth_verifier } , url = 'https://api.twitter.com/oauth/access_token' ; request.post({url:url, oauth:oauth}, function (e, r, body) { // ready to make signed requests on behalf of the user const perm_data = qs.parse(body) , oauth = { consumer_key: CONSUMER_KEY , consumer_secret: CONSUMER_SECRET , token: perm_data.oauth_token , token_secret: perm_data.oauth_token_secret } , url = 'https://api.twitter.com/1.1/users/show.json' , qs = { screen_name: perm_data.screen_name , user_id: perm_data.user_id } ; request.get({url:url, oauth:oauth, qs:qs, json:true}, function (e, r, user) { console.log(user) }) }) }) ``` For [RSA-SHA1 signing](https://tools.ietf.org/html/rfc5849#section-3.4.3), make the following changes to the OAuth options object: * Pass `signature_method : 'RSA-SHA1'` * Instead of `consumer_secret`, specify a `private_key` string in [PEM format](http://how2ssl.com/articles/working_with_pem_files/) For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make the following changes to the OAuth options object: * Pass `signature_method : 'PLAINTEXT'` To send OAuth parameters via query params or in a post body as described in The [Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param) section of the oauth1 spec: * Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth options object. * `transport_method` defaults to `'header'` To use [Request Body Hash](https://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html) you can either * Manually generate the body hash and pass it as a string `body_hash: '...'` * Automatically generate the body hash by passing `body_hash: true` [back to top](#table-of-contents) --- ## Proxies If you specify a `proxy` option, then the request (and any subsequent redirects) will be sent via a connection to the proxy server. If your endpoint is an `https` url, and you are using a proxy, then request will send a `CONNECT` request to the proxy server *first*, and then use the supplied connection to connect to the endpoint. That is, first it will make a request like: ``` HTTP/1.1 CONNECT endpoint-server.com:80 Host: proxy-server.com User-Agent: whatever user agent you specify ``` and then the proxy server make a TCP connection to `endpoint-server` on port `80`, and return a response that looks like: ``` HTTP/1.1 200 OK ``` At this point, the connection is left open, and the client is communicating directly with the `endpoint-server.com` machine. See [the wikipedia page on HTTP Tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel) for more information. By default, when proxying `http` traffic, request will simply make a standard proxied `http` request. This is done by making the `url` section of the initial line of the request a fully qualified url to the endpoint. For example, it will make a single request that looks like: ``` HTTP/1.1 GET http://endpoint-server.com/some-url Host: proxy-server.com Other-Headers: all go here request body or whatever ``` Because a pure "http over http" tunnel offers no additional security or other features, it is generally simpler to go with a straightforward HTTP proxy in this case. However, if you would like to force a tunneling proxy, you may set the `tunnel` option to `true`. You can also make a standard proxied `http` request by explicitly setting `tunnel : false`, but **note that this will allow the proxy to see the traffic to/from the destination server**. If you are using a tunneling proxy, you may set the `proxyHeaderWhiteList` to share certain headers with the proxy. You can also set the `proxyHeaderExclusiveList` to share certain headers only with the proxy and not with destination host. By default, this set is: ``` accept accept-charset accept-encoding accept-language accept-ranges cache-control content-encoding content-language content-length content-location content-md5 content-range content-type connection date expect max-forwards pragma proxy-authorization referer te transfer-encoding user-agent via ``` Note that, when using a tunneling proxy, the `proxy-authorization` header and any headers from custom `proxyHeaderExclusiveList` are *never* sent to the endpoint server, but only to the proxy server. ### Controlling proxy behaviour using environment variables The following environment variables are respected by `request`: * `HTTP_PROXY` / `http_proxy` * `HTTPS_PROXY` / `https_proxy` * `NO_PROXY` / `no_proxy` When `HTTP_PROXY` / `http_proxy` are set, they will be used to proxy non-SSL requests that do not have an explicit `proxy` configuration option present. Similarly, `HTTPS_PROXY` / `https_proxy` will be respected for SSL requests that do not have an explicit `proxy` configuration option. It is valid to define a proxy in one of the environment variables, but then override it for a specific request, using the `proxy` configuration option. Furthermore, the `proxy` configuration option can be explicitly set to false / null to opt out of proxying altogether for that request. `request` is also aware of the `NO_PROXY`/`no_proxy` environment variables. These variables provide a granular way to opt out of proxying, on a per-host basis. It should contain a comma separated list of hosts to opt out of proxying. It is also possible to opt of proxying when a particular destination port is used. Finally, the variable may be set to `*` to opt out of the implicit proxy configuration of the other environment variables. Here's some examples of valid `no_proxy` values: * `google.com` - don't proxy HTTP/HTTPS requests to Google. * `google.com:443` - don't proxy HTTPS requests to Google, but *do* proxy HTTP requests to Google. * `google.com:443, yahoo.com:80` - don't proxy HTTPS requests to Google, and don't proxy HTTP requests to Yahoo! * `*` - ignore `https_proxy`/`http_proxy` environment variables altogether. [back to top](#table-of-contents) --- ## UNIX Domain Sockets `request` supports making requests to [UNIX Domain Sockets](https://en.wikipedia.org/wiki/Unix_domain_socket). To make one, use the following URL scheme: ```js /* Pattern */ 'http://unix:SOCKET:PATH' /* Example */ request.get('http://unix:/absolute/path/to/unix.socket:/request/path') ``` Note: The `SOCKET` path is assumed to be absolute to the root of the host file system. [back to top](#table-of-contents) --- ## TLS/SSL Protocol TLS/SSL Protocol options, such as `cert`, `key` and `passphrase`, can be set directly in `options` object, in the `agentOptions` property of the `options` object, or even in `https.globalAgent.options`. Keep in mind that, although `agentOptions` allows for a slightly wider range of configurations, the recommended way is via `options` object directly, as using `agentOptions` or `https.globalAgent.options` would not be applied in the same way in proxied environments (as data travels through a TLS connection instead of an http/https agent). ```js const fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , caFile = path.resolve(__dirname, 'ssl/ca.cert.pem') , request = require('request'); const options = { url: 'https://api.some-server.com/', cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile), passphrase: 'password', ca: fs.readFileSync(caFile) }; request.get(options); ``` ### Using `options.agentOptions` In the example below, we call an API that requires client side SSL certificate (in PEM format) with passphrase protected private key (in PEM format) and disable the SSLv3 protocol: ```js const fs = require('fs') , path = require('path') , certFile = path.resolve(__dirname, 'ssl/client.crt') , keyFile = path.resolve(__dirname, 'ssl/client.key') , request = require('request'); const options = { url: 'https://api.some-server.com/', agentOptions: { cert: fs.readFileSync(certFile), key: fs.readFileSync(keyFile), // Or use `pfx` property replacing `cert` and `key` when using private key, certificate and CA certs in PFX or PKCS12 format: // pfx: fs.readFileSync(pfxFilePath), passphrase: 'password', securityOptions: 'SSL_OP_NO_SSLv3' } }; request.get(options); ``` It is able to force using SSLv3 only by specifying `secureProtocol`: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { secureProtocol: 'SSLv3_method' } }); ``` It is possible to accept other certificates than those signed by generally allowed Certificate Authorities (CAs). This can be useful, for example, when using self-signed certificates. To require a different root certificate, you can specify the signing CA by adding the contents of the CA's certificate file to the `agentOptions`. The certificate the domain presents must be signed by the root certificate specified: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { ca: fs.readFileSync('ca.cert.pem') } }); ``` The `ca` value can be an array of certificates, in the event you have a private or internal corporate public-key infrastructure hierarchy. For example, if you want to connect to https://api.some-server.com which presents a key chain consisting of: 1. its own public key, which is signed by: 2. an intermediate "Corp Issuing Server", that is in turn signed by: 3. a root CA "Corp Root CA"; you can configure your request as follows: ```js request.get({ url: 'https://api.some-server.com/', agentOptions: { ca: [ fs.readFileSync('Corp Issuing Server.pem'), fs.readFileSync('Corp Root CA.pem') ] } }); ``` [back to top](#table-of-contents) --- ## Support for HAR 1.2 The `options.har` property will override the values: `url`, `method`, `qs`, `headers`, `form`, `formData`, `body`, `json`, as well as construct multipart data and read files from disk when `request.postData.params[].fileName` is present without a matching `value`. A validation step will check if the HAR Request format matches the latest spec (v1.2) and will skip parsing if not matching. ```js const request = require('request') request({ // will be ignored method: 'GET', uri: 'http://www.google.com', // HTTP Archive Request Object har: { url: 'http://www.mockbin.com/har', method: 'POST', headers: [ { name: 'content-type', value: 'application/x-www-form-urlencoded' } ], postData: { mimeType: 'application/x-www-form-urlencoded', params: [ { name: 'foo', value: 'bar' }, { name: 'hello', value: 'world' } ] } } }) // a POST request will be sent to http://www.mockbin.com // with body an application/x-www-form-urlencoded body: // foo=bar&hello=world ``` [back to top](#table-of-contents) --- ## request(options, callback) The first argument can be either a `url` or an `options` object. The only required option is `uri`; all others are optional. - `uri` || `url` - fully qualified uri or a parsed url object from `url.parse()` - `baseUrl` - fully qualified uri string used as the base url. Most useful with `request.defaults`, for example when you want to do many requests to the same domain. If `baseUrl` is `https://example.com/api/`, then requesting `/end/point?test=true` will fetch `https://example.com/api/end/point?test=true`. When `baseUrl` is given, `uri` must also be a string. - `method` - http method (default: `"GET"`) - `headers` - http headers (default: `{}`) --- - `qs` - object containing querystring values to be appended to the `uri` - `qsParseOptions` - object containing options to pass to the [qs.parse](https://github.com/hapijs/qs#parsing-objects) method. Alternatively pass options to the [querystring.parse](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_parse_str_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}` - `qsStringifyOptions` - object containing options to pass to the [qs.stringify](https://github.com/hapijs/qs#stringifying) method. Alternatively pass options to the [querystring.stringify](https://nodejs.org/docs/v0.12.0/api/querystring.html#querystring_querystring_stringify_obj_sep_eq_options) method using this format `{sep:';', eq:':', options:{}}`. For example, to change the way arrays are converted to query strings using the `qs` module pass the `arrayFormat` option with one of `indices|brackets|repeat` - `useQuerystring` - if true, use `querystring` to stringify and parse querystrings, otherwise use `qs` (default: `false`). Set this option to `true` if you need arrays to be serialized as `foo=bar&foo=baz` instead of the default `foo[0]=bar&foo[1]=baz`. --- - `body` - entity body for PATCH, POST and PUT requests. Must be a `Buffer`, `String` or `ReadStream`. If `json` is `true`, then `body` must be a JSON-serializable object. - `form` - when passed an object or a querystring, this sets `body` to a querystring representation of value, and adds `Content-type: application/x-www-form-urlencoded` header. When passed no options, a `FormData` instance is returned (and is piped to request). See "Forms" section above. - `formData` - data to pass for a `multipart/form-data` request. See [Forms](#forms) section above. - `multipart` - array of objects which contain their own headers and `body` attributes. Sends a `multipart/related` request. See [Forms](#forms) section above. - Alternatively you can pass in an object `{chunked: false, data: []}` where `chunked` is used to specify whether the request is sent in [chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding) In non-chunked requests, data items with body streams are not allowed. - `preambleCRLF` - append a newline/CRLF before the boundary of your `multipart/form-data` request. - `postambleCRLF` - append a newline/CRLF at the end of the boundary of your `multipart/form-data` request. - `json` - sets `body` to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON. - `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body. - `jsonReplacer` - a [replacer function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) that will be passed to `JSON.stringify()` when stringifying a JSON request body. --- - `auth` - a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above. - `oauth` - options for OAuth HMAC-SHA1 signing. See documentation above. - `hawk` - options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example). - `aws` - `object` containing AWS signing information. Should have the properties `key`, `secret`, and optionally `session` (note that this only works for services that require session as part of the canonical string). Also requires the property `bucket`, unless you’re specifying your `bucket` as part of the path, or the request doesn’t use a bucket (i.e. GET Services). If you want to use AWS sign version 4 use the parameter `sign_version` with value `4` otherwise the default is version 2. If you are using SigV4, you can also include a `service` property that specifies the service name. **Note:** you need to `npm install aws4` first. - `httpSignature` - options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options. --- - `followRedirect` - follow HTTP 3xx responses as redirects (default: `true`). This property can also be implemented as function which gets `response` object as a single argument and should return `true` if redirects should continue or `false` otherwise. - `followAllRedirects` - follow non-GET HTTP 3xx responses as redirects (default: `false`) - `followOriginalHttpMethod` - by default we redirect to HTTP method GET. you can enable this property to redirect to the original HTTP method (default: `false`) - `maxRedirects` - the maximum number of redirects to follow (default: `10`) - `removeRefererHeader` - removes the referer header when a redirect happens (default: `false`). **Note:** if true, referer header set in the initial request is preserved during redirect chain. --- - `encoding` - encoding to be used on `setEncoding` of response data. If `null`, the `body` is returned as a `Buffer`. Anything else **(including the default value of `undefined`)** will be passed as the [encoding](http://nodejs.org/api/buffer.html#buffer_buffer) parameter to `toString()` (meaning this is effectively `utf8` by default). (**Note:** if you expect binary data, you should set `encoding: null`.) - `gzip` - if `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below. - `jar` - if `true`, remember cookies for future use (or define your custom cookie jar; see examples section) --- - `agent` - `http(s).Agent` instance to use - `agentClass` - alternatively specify your agent's class name - `agentOptions` - and pass its options. **Note:** for HTTPS see [tls API doc for TLS/SSL options](http://nodejs.org/api/tls.html#tls_tls_connect_options_callback) and the [documentation above](#using-optionsagentoptions). - `forever` - set to `true` to use the [forever-agent](https://github.com/request/forever-agent) **Note:** Defaults to `http(s).Agent({keepAlive:true})` in node 0.12+ - `pool` - an object describing which agents to use for the request. If this option is omitted the request will use the global agent (as long as your options allow for it). Otherwise, request will search the pool for your custom agent. If no custom agent is found, a new agent will be created and added to the pool. **Note:** `pool` is used only when the `agent` option is not specified. - A `maxSockets` property can also be provided on the `pool` object to set the max number of sockets for all agents created (ex: `pool: {maxSockets: Infinity}`). - Note that if you are sending multiple requests in a loop and creating multiple new `pool` objects, `maxSockets` will not work as intended. To work around this, either use [`request.defaults`](#requestdefaultsoptions) with your pool options or create the pool object with the `maxSockets` property outside of the loop. - `timeout` - integer containing number of milliseconds, controls two timeouts. - **Read timeout**: Time to wait for a server to send response headers (and start the response body) before aborting the request. - **Connection timeout**: Sets the socket to timeout after `timeout` milliseconds of inactivity. Note that increasing the timeout beyond the OS-wide TCP connection timeout will not have any effect ([the default in Linux can be anywhere from 20-120 seconds][linux-timeout]) [linux-timeout]: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout --- - `localAddress` - local interface to bind for network connections. - `proxy` - an HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`) - `strictSSL` - if `true`, requires SSL certificates be valid. **Note:** to use your own certificate authority, you need to specify an agent that was created with that CA as an option. - `tunnel` - controls the behavior of [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling) as follows: - `undefined` (default) - `true` if the destination is `https`, `false` otherwise - `true` - always tunnel to the destination by making a `CONNECT` request to the proxy - `false` - request the destination as a `GET` request. - `proxyHeaderWhiteList` - a whitelist of headers to send to a tunneling proxy. - `proxyHeaderExclusiveList` - a whitelist of headers to send exclusively to a tunneling proxy and not to destination. --- - `time` - if `true`, the request-response cycle (including all redirects) is timed at millisecond resolution. When set, the following properties are added to the response object: - `elapsedTime` Duration of the entire request/response in milliseconds (*deprecated*). - `responseStartTime` Timestamp when the response began (in Unix Epoch milliseconds) (*deprecated*). - `timingStart` Timestamp of the start of the request (in Unix Epoch milliseconds). - `timings` Contains event timestamps in millisecond resolution relative to `timingStart`. If there were redirects, the properties reflect the timings of the final request in the redirect chain: - `socket` Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_socket) module's `socket` event fires. This happens when the socket is assigned to the request. - `lookup` Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_lookup) module's `lookup` event fires. This happens when the DNS has been resolved. - `connect`: Relative timestamp when the [`net`](https://nodejs.org/api/net.html#net_event_connect) module's `connect` event fires. This happens when the server acknowledges the TCP connection. - `response`: Relative timestamp when the [`http`](https://nodejs.org/api/http.html#http_event_response) module's `response` event fires. This happens when the first bytes are received from the server. - `end`: Relative timestamp when the last bytes of the response are received. - `timingPhases` Contains the durations of each request phase. If there were redirects, the properties reflect the timings of the final request in the redirect chain: - `wait`: Duration of socket initialization (`timings.socket`) - `dns`: Duration of DNS lookup (`timings.lookup` - `timings.socket`) - `tcp`: Duration of TCP connection (`timings.connect` - `timings.socket`) - `firstByte`: Duration of HTTP server response (`timings.response` - `timings.connect`) - `download`: Duration of HTTP download (`timings.end` - `timings.response`) - `total`: Duration entire HTTP round-trip (`timings.end`) - `har` - a [HAR 1.2 Request Object](http://www.softwareishard.com/blog/har-12-spec/#request), will be processed from HAR format into options overwriting matching values *(see the [HAR 1.2 section](#support-for-har-12) for details)* - `callback` - alternatively pass the request's callback in the options object The callback argument gets 3 arguments: 1. An `error` when applicable (usually from [`http.ClientRequest`](http://nodejs.org/api/http.html#http_class_http_clientrequest) object) 2. An [`http.IncomingMessage`](https://nodejs.org/api/http.html#http_class_http_incomingmessage) object (Response object) 3. The third is the `response` body (`String` or `Buffer`, or JSON object if the `json` option is supplied) [back to top](#table-of-contents) --- ## Convenience methods There are also shorthand methods for different HTTP METHODs and some other conveniences. ### request.defaults(options) This method **returns a wrapper** around the normal request API that defaults to whatever options you pass to it. **Note:** `request.defaults()` **does not** modify the global request API; instead, it **returns a wrapper** that has your default settings applied to it. **Note:** You can call `.defaults()` on the wrapper that is returned from `request.defaults` to add/override defaults that were previously defaulted. For example: ```js //requests using baseRequest() will set the 'x-token' header const baseRequest = request.defaults({ headers: {'x-token': 'my-token'} }) //requests using specialRequest() will include the 'x-token' header set in //baseRequest and will also include the 'special' header const specialRequest = baseRequest.defaults({ headers: {special: 'special value'} }) ``` ### request.METHOD() These HTTP method convenience functions act just like `request()` but with a default method already set for you: - *request.get()*: Defaults to `method: "GET"`. - *request.post()*: Defaults to `method: "POST"`. - *request.put()*: Defaults to `method: "PUT"`. - *request.patch()*: Defaults to `method: "PATCH"`. - *request.del() / request.delete()*: Defaults to `method: "DELETE"`. - *request.head()*: Defaults to `method: "HEAD"`. - *request.options()*: Defaults to `method: "OPTIONS"`. ### request.cookie() Function that creates a new cookie. ```js request.cookie('key1=value1') ``` ### request.jar() Function that creates a new cookie jar. ```js request.jar() ``` ### response.caseless.get('header-name') Function that returns the specified response header field using a [case-insensitive match](https://tools.ietf.org/html/rfc7230#section-3.2) ```js request('http://www.google.com', function (error, response, body) { // print the Content-Type header even if the server returned it as 'content-type' (lowercase) console.log('Content-Type is:', response.caseless.get('Content-Type')); }); ``` [back to top](#table-of-contents) --- ## Debugging There are at least three ways to debug the operation of `request`: 1. Launch the node process like `NODE_DEBUG=request node script.js` (`lib,request,otherlib` works too). 2. Set `require('request').debug = true` at any time (this does the same thing as #1). 3. Use the [request-debug module](https://github.com/request/request-debug) to view request and response headers and bodies. [back to top](#table-of-contents) --- ## Timeouts Most requests to external servers should have a timeout attached, in case the server is not responding in a timely manner. Without a timeout, your code may have a socket open/consume resources for minutes or more. There are two main types of timeouts: **connection timeouts** and **read timeouts**. A connect timeout occurs if the timeout is hit while your client is attempting to establish a connection to a remote machine (corresponding to the [connect() call][connect] on the socket). A read timeout occurs any time the server is too slow to send back a part of the response. These two situations have widely different implications for what went wrong with the request, so it's useful to be able to distinguish them. You can detect timeout errors by checking `err.code` for an 'ETIMEDOUT' value. Further, you can detect whether the timeout was a connection timeout by checking if the `err.connect` property is set to `true`. ```js request.get('http://10.255.255.1', {timeout: 1500}, function(err) { console.log(err.code === 'ETIMEDOUT'); // Set to `true` if the timeout was a connection timeout, `false` or // `undefined` otherwise. console.log(err.connect === true); process.exit(0); }); ``` [connect]: http://linux.die.net/man/2/connect ## Examples: ```js const request = require('request') , rand = Math.floor(Math.random()*100000000).toString() ; request( { method: 'PUT' , uri: 'http://mikeal.iriscouch.com/testjs/' + rand , multipart: [ { 'content-type': 'application/json' , body: JSON.stringify({foo: 'bar', _attachments: {'message.txt': {follows: true, length: 18, 'content_type': 'text/plain' }}}) } , { body: 'I am an attachment' } ] } , function (error, response, body) { if(response.statusCode == 201){ console.log('document saved as: http://mikeal.iriscouch.com/testjs/'+ rand) } else { console.log('error: '+ response.statusCode) console.log(body) } } ) ``` For backwards-compatibility, response compression is not supported by default. To accept gzip-compressed responses, set the `gzip` option to `true`. Note that the body data passed through `request` is automatically decompressed while the response object is unmodified and will contain compressed data if the server sent a compressed response. ```js const request = require('request') request( { method: 'GET' , uri: 'http://www.google.com' , gzip: true } , function (error, response, body) { // body is the decompressed response body console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity')) console.log('the decoded data is: ' + body) } ) .on('data', function(data) { // decompressed data as it is received console.log('decoded chunk: ' + data) }) .on('response', function(response) { // unmodified http.IncomingMessage object response.on('data', function(data) { // compressed data as it is received console.log('received ' + data.length + ' bytes of compressed data') }) }) ``` Cookies are disabled by default (else, they would be used in subsequent requests). To enable cookies, set `jar` to `true` (either in `defaults` or `options`). ```js const request = request.defaults({jar: true}) request('http://www.google.com', function () { request('http://images.google.com') }) ``` To use a custom cookie jar (instead of `request`’s global cookie jar), set `jar` to an instance of `request.jar()` (either in `defaults` or `options`) ```js const j = request.jar() const request = request.defaults({jar:j}) request('http://www.google.com', function () { request('http://images.google.com') }) ``` OR ```js const j = request.jar(); const cookie = request.cookie('key1=value1'); const url = 'http://www.google.com'; j.setCookie(cookie, url); request({url: url, jar: j}, function () { request('http://images.google.com') }) ``` To use a custom cookie store (such as a [`FileCookieStore`](https://github.com/mitsuru/tough-cookie-filestore) which supports saving to and restoring from JSON files), pass it as a parameter to `request.jar()`: ```js const FileCookieStore = require('tough-cookie-filestore'); // NOTE - currently the 'cookies.json' file must already exist! const j = request.jar(new FileCookieStore('cookies.json')); request = request.defaults({ jar : j }) request('http://www.google.com', function() { request('http://images.google.com') }) ``` The cookie store must be a [`tough-cookie`](https://github.com/SalesforceEng/tough-cookie) store and it must support synchronous operations; see the [`CookieStore` API docs](https://github.com/SalesforceEng/tough-cookie#api) for details. To inspect your cookie jar after a request: ```js const j = request.jar() request({url: 'http://www.google.com', jar: j}, function () { const cookie_string = j.getCookieString(url); // "key1=value1; key2=value2; ..." const cookies = j.getCookies(url); // [{key: 'key1', value: 'value1', domain: "www.google.com", ...}, ...] }) ``` [back to top](#table-of-contents)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/README.md
README.md
'use strict' var extend = require('extend') var cookies = require('request/lib/cookies') var helpers = require('request/lib/helpers') var paramsHaveRequestBody = helpers.paramsHaveRequestBody // organize params for patch, post, put, head, del function initParams (uri, options, callback) { if (typeof options === 'function') { callback = options } var params = {} if (options !== null && typeof options === 'object') { extend(params, options, {uri: uri}) } else if (typeof uri === 'string') { extend(params, {uri: uri}) } else { extend(params, uri) } params.callback = callback || params.callback return params } function request (uri, options, callback) { if (typeof uri === 'undefined') { throw new Error('undefined is not a valid uri or options object.') } var params = initParams(uri, options, callback) if (params.method === 'HEAD' && paramsHaveRequestBody(params)) { throw new Error('HTTP HEAD requests MUST NOT include a request body.') } return new request.Request(params) } function verbFunc (verb) { var method = verb.toUpperCase() return function (uri, options, callback) { var params = initParams(uri, options, callback) params.method = method return request(params, params.callback) } } // define like this to please codeintel/intellisense IDEs request.get = verbFunc('get') request.head = verbFunc('head') request.options = verbFunc('options') request.post = verbFunc('post') request.put = verbFunc('put') request.patch = verbFunc('patch') request.del = verbFunc('delete') request['delete'] = verbFunc('delete') request.jar = function (store) { return cookies.jar(store) } request.cookie = function (str) { return cookies.parse(str) } function wrapRequestMethod (method, options, requester, verb) { return function (uri, opts, callback) { var params = initParams(uri, opts, callback) var target = {} extend(true, target, options, params) target.pool = params.pool || options.pool if (verb) { target.method = verb.toUpperCase() } if (typeof requester === 'function') { method = requester } return method(target, target.callback) } } request.defaults = function (options, requester) { var self = this options = options || {} if (typeof options === 'function') { requester = options options = {} } var defaults = wrapRequestMethod(self, options, requester) var verbs = ['get', 'head', 'post', 'put', 'patch', 'del', 'delete'] verbs.forEach(function (verb) { defaults[verb] = wrapRequestMethod(self[verb], options, requester, verb) }) defaults.cookie = wrapRequestMethod(self.cookie, options, requester) defaults.jar = self.jar defaults.defaults = self.defaults return defaults } request.forever = function (agentOptions, optionsArg) { var options = {} if (optionsArg) { extend(options, optionsArg) } if (agentOptions) { options.agentOptions = agentOptions } options.forever = true return request.defaults(options) } // Exports module.exports = request request.Request = require('request/request') request.initParams = initParams // Backwards compatibility for request.debug Object.defineProperty(request, 'debug', { enumerable: true, get: function () { return request.Request.debug }, set: function (debug) { request.Request.debug = debug } })
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/index.js
index.js
## Change Log ### v2.88.0 (2018/08/10) - [#2996](https://github.com/request/request/pull/2996) fix(uuid): import versioned uuid (@kwonoj) - [#2994](https://github.com/request/request/pull/2994) Update to oauth-sign 0.9.0 (@dlecocq) - [#2993](https://github.com/request/request/pull/2993) Fix header tests (@simov) - [#2904](https://github.com/request/request/pull/2904) #515, #2894 Strip port suffix from Host header if the protocol is known. (#2904) (@paambaati) - [#2791](https://github.com/request/request/pull/2791) Improve AWS SigV4 support. (#2791) (@vikhyat) - [#2977](https://github.com/request/request/pull/2977) Update test certificates (@simov) ### v2.87.0 (2018/05/21) - [#2943](https://github.com/request/request/pull/2943) Replace hawk dependency with a local implemenation (#2943) (@hueniverse) ### v2.86.0 (2018/05/15) - [#2885](https://github.com/request/request/pull/2885) Remove redundant code (for Node.js 0.9.4 and below) and dependency (@ChALkeR) - [#2942](https://github.com/request/request/pull/2942) Make Test GREEN Again! (@simov) - [#2923](https://github.com/request/request/pull/2923) Alterations for failing CI tests (@gareth-robinson) ### v2.85.0 (2018/03/12) - [#2880](https://github.com/request/request/pull/2880) Revert "Update hawk to 7.0.7 (#2880)" (@simov) ### v2.84.0 (2018/03/12) - [#2793](https://github.com/request/request/pull/2793) Fixed calculation of oauth_body_hash, issue #2792 (@dvishniakov) - [#2880](https://github.com/request/request/pull/2880) Update hawk to 7.0.7 (#2880) (@kornel-kedzierski) ### v2.83.0 (2017/09/27) - [#2776](https://github.com/request/request/pull/2776) Updating tough-cookie due to security fix. (#2776) (@karlnorling) ### v2.82.0 (2017/09/19) - [#2703](https://github.com/request/request/pull/2703) Add Node.js v8 to Travis CI (@ryysud) - [#2751](https://github.com/request/request/pull/2751) Update of hawk and qs to latest version (#2751) (@Olivier-Moreau) - [#2658](https://github.com/request/request/pull/2658) Fixed some text in README.md (#2658) (@Marketionist) - [#2635](https://github.com/request/request/pull/2635) chore(package): update aws-sign2 to version 0.7.0 (#2635) (@greenkeeperio-bot) - [#2641](https://github.com/request/request/pull/2641) Update README to simplify & update convenience methods (#2641) (@FredKSchott) - [#2541](https://github.com/request/request/pull/2541) Add convenience method for HTTP OPTIONS (#2541) (@jamesseanwright) - [#2605](https://github.com/request/request/pull/2605) Add promise support section to README (#2605) (@FredKSchott) - [#2579](https://github.com/request/request/pull/2579) refactor(lint): replace eslint with standard (#2579) (@ahmadnassri) - [#2598](https://github.com/request/request/pull/2598) Update codecov to version 2.0.2 🚀 (@greenkeeperio-bot) - [#2590](https://github.com/request/request/pull/2590) Adds test-timing keepAlive test (@nicjansma) - [#2589](https://github.com/request/request/pull/2589) fix tabulation on request example README.MD (@odykyi) - [#2594](https://github.com/request/request/pull/2594) chore(dependencies): har-validator to 5.x [removes babel dep] (@ahmadnassri) ### v2.81.0 (2017/03/09) - [#2584](https://github.com/request/request/pull/2584) Security issue: Upgrade qs to version 6.4.0 (@sergejmueller) - [#2578](https://github.com/request/request/pull/2578) safe-buffer doesn't zero-fill by default, its just a polyfill. (#2578) (@mikeal) - [#2566](https://github.com/request/request/pull/2566) Timings: Tracks 'lookup', adds 'wait' time, fixes connection re-use (#2566) (@nicjansma) - [#2574](https://github.com/request/request/pull/2574) Migrating to safe-buffer for improved security. (@mikeal) - [#2573](https://github.com/request/request/pull/2573) fixes #2572 (@ahmadnassri) ### v2.80.0 (2017/03/04) - [#2571](https://github.com/request/request/pull/2571) Correctly format the Host header for IPv6 addresses (@JamesMGreene) - [#2558](https://github.com/request/request/pull/2558) Update README.md example snippet (@FredKSchott) - [#2221](https://github.com/request/request/pull/2221) Adding a simple Response object reference in argument specification (@calamarico) - [#2452](https://github.com/request/request/pull/2452) Adds .timings array with DNC, TCP, request and response times (@nicjansma) - [#2553](https://github.com/request/request/pull/2553) add ISSUE_TEMPLATE, move PR template (@FredKSchott) - [#2539](https://github.com/request/request/pull/2539) Create PULL_REQUEST_TEMPLATE.md (@FredKSchott) - [#2524](https://github.com/request/request/pull/2524) Update caseless to version 0.12.0 🚀 (@greenkeeperio-bot) - [#2460](https://github.com/request/request/pull/2460) Fix wrong MIME type in example (@OwnageIsMagic) - [#2514](https://github.com/request/request/pull/2514) Change tags to keywords in package.json (@humphd) - [#2492](https://github.com/request/request/pull/2492) More lenient gzip decompression (@addaleax) ### v2.79.0 (2016/11/18) - [#2368](https://github.com/request/request/pull/2368) Fix typeof check in test-pool.js (@forivall) - [#2394](https://github.com/request/request/pull/2394) Use `files` in package.json (@SimenB) - [#2463](https://github.com/request/request/pull/2463) AWS support for session tokens for temporary credentials (@simov) - [#2467](https://github.com/request/request/pull/2467) Migrate to uuid (@simov, @antialias) - [#2459](https://github.com/request/request/pull/2459) Update taper to version 0.5.0 🚀 (@greenkeeperio-bot) - [#2448](https://github.com/request/request/pull/2448) Make other connect timeout test more reliable too (@mscdex) ### v2.78.0 (2016/11/03) - [#2447](https://github.com/request/request/pull/2447) Always set request timeout on keep-alive connections (@mscdex) ### v2.77.0 (2016/11/03) - [#2439](https://github.com/request/request/pull/2439) Fix socket 'connect' listener handling (@mscdex) - [#2442](https://github.com/request/request/pull/2442) 👻😱 Node.js 0.10 is unmaintained 😱👻 (@greenkeeperio-bot) - [#2435](https://github.com/request/request/pull/2435) Add followOriginalHttpMethod to redirect to original HTTP method (@kirrg001) - [#2414](https://github.com/request/request/pull/2414) Improve test-timeout reliability (@mscdex) ### v2.76.0 (2016/10/25) - [#2424](https://github.com/request/request/pull/2424) Handle buffers directly instead of using "bl" (@zertosh) - [#2415](https://github.com/request/request/pull/2415) Re-enable timeout tests on Travis + other fixes (@mscdex) - [#2431](https://github.com/request/request/pull/2431) Improve timeouts accuracy and node v6.8.0+ compatibility (@mscdex, @greenkeeperio-bot) - [#2428](https://github.com/request/request/pull/2428) Update qs to version 6.3.0 🚀 (@greenkeeperio-bot) - [#2420](https://github.com/request/request/pull/2420) change .on to .once, remove possible memory leaks (@duereg) - [#2426](https://github.com/request/request/pull/2426) Remove "isFunction" helper in favor of "typeof" check (@zertosh) - [#2425](https://github.com/request/request/pull/2425) Simplify "defer" helper creation (@zertosh) - [#2402](https://github.com/request/request/pull/2402) [email protected] breaks build 🚨 (@greenkeeperio-bot) - [#2393](https://github.com/request/request/pull/2393) Update form-data to version 2.1.0 🚀 (@greenkeeperio-bot) ### v2.75.0 (2016/09/17) - [#2381](https://github.com/request/request/pull/2381) Drop support for Node 0.10 (@simov) - [#2377](https://github.com/request/request/pull/2377) Update form-data to version 2.0.0 🚀 (@greenkeeperio-bot) - [#2353](https://github.com/request/request/pull/2353) Add greenkeeper ignored packages (@simov) - [#2351](https://github.com/request/request/pull/2351) Update karma-tap to version 3.0.1 🚀 (@greenkeeperio-bot) - [#2348](https://github.com/request/request/pull/2348) [email protected] breaks build 🚨 (@greenkeeperio-bot) - [#2349](https://github.com/request/request/pull/2349) Check error type instead of string (@scotttrinh) ### v2.74.0 (2016/07/22) - [#2295](https://github.com/request/request/pull/2295) Update tough-cookie to 2.3.0 (@stash-sfdc) - [#2280](https://github.com/request/request/pull/2280) Update karma-tap to version 2.0.1 🚀 (@greenkeeperio-bot) ### v2.73.0 (2016/07/09) - [#2240](https://github.com/request/request/pull/2240) Remove connectionErrorHandler to fix #1903 (@zarenner) - [#2251](https://github.com/request/request/pull/2251) [email protected] breaks build 🚨 (@greenkeeperio-bot) - [#2225](https://github.com/request/request/pull/2225) Update docs (@ArtskydJ) - [#2203](https://github.com/request/request/pull/2203) Update browserify to version 13.0.1 🚀 (@greenkeeperio-bot) - [#2275](https://github.com/request/request/pull/2275) Update karma to version 1.1.1 🚀 (@greenkeeperio-bot) - [#2204](https://github.com/request/request/pull/2204) Add codecov.yml and disable PR comments (@simov) - [#2212](https://github.com/request/request/pull/2212) Fix link to http.IncomingMessage documentation (@nazieb) - [#2208](https://github.com/request/request/pull/2208) Update to form-data RC4 and pass null values to it (@simov) - [#2207](https://github.com/request/request/pull/2207) Move aws4 require statement to the top (@simov) - [#2199](https://github.com/request/request/pull/2199) Update karma-coverage to version 1.0.0 🚀 (@greenkeeperio-bot) - [#2206](https://github.com/request/request/pull/2206) Update qs to version 6.2.0 🚀 (@greenkeeperio-bot) - [#2205](https://github.com/request/request/pull/2205) Use server-destory to close hanging sockets in tests (@simov) - [#2200](https://github.com/request/request/pull/2200) Update karma-cli to version 1.0.0 🚀 (@greenkeeperio-bot) ### v2.72.0 (2016/04/17) - [#2176](https://github.com/request/request/pull/2176) Do not try to pipe Gzip responses with no body (@simov) - [#2175](https://github.com/request/request/pull/2175) Add 'delete' alias for the 'del' API method (@simov, @MuhanZou) - [#2172](https://github.com/request/request/pull/2172) Add support for deflate content encoding (@czardoz) - [#2169](https://github.com/request/request/pull/2169) Add callback option (@simov) - [#2165](https://github.com/request/request/pull/2165) Check for self.req existence inside the write method (@simov) - [#2167](https://github.com/request/request/pull/2167) Fix TravisCI badge reference master branch (@a0viedo) ### v2.71.0 (2016/04/12) - [#2164](https://github.com/request/request/pull/2164) Catch errors from the underlying http module (@simov) ### v2.70.0 (2016/04/05) - [#2147](https://github.com/request/request/pull/2147) Update eslint to version 2.5.3 🚀 (@simov, @greenkeeperio-bot) - [#2009](https://github.com/request/request/pull/2009) Support JSON stringify replacer argument. (@elyobo) - [#2142](https://github.com/request/request/pull/2142) Update eslint to version 2.5.1 🚀 (@greenkeeperio-bot) - [#2128](https://github.com/request/request/pull/2128) Update browserify-istanbul to version 2.0.0 🚀 (@greenkeeperio-bot) - [#2115](https://github.com/request/request/pull/2115) Update eslint to version 2.3.0 🚀 (@simov, @greenkeeperio-bot) - [#2089](https://github.com/request/request/pull/2089) Fix badges (@simov) - [#2092](https://github.com/request/request/pull/2092) Update browserify-istanbul to version 1.0.0 🚀 (@greenkeeperio-bot) - [#2079](https://github.com/request/request/pull/2079) Accept read stream as body option (@simov) - [#2070](https://github.com/request/request/pull/2070) Update bl to version 1.1.2 🚀 (@greenkeeperio-bot) - [#2063](https://github.com/request/request/pull/2063) Up bluebird and oauth-sign (@simov) - [#2058](https://github.com/request/request/pull/2058) Karma fixes for latest versions (@eiriksm) - [#2057](https://github.com/request/request/pull/2057) Update contributing guidelines (@simov) - [#2054](https://github.com/request/request/pull/2054) Update qs to version 6.1.0 🚀 (@greenkeeperio-bot) ### v2.69.0 (2016/01/27) - [#2041](https://github.com/request/request/pull/2041) restore aws4 as regular dependency (@rmg) ### v2.68.0 (2016/01/27) - [#2036](https://github.com/request/request/pull/2036) Add AWS Signature Version 4 (@simov, @mirkods) - [#2022](https://github.com/request/request/pull/2022) Convert numeric multipart bodies to string (@simov, @feross) - [#2024](https://github.com/request/request/pull/2024) Update har-validator dependency for nsp advisory #76 (@TylerDixon) - [#2016](https://github.com/request/request/pull/2016) Update qs to version 6.0.2 🚀 (@greenkeeperio-bot) - [#2007](https://github.com/request/request/pull/2007) Use the `extend` module instead of util._extend (@simov) - [#2003](https://github.com/request/request/pull/2003) Update browserify to version 13.0.0 🚀 (@greenkeeperio-bot) - [#1989](https://github.com/request/request/pull/1989) Update buffer-equal to version 1.0.0 🚀 (@greenkeeperio-bot) - [#1956](https://github.com/request/request/pull/1956) Check form-data content-length value before setting up the header (@jongyoonlee) - [#1958](https://github.com/request/request/pull/1958) Use IncomingMessage.destroy method (@simov) - [#1952](https://github.com/request/request/pull/1952) Adds example for Tor proxy (@prometheansacrifice) - [#1943](https://github.com/request/request/pull/1943) Update eslint to version 1.10.3 🚀 (@simov, @greenkeeperio-bot) - [#1924](https://github.com/request/request/pull/1924) Update eslint to version 1.10.1 🚀 (@greenkeeperio-bot) - [#1915](https://github.com/request/request/pull/1915) Remove content-length and transfer-encoding headers from defaultProxyHeaderWhiteList (@yaxia) ### v2.67.0 (2015/11/19) - [#1913](https://github.com/request/request/pull/1913) Update http-signature to version 1.1.0 🚀 (@greenkeeperio-bot) ### v2.66.0 (2015/11/18) - [#1906](https://github.com/request/request/pull/1906) Update README URLs based on HTTP redirects (@ReadmeCritic) - [#1905](https://github.com/request/request/pull/1905) Convert typed arrays into regular buffers (@simov) - [#1902](https://github.com/request/request/pull/1902) [email protected] breaks build 🚨 (@greenkeeperio-bot) - [#1894](https://github.com/request/request/pull/1894) Fix tunneling after redirection from https (Original: #1881) (@simov, @falms) - [#1893](https://github.com/request/request/pull/1893) Update eslint to version 1.9.0 🚀 (@greenkeeperio-bot) - [#1852](https://github.com/request/request/pull/1852) Update eslint to version 1.7.3 🚀 (@simov, @greenkeeperio-bot, @paulomcnally, @michelsalib, @arbaaz, @nsklkn, @LoicMahieu, @JoshWillik, @jzaefferer, @ryanwholey, @djchie, @thisconnect, @mgenereu, @acroca, @Sebmaster, @KoltesDigital) - [#1876](https://github.com/request/request/pull/1876) Implement loose matching for har mime types (@simov) - [#1875](https://github.com/request/request/pull/1875) Update bluebird to version 3.0.2 🚀 (@simov, @greenkeeperio-bot) - [#1871](https://github.com/request/request/pull/1871) Update browserify to version 12.0.1 🚀 (@greenkeeperio-bot) - [#1866](https://github.com/request/request/pull/1866) Add missing quotes on x-token property in README (@miguelmota) - [#1874](https://github.com/request/request/pull/1874) Fix typo in README.md (@gswalden) - [#1860](https://github.com/request/request/pull/1860) Improve referer header tests and docs (@simov) - [#1861](https://github.com/request/request/pull/1861) Remove redundant call to Stream constructor (@watson) - [#1857](https://github.com/request/request/pull/1857) Fix Referer header to point to the original host name (@simov) - [#1850](https://github.com/request/request/pull/1850) Update karma-coverage to version 0.5.3 🚀 (@greenkeeperio-bot) - [#1847](https://github.com/request/request/pull/1847) Use node's latest version when building (@simov) - [#1836](https://github.com/request/request/pull/1836) Tunnel: fix wrong property name (@KoltesDigital) - [#1820](https://github.com/request/request/pull/1820) Set href as request.js uses it (@mgenereu) - [#1840](https://github.com/request/request/pull/1840) Update http-signature to version 1.0.2 🚀 (@greenkeeperio-bot) - [#1845](https://github.com/request/request/pull/1845) Update istanbul to version 0.4.0 🚀 (@greenkeeperio-bot) ### v2.65.0 (2015/10/11) - [#1833](https://github.com/request/request/pull/1833) Update aws-sign2 to version 0.6.0 🚀 (@greenkeeperio-bot) - [#1811](https://github.com/request/request/pull/1811) Enable loose cookie parsing in tough-cookie (@Sebmaster) - [#1830](https://github.com/request/request/pull/1830) Bring back tilde ranges for all dependencies (@simov) - [#1821](https://github.com/request/request/pull/1821) Implement support for RFC 2617 MD5-sess algorithm. (@BigDSK) - [#1828](https://github.com/request/request/pull/1828) Updated qs dependency to 5.2.0 (@acroca) - [#1818](https://github.com/request/request/pull/1818) Extract `readResponseBody` method out of `onRequestResponse` (@pvoisin) - [#1819](https://github.com/request/request/pull/1819) Run stringify once (@mgenereu) - [#1814](https://github.com/request/request/pull/1814) Updated har-validator to version 2.0.2 (@greenkeeperio-bot) - [#1807](https://github.com/request/request/pull/1807) Updated tough-cookie to version 2.1.0 (@greenkeeperio-bot) - [#1800](https://github.com/request/request/pull/1800) Add caret ranges for devDependencies, except eslint (@simov) - [#1799](https://github.com/request/request/pull/1799) Updated karma-browserify to version 4.4.0 (@greenkeeperio-bot) - [#1797](https://github.com/request/request/pull/1797) Updated tape to version 4.2.0 (@greenkeeperio-bot) - [#1788](https://github.com/request/request/pull/1788) Pinned all dependencies (@greenkeeperio-bot) ### v2.64.0 (2015/09/25) - [#1787](https://github.com/request/request/pull/1787) npm ignore examples, release.sh and disabled.appveyor.yml (@thisconnect) - [#1775](https://github.com/request/request/pull/1775) Fix typo in README.md (@djchie) - [#1776](https://github.com/request/request/pull/1776) Changed word 'conjuction' to read 'conjunction' in README.md (@ryanwholey) - [#1785](https://github.com/request/request/pull/1785) Revert: Set default application/json content-type when using json option #1772 (@simov) ### v2.63.0 (2015/09/21) - [#1772](https://github.com/request/request/pull/1772) Set default application/json content-type when using json option (@jzaefferer) ### v2.62.0 (2015/09/15) - [#1768](https://github.com/request/request/pull/1768) Add node 4.0 to the list of build targets (@simov) - [#1767](https://github.com/request/request/pull/1767) Query strings now cooperate with unix sockets (@JoshWillik) - [#1750](https://github.com/request/request/pull/1750) Revert doc about installation of tough-cookie added in #884 (@LoicMahieu) - [#1746](https://github.com/request/request/pull/1746) Missed comma in Readme (@nsklkn) - [#1743](https://github.com/request/request/pull/1743) Fix options not being initialized in defaults method (@simov) ### v2.61.0 (2015/08/19) - [#1721](https://github.com/request/request/pull/1721) Minor fix in README.md (@arbaaz) - [#1733](https://github.com/request/request/pull/1733) Avoid useless Buffer transformation (@michelsalib) - [#1726](https://github.com/request/request/pull/1726) Update README.md (@paulomcnally) - [#1715](https://github.com/request/request/pull/1715) Fix forever option in node > 0.10 #1709 (@calibr) - [#1716](https://github.com/request/request/pull/1716) Do not create Buffer from Object in setContentLength(iojs v3.0 issue) (@calibr) - [#1711](https://github.com/request/request/pull/1711) Add ability to detect connect timeouts (@kevinburke) - [#1712](https://github.com/request/request/pull/1712) Set certificate expiration to August 2, 2018 (@kevinburke) - [#1700](https://github.com/request/request/pull/1700) debug() when JSON.parse() on a response body fails (@phillipj) ### v2.60.0 (2015/07/21) - [#1687](https://github.com/request/request/pull/1687) Fix caseless bug - content-type not being set for multipart/form-data (@simov, @garymathews) ### v2.59.0 (2015/07/20) - [#1671](https://github.com/request/request/pull/1671) Add tests and docs for using the agent, agentClass, agentOptions and forever options. Forever option defaults to using http(s).Agent in node 0.12+ (@simov) - [#1679](https://github.com/request/request/pull/1679) Fix - do not remove OAuth param when using OAuth realm (@simov, @jhalickman) - [#1668](https://github.com/request/request/pull/1668) updated dependencies (@deamme) - [#1656](https://github.com/request/request/pull/1656) Fix form method (@simov) - [#1651](https://github.com/request/request/pull/1651) Preserve HEAD method when using followAllRedirects (@simov) - [#1652](https://github.com/request/request/pull/1652) Update `encoding` option documentation in README.md (@daniel347x) - [#1650](https://github.com/request/request/pull/1650) Allow content-type overriding when using the `form` option (@simov) - [#1646](https://github.com/request/request/pull/1646) Clarify the nature of setting `ca` in `agentOptions` (@jeffcharles) ### v2.58.0 (2015/06/16) - [#1638](https://github.com/request/request/pull/1638) Use the `extend` module to deep extend in the defaults method (@simov) - [#1631](https://github.com/request/request/pull/1631) Move tunnel logic into separate module (@simov) - [#1634](https://github.com/request/request/pull/1634) Fix OAuth query transport_method (@simov) - [#1603](https://github.com/request/request/pull/1603) Add codecov (@simov) ### v2.57.0 (2015/05/31) - [#1615](https://github.com/request/request/pull/1615) Replace '.client' with '.socket' as the former was deprecated in 2.2.0. (@ChALkeR) ### v2.56.0 (2015/05/28) - [#1610](https://github.com/request/request/pull/1610) Bump module dependencies (@simov) - [#1600](https://github.com/request/request/pull/1600) Extract the querystring logic into separate module (@simov) - [#1607](https://github.com/request/request/pull/1607) Re-generate certificates (@simov) - [#1599](https://github.com/request/request/pull/1599) Move getProxyFromURI logic below the check for Invaild URI (#1595) (@simov) - [#1598](https://github.com/request/request/pull/1598) Fix the way http verbs are defined in order to please intellisense IDEs (@simov, @flannelJesus) - [#1591](https://github.com/request/request/pull/1591) A few minor fixes: (@simov) - [#1584](https://github.com/request/request/pull/1584) Refactor test-default tests (according to comments in #1430) (@simov) - [#1585](https://github.com/request/request/pull/1585) Fixing documentation regarding TLS options (#1583) (@mainakae) - [#1574](https://github.com/request/request/pull/1574) Refresh the oauth_nonce on redirect (#1573) (@simov) - [#1570](https://github.com/request/request/pull/1570) Discovered tests that weren't properly running (@seanstrom) - [#1569](https://github.com/request/request/pull/1569) Fix pause before response arrives (@kevinoid) - [#1558](https://github.com/request/request/pull/1558) Emit error instead of throw (@simov) - [#1568](https://github.com/request/request/pull/1568) Fix stall when piping gzipped response (@kevinoid) - [#1560](https://github.com/request/request/pull/1560) Update combined-stream (@apechimp) - [#1543](https://github.com/request/request/pull/1543) Initial support for oauth_body_hash on json payloads (@simov, @aesopwolf) - [#1541](https://github.com/request/request/pull/1541) Fix coveralls (@simov) - [#1540](https://github.com/request/request/pull/1540) Fix recursive defaults for convenience methods (@simov) - [#1536](https://github.com/request/request/pull/1536) More eslint style rules (@froatsnook) - [#1533](https://github.com/request/request/pull/1533) Adding dependency status bar to README.md (@YasharF) - [#1539](https://github.com/request/request/pull/1539) ensure the latest version of har-validator is included (@ahmadnassri) - [#1516](https://github.com/request/request/pull/1516) forever+pool test (@devTristan) ### v2.55.0 (2015/04/05) - [#1520](https://github.com/request/request/pull/1520) Refactor defaults (@simov) - [#1525](https://github.com/request/request/pull/1525) Delete request headers with undefined value. (@froatsnook) - [#1521](https://github.com/request/request/pull/1521) Add promise tests (@simov) - [#1518](https://github.com/request/request/pull/1518) Fix defaults (@simov) - [#1515](https://github.com/request/request/pull/1515) Allow static invoking of convenience methods (@simov) - [#1505](https://github.com/request/request/pull/1505) Fix multipart boundary extraction regexp (@simov) - [#1510](https://github.com/request/request/pull/1510) Fix basic auth form data (@simov) ### v2.54.0 (2015/03/24) - [#1501](https://github.com/request/request/pull/1501) HTTP Archive 1.2 support (@ahmadnassri) - [#1486](https://github.com/request/request/pull/1486) Add a test for the forever agent (@akshayp) - [#1500](https://github.com/request/request/pull/1500) Adding handling for no auth method and null bearer (@philberg) - [#1498](https://github.com/request/request/pull/1498) Add table of contents in readme (@simov) - [#1477](https://github.com/request/request/pull/1477) Add support for qs options via qsOptions key (@simov) - [#1496](https://github.com/request/request/pull/1496) Parameters encoded to base 64 should be decoded as UTF-8, not ASCII. (@albanm) - [#1494](https://github.com/request/request/pull/1494) Update eslint (@froatsnook) - [#1474](https://github.com/request/request/pull/1474) Require Colon in Basic Auth (@erykwalder) - [#1481](https://github.com/request/request/pull/1481) Fix baseUrl and redirections. (@burningtree) - [#1469](https://github.com/request/request/pull/1469) Feature/base url (@froatsnook) - [#1459](https://github.com/request/request/pull/1459) Add option to time request/response cycle (including rollup of redirects) (@aaron-em) - [#1468](https://github.com/request/request/pull/1468) Re-enable io.js/node 0.12 build (@simov, @mikeal, @BBB) - [#1442](https://github.com/request/request/pull/1442) Fixed the issue with strictSSL tests on 0.12 & io.js by explicitly setting a cipher that matches the cert. (@BBB, @nickmccurdy, @demohi, @simov, @0x4139) - [#1460](https://github.com/request/request/pull/1460) localAddress or proxy config is lost when redirecting (@simov, @0x4139) - [#1453](https://github.com/request/request/pull/1453) Test on Node.js 0.12 and io.js with allowed failures (@nickmccurdy, @demohi) - [#1426](https://github.com/request/request/pull/1426) Fixing tests to pass on io.js and node 0.12 (only test-https.js stiff failing) (@mikeal) - [#1446](https://github.com/request/request/pull/1446) Missing HTTP referer header with redirects Fixes #1038 (@simov, @guimon) - [#1428](https://github.com/request/request/pull/1428) Deprecate Node v0.8.x (@nylen) - [#1436](https://github.com/request/request/pull/1436) Add ability to set a requester without setting default options (@tikotzky) - [#1435](https://github.com/request/request/pull/1435) dry up verb methods (@sethpollack) - [#1423](https://github.com/request/request/pull/1423) Allow fully qualified multipart content-type header (@simov) - [#1430](https://github.com/request/request/pull/1430) Fix recursive requester (@tikotzky) - [#1429](https://github.com/request/request/pull/1429) Throw error when making HEAD request with a body (@tikotzky) - [#1419](https://github.com/request/request/pull/1419) Add note that the project is broken in 0.12.x (@nylen) - [#1413](https://github.com/request/request/pull/1413) Fix basic auth (@simov) - [#1397](https://github.com/request/request/pull/1397) Improve pipe-from-file tests (@nylen) ### v2.53.0 (2015/02/02) - [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov) - [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson) ### v2.52.0 (2015/02/02) - [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen) - [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao) - [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom) - [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen) - [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm) - [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov) - [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen) - [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen) - [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov) - [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen) - [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov) - [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway) - [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik) - [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm) - [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom) - [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen) - [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky) - [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen) - [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig) - [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen) - [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm) - [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen) - [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov) - [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom) - [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen) - [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom) - [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen) - [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov, @nylen, @apoco, @DullReferenceException, @mmalecki, @oliamb, @cliffcrosland, @LewisJEllis, @eiriksm, @poislagarde) - [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov) - [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov) ### v2.51.0 (2014/12/10) - [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov) ### v2.50.0 (2014/12/09) - [#1308](https://github.com/request/request/pull/1308) Add browser test to keep track of browserify compability. (@eiriksm) - [#1299](https://github.com/request/request/pull/1299) Add optional support for jsonReviver (@poislagarde) - [#1277](https://github.com/request/request/pull/1277) Add Coveralls configuration (@simov) - [#1307](https://github.com/request/request/pull/1307) Upgrade form-data, add back browserify compability. Fixes #455. (@eiriksm) - [#1305](https://github.com/request/request/pull/1305) Fix typo in README.md (@LewisJEllis) - [#1288](https://github.com/request/request/pull/1288) Update README.md to explain custom file use case (@cliffcrosland) ### v2.49.0 (2014/11/28) - [#1295](https://github.com/request/request/pull/1295) fix(proxy): no-proxy false positive (@oliamb) - [#1292](https://github.com/request/request/pull/1292) Upgrade `caseless` to 0.8.1 (@mmalecki) - [#1276](https://github.com/request/request/pull/1276) Set transfer encoding for multipart/related to chunked by default (@simov) - [#1275](https://github.com/request/request/pull/1275) Fix multipart content-type headers detection (@simov) - [#1269](https://github.com/request/request/pull/1269) adds streams example for review (@tbuchok) - [#1238](https://github.com/request/request/pull/1238) Add examples README.md (@simov) ### v2.48.0 (2014/11/12) - [#1263](https://github.com/request/request/pull/1263) Fixed a syntax error / typo in README.md (@xna2) - [#1253](https://github.com/request/request/pull/1253) Add multipart chunked flag (@simov, @nylen) - [#1251](https://github.com/request/request/pull/1251) Clarify that defaults() does not modify global defaults (@nylen) - [#1250](https://github.com/request/request/pull/1250) Improve documentation for pool and maxSockets options (@nylen) - [#1237](https://github.com/request/request/pull/1237) Documenting error handling when using streams (@vmattos) - [#1244](https://github.com/request/request/pull/1244) Finalize changelog command (@nylen) - [#1241](https://github.com/request/request/pull/1241) Fix typo (@alexanderGugel) - [#1223](https://github.com/request/request/pull/1223) Show latest version number instead of "upcoming" in changelog (@nylen) - [#1236](https://github.com/request/request/pull/1236) Document how to use custom CA in README (#1229) (@hypesystem) - [#1228](https://github.com/request/request/pull/1228) Support for oauth with RSA-SHA1 signing (@nylen) - [#1216](https://github.com/request/request/pull/1216) Made json and multipart options coexist (@nylen, @simov) - [#1225](https://github.com/request/request/pull/1225) Allow header white/exclusive lists in any case. (@RReverser) ### v2.47.0 (2014/10/26) - [#1222](https://github.com/request/request/pull/1222) Move from mikeal/request to request/request (@nylen) - [#1220](https://github.com/request/request/pull/1220) update qs dependency to 2.3.1 (@FredKSchott) - [#1212](https://github.com/request/request/pull/1212) Improve tests/test-timeout.js (@nylen) - [#1219](https://github.com/request/request/pull/1219) remove old globalAgent workaround for node 0.4 (@request) - [#1214](https://github.com/request/request/pull/1214) Remove cruft left over from optional dependencies (@nylen) - [#1215](https://github.com/request/request/pull/1215) Add proxyHeaderExclusiveList option for proxy-only headers. (@RReverser) - [#1211](https://github.com/request/request/pull/1211) Allow 'Host' header instead of 'host' and remember case across redirects (@nylen) - [#1208](https://github.com/request/request/pull/1208) Improve release script (@nylen) - [#1213](https://github.com/request/request/pull/1213) Support for custom cookie store (@nylen, @mitsuru) - [#1197](https://github.com/request/request/pull/1197) Clean up some code around setting the agent (@FredKSchott) - [#1209](https://github.com/request/request/pull/1209) Improve multipart form append test (@simov) - [#1207](https://github.com/request/request/pull/1207) Update changelog (@nylen) - [#1185](https://github.com/request/request/pull/1185) Stream multipart/related bodies (@simov) ### v2.46.0 (2014/10/23) - [#1198](https://github.com/request/request/pull/1198) doc for TLS/SSL protocol options (@shawnzhu) - [#1200](https://github.com/request/request/pull/1200) Add a Gitter chat badge to README.md (@gitter-badger) - [#1196](https://github.com/request/request/pull/1196) Upgrade taper test reporter to v0.3.0 (@nylen) - [#1199](https://github.com/request/request/pull/1199) Fix lint error: undeclared var i (@nylen) - [#1191](https://github.com/request/request/pull/1191) Move self.proxy decision logic out of init and into a helper (@FredKSchott) - [#1190](https://github.com/request/request/pull/1190) Move _buildRequest() logic back into init (@FredKSchott) - [#1186](https://github.com/request/request/pull/1186) Support Smarter Unix URL Scheme (@FredKSchott) - [#1178](https://github.com/request/request/pull/1178) update form documentation for new usage (@FredKSchott) - [#1180](https://github.com/request/request/pull/1180) Enable no-mixed-requires linting rule (@nylen) - [#1184](https://github.com/request/request/pull/1184) Don't forward authorization header across redirects to different hosts (@nylen) - [#1183](https://github.com/request/request/pull/1183) Correct README about pre and postamble CRLF using multipart and not mult... (@netpoetica) - [#1179](https://github.com/request/request/pull/1179) Lint tests directory (@nylen) - [#1169](https://github.com/request/request/pull/1169) add metadata for form-data file field (@dotcypress) - [#1173](https://github.com/request/request/pull/1173) remove optional dependencies (@seanstrom) - [#1165](https://github.com/request/request/pull/1165) Cleanup event listeners and remove function creation from init (@FredKSchott) - [#1174](https://github.com/request/request/pull/1174) update the request.cookie docs to have a valid cookie example (@seanstrom) - [#1168](https://github.com/request/request/pull/1168) create a detach helper and use detach helper in replace of nextTick (@seanstrom) - [#1171](https://github.com/request/request/pull/1171) in post can send form data and use callback (@MiroRadenovic) - [#1159](https://github.com/request/request/pull/1159) accept charset for x-www-form-urlencoded content-type (@seanstrom) - [#1157](https://github.com/request/request/pull/1157) Update README.md: body with json=true (@Rob--W) - [#1164](https://github.com/request/request/pull/1164) Disable tests/test-timeout.js on Travis (@nylen) - [#1153](https://github.com/request/request/pull/1153) Document how to run a single test (@nylen) - [#1144](https://github.com/request/request/pull/1144) adds documentation for the "response" event within the streaming section (@tbuchok) - [#1162](https://github.com/request/request/pull/1162) Update eslintrc file to no longer allow past errors (@FredKSchott) - [#1155](https://github.com/request/request/pull/1155) Support/use self everywhere (@seanstrom) - [#1161](https://github.com/request/request/pull/1161) fix no-use-before-define lint warnings (@emkay) - [#1156](https://github.com/request/request/pull/1156) adding curly brackets to get rid of lint errors (@emkay) - [#1151](https://github.com/request/request/pull/1151) Fix localAddress test on OS X (@nylen) - [#1145](https://github.com/request/request/pull/1145) documentation: fix outdated reference to setCookieSync old name in README (@FredKSchott) - [#1131](https://github.com/request/request/pull/1131) Update pool documentation (@FredKSchott) - [#1143](https://github.com/request/request/pull/1143) Rewrite all tests to use tape (@nylen) - [#1137](https://github.com/request/request/pull/1137) Add ability to specifiy querystring lib in options. (@jgrund) - [#1138](https://github.com/request/request/pull/1138) allow hostname and port in place of host on uri (@cappslock) - [#1134](https://github.com/request/request/pull/1134) Fix multiple redirects and `self.followRedirect` (@blakeembrey) - [#1130](https://github.com/request/request/pull/1130) documentation fix: add note about npm test for contributing (@FredKSchott) - [#1120](https://github.com/request/request/pull/1120) Support/refactor request setup tunnel (@seanstrom) - [#1129](https://github.com/request/request/pull/1129) linting fix: convert double quote strings to use single quotes (@FredKSchott) - [#1124](https://github.com/request/request/pull/1124) linting fix: remove unneccesary semi-colons (@FredKSchott) ### v2.45.0 (2014/10/06) - [#1128](https://github.com/request/request/pull/1128) Add test for setCookie regression (@nylen) - [#1127](https://github.com/request/request/pull/1127) added tests around using objects as values in a query string (@bcoe) - [#1103](https://github.com/request/request/pull/1103) Support/refactor request constructor (@nylen, @seanstrom) - [#1119](https://github.com/request/request/pull/1119) add basic linting to request library (@FredKSchott) - [#1121](https://github.com/request/request/pull/1121) Revert "Explicitly use sync versions of cookie functions" (@nylen) - [#1118](https://github.com/request/request/pull/1118) linting fix: Restructure bad empty if statement (@FredKSchott) - [#1117](https://github.com/request/request/pull/1117) Fix a bad check for valid URIs (@FredKSchott) - [#1113](https://github.com/request/request/pull/1113) linting fix: space out operators (@FredKSchott) - [#1116](https://github.com/request/request/pull/1116) Fix typo in `noProxyHost` definition (@FredKSchott) - [#1114](https://github.com/request/request/pull/1114) linting fix: Added a `new` operator that was missing when creating and throwing a new error (@FredKSchott) - [#1096](https://github.com/request/request/pull/1096) No_proxy support (@samcday) - [#1107](https://github.com/request/request/pull/1107) linting-fix: remove unused variables (@FredKSchott) - [#1112](https://github.com/request/request/pull/1112) linting fix: Make return values consistent and more straitforward (@FredKSchott) - [#1111](https://github.com/request/request/pull/1111) linting fix: authPieces was getting redeclared (@FredKSchott) - [#1105](https://github.com/request/request/pull/1105) Use strict mode in request (@FredKSchott) - [#1110](https://github.com/request/request/pull/1110) linting fix: replace lazy '==' with more strict '===' (@FredKSchott) - [#1109](https://github.com/request/request/pull/1109) linting fix: remove function call from if-else conditional statement (@FredKSchott) - [#1102](https://github.com/request/request/pull/1102) Fix to allow setting a `requester` on recursive calls to `request.defaults` (@tikotzky) - [#1095](https://github.com/request/request/pull/1095) Tweaking engines in package.json (@pdehaan) - [#1082](https://github.com/request/request/pull/1082) Forward the socket event from the httpModule request (@seanstrom) - [#972](https://github.com/request/request/pull/972) Clarify gzip handling in the README (@kevinoid) - [#1089](https://github.com/request/request/pull/1089) Mention that encoding defaults to utf8, not Buffer (@stuartpb) - [#1088](https://github.com/request/request/pull/1088) Fix cookie example in README.md and make it more clear (@pipi32167) - [#1027](https://github.com/request/request/pull/1027) Add support for multipart form data in request options. (@crocket) - [#1076](https://github.com/request/request/pull/1076) use Request.abort() to abort the request when the request has timed-out (@seanstrom) - [#1068](https://github.com/request/request/pull/1068) add optional postamble required by .NET multipart requests (@netpoetica) ### v2.43.0 (2014/09/18) - [#1057](https://github.com/request/request/pull/1057) Defaults should not overwrite defined options (@davidwood) - [#1046](https://github.com/request/request/pull/1046) Propagate datastream errors, useful in case gzip fails. (@ZJONSSON, @Janpot) - [#1063](https://github.com/request/request/pull/1063) copy the input headers object #1060 (@finnp) - [#1031](https://github.com/request/request/pull/1031) Explicitly use sync versions of cookie functions (@ZJONSSON) - [#1056](https://github.com/request/request/pull/1056) Fix redirects when passing url.parse(x) as URL to convenience method (@nylen) ### v2.42.0 (2014/09/04) - [#1053](https://github.com/request/request/pull/1053) Fix #1051 Parse auth properly when using non-tunneling proxy (@isaacs) ### v2.41.0 (2014/09/04) - [#1050](https://github.com/request/request/pull/1050) Pass whitelisted headers to tunneling proxy. Organize all tunneling logic. (@isaacs, @Feldhacker) - [#1035](https://github.com/request/request/pull/1035) souped up nodei.co badge (@rvagg) - [#1048](https://github.com/request/request/pull/1048) Aws is now possible over a proxy (@steven-aerts) - [#1039](https://github.com/request/request/pull/1039) extract out helper functions to a helper file (@seanstrom) - [#1021](https://github.com/request/request/pull/1021) Support/refactor indexjs (@seanstrom) - [#1033](https://github.com/request/request/pull/1033) Improve and document debug options (@nylen) - [#1034](https://github.com/request/request/pull/1034) Fix readme headings (@nylen) - [#1030](https://github.com/request/request/pull/1030) Allow recursive request.defaults (@tikotzky) - [#1029](https://github.com/request/request/pull/1029) Fix a couple of typos (@nylen) - [#675](https://github.com/request/request/pull/675) Checking for SSL fault on connection before reading SSL properties (@VRMink) - [#989](https://github.com/request/request/pull/989) Added allowRedirect function. Should return true if redirect is allowed or false otherwise (@doronin) - [#1025](https://github.com/request/request/pull/1025) [fixes #1023] Set self._ended to true once response has ended (@mridgway) - [#1020](https://github.com/request/request/pull/1020) Add back removed debug metadata (@FredKSchott) - [#1008](https://github.com/request/request/pull/1008) Moving to module instead of cutomer buffer concatenation. (@mikeal) - [#770](https://github.com/request/request/pull/770) Added dependency badge for README file; (@timgluz, @mafintosh, @lalitkapoor, @stash, @bobyrizov) - [#1016](https://github.com/request/request/pull/1016) toJSON no longer results in an infinite loop, returns simple objects (@FredKSchott) - [#1018](https://github.com/request/request/pull/1018) Remove pre-0.4.4 HTTPS fix (@mmalecki) - [#1006](https://github.com/request/request/pull/1006) Migrate to caseless, fixes #1001 (@mikeal) - [#995](https://github.com/request/request/pull/995) Fix parsing array of objects (@sjonnet19) - [#999](https://github.com/request/request/pull/999) Fix fallback for browserify for optional modules. (@eiriksm) - [#996](https://github.com/request/request/pull/996) Wrong oauth signature when multiple same param keys exist [updated] (@bengl) ### v2.40.0 (2014/08/06) - [#992](https://github.com/request/request/pull/992) Fix security vulnerability. Update qs (@poeticninja) - [#988](https://github.com/request/request/pull/988) “--” -> “—” (@upisfree) - [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna) ### v2.39.0 (2014/07/24) - [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko) ### v2.38.0 (2014/07/22) - [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked) - [#884](https://github.com/request/request/pull/884) Documented tough-cookie installation. (@wbyoung) - [#935](https://github.com/request/request/pull/935) Correct repository url (@fritx) - [#963](https://github.com/request/request/pull/963) Update changelog (@nylen) - [#960](https://github.com/request/request/pull/960) Support gzip with encoding on node pre-v0.9.4 (@kevinoid) - [#953](https://github.com/request/request/pull/953) Add async Content-Length computation when using form-data (@LoicMahieu) - [#844](https://github.com/request/request/pull/844) Add support for HTTP[S]_PROXY environment variables. Fixes #595. (@jvmccarthy) - [#946](https://github.com/request/request/pull/946) defaults: merge headers (@aj0strow) ### v2.37.0 (2014/07/07) - [#957](https://github.com/request/request/pull/957) Silence EventEmitter memory leak warning #311 (@watson) - [#955](https://github.com/request/request/pull/955) check for content-length header before setting it in nextTick (@camilleanne) - [#951](https://github.com/request/request/pull/951) Add support for gzip content decoding (@kevinoid) - [#949](https://github.com/request/request/pull/949) Manually enter querystring in form option (@charlespwd) - [#944](https://github.com/request/request/pull/944) Make request work with browserify (@eiriksm) - [#943](https://github.com/request/request/pull/943) New mime module (@eiriksm) - [#927](https://github.com/request/request/pull/927) Bump version of hawk dep. (@samccone) - [#907](https://github.com/request/request/pull/907) append secureOptions to poolKey (@medovob) ### v2.35.0 (2014/05/17) - [#901](https://github.com/request/request/pull/901) Fixes #555 (@pigulla) - [#897](https://github.com/request/request/pull/897) merge with default options (@vohof) - [#891](https://github.com/request/request/pull/891) fixes 857 - options object is mutated by calling request (@lalitkapoor) - [#869](https://github.com/request/request/pull/869) Pipefilter test (@tgohn) - [#866](https://github.com/request/request/pull/866) Fix typo (@dandv) - [#861](https://github.com/request/request/pull/861) Add support for RFC 6750 Bearer Tokens (@phedny) - [#809](https://github.com/request/request/pull/809) upgrade tunnel-proxy to 0.4.0 (@ksato9700) - [#850](https://github.com/request/request/pull/850) Fix word consistency in readme (@0xNobody) - [#810](https://github.com/request/request/pull/810) add some exposition to mpu example in README.md (@mikermcneil) - [#840](https://github.com/request/request/pull/840) improve error reporting for invalid protocols (@FND) - [#821](https://github.com/request/request/pull/821) added secureOptions back (@nw) - [#815](https://github.com/request/request/pull/815) Create changelog based on pull requests (@lalitkapoor) ### v2.34.0 (2014/02/18) - [#516](https://github.com/request/request/pull/516) UNIX Socket URL Support (@lyuzashi) - [#801](https://github.com/request/request/pull/801) 794 ignore cookie parsing and domain errors (@lalitkapoor) - [#802](https://github.com/request/request/pull/802) Added the Apache license to the package.json. (@keskival) - [#793](https://github.com/request/request/pull/793) Adds content-length calculation when submitting forms using form-data li... (@Juul) - [#785](https://github.com/request/request/pull/785) Provide ability to override content-type when `json` option used (@vvo) - [#781](https://github.com/request/request/pull/781) simpler isReadStream function (@joaojeronimo) ### v2.32.0 (2014/01/16) - [#767](https://github.com/request/request/pull/767) Use tough-cookie CookieJar sync API (@stash) - [#764](https://github.com/request/request/pull/764) Case-insensitive authentication scheme (@bobyrizov) - [#763](https://github.com/request/request/pull/763) Upgrade tough-cookie to 0.10.0 (@stash) - [#744](https://github.com/request/request/pull/744) Use Cookie.parse (@lalitkapoor) - [#757](https://github.com/request/request/pull/757) require aws-sign2 (@mafintosh) ### v2.31.0 (2014/01/08) - [#645](https://github.com/request/request/pull/645) update twitter api url to v1.1 (@mick) - [#746](https://github.com/request/request/pull/746) README: Markdown code highlight (@weakish) - [#745](https://github.com/request/request/pull/745) updating setCookie example to make it clear that the callback is required (@emkay) - [#742](https://github.com/request/request/pull/742) Add note about JSON output body type (@iansltx) - [#741](https://github.com/request/request/pull/741) README example is using old cookie jar api (@emkay) - [#736](https://github.com/request/request/pull/736) Fix callback arguments documentation (@mmalecki) - [#732](https://github.com/request/request/pull/732) JSHINT: Creating global 'for' variable. Should be 'for (var ...'. (@Fritz-Lium) - [#730](https://github.com/request/request/pull/730) better HTTP DIGEST support (@dai-shi) - [#728](https://github.com/request/request/pull/728) Fix TypeError when calling request.cookie (@scarletmeow) - [#727](https://github.com/request/request/pull/727) fix requester bug (@jchris) - [#724](https://github.com/request/request/pull/724) README.md: add custom HTTP Headers example. (@tcort) - [#719](https://github.com/request/request/pull/719) Made a comment gender neutral. (@unsetbit) - [#715](https://github.com/request/request/pull/715) Request.multipart no longer crashes when header 'Content-type' present (@pastaclub) - [#710](https://github.com/request/request/pull/710) Fixing listing in callback part of docs. (@lukasz-zak) - [#696](https://github.com/request/request/pull/696) Edited README.md for formatting and clarity of phrasing (@Zearin) - [#694](https://github.com/request/request/pull/694) Typo in README (@VRMink) - [#690](https://github.com/request/request/pull/690) Handle blank password in basic auth. (@diversario) - [#682](https://github.com/request/request/pull/682) Optional dependencies (@Turbo87) - [#683](https://github.com/request/request/pull/683) Travis CI support (@Turbo87) - [#674](https://github.com/request/request/pull/674) change cookie module,to tough-cookie.please check it . (@sxyizhiren) - [#666](https://github.com/request/request/pull/666) make `ciphers` and `secureProtocol` to work in https request (@richarddong) - [#656](https://github.com/request/request/pull/656) Test case for #304. (@diversario) - [#662](https://github.com/request/request/pull/662) option.tunnel to explicitly disable tunneling (@seanmonstar) - [#659](https://github.com/request/request/pull/659) fix failure when running with NODE_DEBUG=request, and a test for that (@jrgm) - [#630](https://github.com/request/request/pull/630) Send random cnonce for HTTP Digest requests (@wprl) - [#619](https://github.com/request/request/pull/619) decouple things a bit (@joaojeronimo) - [#613](https://github.com/request/request/pull/613) Fixes #583, moved initialization of self.uri.pathname (@lexander) - [#605](https://github.com/request/request/pull/605) Only include ":" + pass in Basic Auth if it's defined (fixes #602) (@bendrucker) - [#596](https://github.com/request/request/pull/596) Global agent is being used when pool is specified (@Cauldrath) - [#594](https://github.com/request/request/pull/594) Emit complete event when there is no callback (@RomainLK) - [#601](https://github.com/request/request/pull/601) Fixed a small typo (@michalstanko) - [#589](https://github.com/request/request/pull/589) Prevent setting headers after they are sent (@geek) - [#587](https://github.com/request/request/pull/587) Global cookie jar disabled by default (@threepointone) - [#544](https://github.com/request/request/pull/544) Update http-signature version. (@davidlehn) - [#581](https://github.com/request/request/pull/581) Fix spelling of "ignoring." (@bigeasy) - [#568](https://github.com/request/request/pull/568) use agentOptions to create agent when specified in request (@SamPlacette) - [#564](https://github.com/request/request/pull/564) Fix redirections (@criloz) - [#541](https://github.com/request/request/pull/541) The exported request function doesn't have an auth method (@tschaub) - [#542](https://github.com/request/request/pull/542) Expose Request class (@regality) - [#536](https://github.com/request/request/pull/536) Allow explicitly empty user field for basic authentication. (@mikeando) - [#532](https://github.com/request/request/pull/532) fix typo (@fredericosilva) - [#497](https://github.com/request/request/pull/497) Added redirect event (@Cauldrath) - [#503](https://github.com/request/request/pull/503) Fix basic auth for passwords that contain colons (@tonistiigi) - [#521](https://github.com/request/request/pull/521) Improving test-localAddress.js (@noway) - [#529](https://github.com/request/request/pull/529) dependencies versions bump (@jodaka) - [#523](https://github.com/request/request/pull/523) Updating dependencies (@noway) - [#520](https://github.com/request/request/pull/520) Fixing test-tunnel.js (@noway) - [#519](https://github.com/request/request/pull/519) Update internal path state on post-creation QS changes (@jblebrun) - [#510](https://github.com/request/request/pull/510) Add HTTP Signature support. (@davidlehn) - [#502](https://github.com/request/request/pull/502) Fix POST (and probably other) requests that are retried after 401 Unauthorized (@nylen) - [#508](https://github.com/request/request/pull/508) Honor the .strictSSL option when using proxies (tunnel-agent) (@jhs) - [#512](https://github.com/request/request/pull/512) Make password optional to support the format: http://username@hostname/ (@pajato1) - [#513](https://github.com/request/request/pull/513) add 'localAddress' support (@yyfrankyy) - [#498](https://github.com/request/request/pull/498) Moving response emit above setHeaders on destination streams (@kenperkins) - [#490](https://github.com/request/request/pull/490) Empty response body (3-rd argument) must be passed to callback as an empty string (@Olegas) - [#479](https://github.com/request/request/pull/479) Changing so if Accept header is explicitly set, sending json does not ov... (@RoryH) - [#475](https://github.com/request/request/pull/475) Use `unescape` from `querystring` (@shimaore) - [#473](https://github.com/request/request/pull/473) V0.10 compat (@isaacs) - [#471](https://github.com/request/request/pull/471) Using querystring library from visionmedia (@kbackowski) - [#461](https://github.com/request/request/pull/461) Strip the UTF8 BOM from a UTF encoded response (@kppullin) - [#460](https://github.com/request/request/pull/460) hawk 0.10.0 (@hueniverse) - [#462](https://github.com/request/request/pull/462) if query params are empty, then request path shouldn't end with a '?' (merges cleanly now) (@jaipandya) - [#456](https://github.com/request/request/pull/456) hawk 0.9.0 (@hueniverse) - [#429](https://github.com/request/request/pull/429) Copy options before adding callback. (@nrn, @nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) - [#454](https://github.com/request/request/pull/454) Destroy the response if present when destroying the request (clean merge) (@mafintosh) - [#310](https://github.com/request/request/pull/310) Twitter Oauth Stuff Out of Date; Now Updated (@joemccann, @isaacs, @mscdex) - [#413](https://github.com/request/request/pull/413) rename googledoodle.png to .jpg (@nfriedly, @youurayy, @jplock, @kapetan, @landeiro, @othiym23, @mmalecki) - [#448](https://github.com/request/request/pull/448) Convenience method for PATCH (@mloar) - [#444](https://github.com/request/request/pull/444) protect against double callbacks on error path (@spollack) - [#433](https://github.com/request/request/pull/433) Added support for HTTPS cert & key (@mmalecki) - [#430](https://github.com/request/request/pull/430) Respect specified {Host,host} headers, not just {host} (@andrewschaaf) - [#415](https://github.com/request/request/pull/415) Fixed a typo. (@jerem) - [#338](https://github.com/request/request/pull/338) Add more auth options, including digest support (@nylen) - [#403](https://github.com/request/request/pull/403) Optimize environment lookup to happen once only (@mmalecki) - [#398](https://github.com/request/request/pull/398) Add more reporting to tests (@mmalecki) - [#388](https://github.com/request/request/pull/388) Ensure "safe" toJSON doesn't break EventEmitters (@othiym23) - [#381](https://github.com/request/request/pull/381) Resolving "Invalid signature. Expected signature base string: " (@landeiro) - [#380](https://github.com/request/request/pull/380) Fixes missing host header on retried request when using forever agent (@mac-) - [#376](https://github.com/request/request/pull/376) Headers lost on redirect (@kapetan) - [#375](https://github.com/request/request/pull/375) Fix for missing oauth_timestamp parameter (@jplock) - [#374](https://github.com/request/request/pull/374) Correct Host header for proxy tunnel CONNECT (@youurayy) - [#370](https://github.com/request/request/pull/370) Twitter reverse auth uses x_auth_mode not x_auth_type (@drudge) - [#369](https://github.com/request/request/pull/369) Don't remove x_auth_mode for Twitter reverse auth (@drudge) - [#344](https://github.com/request/request/pull/344) Make AWS auth signing find headers correctly (@nlf) - [#363](https://github.com/request/request/pull/363) rfc3986 on base_uri, now passes tests (@jeffmarshall) - [#362](https://github.com/request/request/pull/362) Running `rfc3986` on `base_uri` in `oauth.hmacsign` instead of just `encodeURIComponent` (@jeffmarshall) - [#361](https://github.com/request/request/pull/361) Don't create a Content-Length header if we already have it set (@danjenkins) - [#360](https://github.com/request/request/pull/360) Delete self._form along with everything else on redirect (@jgautier) - [#355](https://github.com/request/request/pull/355) stop sending erroneous headers on redirected requests (@azylman) - [#332](https://github.com/request/request/pull/332) Fix #296 - Only set Content-Type if body exists (@Marsup) - [#343](https://github.com/request/request/pull/343) Allow AWS to work in more situations, added a note in the README on its usage (@nlf) - [#320](https://github.com/request/request/pull/320) request.defaults() doesn't need to wrap jar() (@StuartHarris) - [#322](https://github.com/request/request/pull/322) Fix + test for piped into request bumped into redirect. #321 (@alexindigo) - [#326](https://github.com/request/request/pull/326) Do not try to remove listener from an undefined connection (@CartoDB) - [#318](https://github.com/request/request/pull/318) Pass servername to tunneling secure socket creation (@isaacs) - [#317](https://github.com/request/request/pull/317) Workaround for #313 (@isaacs) - [#293](https://github.com/request/request/pull/293) Allow parser errors to bubble up to request (@mscdex) - [#290](https://github.com/request/request/pull/290) A test for #289 (@isaacs) - [#280](https://github.com/request/request/pull/280) Like in node.js print options if NODE_DEBUG contains the word request (@Filirom1) - [#207](https://github.com/request/request/pull/207) Fix #206 Change HTTP/HTTPS agent when redirecting between protocols (@isaacs) - [#214](https://github.com/request/request/pull/214) documenting additional behavior of json option (@jphaas, @vpulim) - [#272](https://github.com/request/request/pull/272) Boundary begins with CRLF? (@elspoono, @timshadel, @naholyr, @nanodocumet, @TehShrike) - [#284](https://github.com/request/request/pull/284) Remove stray `console.log()` call in multipart generator. (@bcherry) - [#241](https://github.com/request/request/pull/241) Composability updates suggested by issue #239 (@polotek) - [#282](https://github.com/request/request/pull/282) OAuth Authorization header contains non-"oauth_" parameters (@jplock) - [#279](https://github.com/request/request/pull/279) fix tests with boundary by injecting boundry from header (@benatkin) - [#273](https://github.com/request/request/pull/273) Pipe back pressure issue (@mafintosh) - [#268](https://github.com/request/request/pull/268) I'm not OCD seriously (@TehShrike) - [#263](https://github.com/request/request/pull/263) Bug in OAuth key generation for sha1 (@nanodocumet) - [#265](https://github.com/request/request/pull/265) uncaughtException when redirected to invalid URI (@naholyr) - [#262](https://github.com/request/request/pull/262) JSON test should check for equality (@timshadel) - [#261](https://github.com/request/request/pull/261) Setting 'pool' to 'false' does NOT disable Agent pooling (@timshadel) - [#249](https://github.com/request/request/pull/249) Fix for the fix of your (closed) issue #89 where self.headers[content-length] is set to 0 for all methods (@sethbridges, @polotek, @zephrax, @jeromegn) - [#255](https://github.com/request/request/pull/255) multipart allow body === '' ( the empty string ) (@Filirom1) - [#260](https://github.com/request/request/pull/260) fixed just another leak of 'i' (@sreuter) - [#246](https://github.com/request/request/pull/246) Fixing the set-cookie header (@jeromegn) - [#243](https://github.com/request/request/pull/243) Dynamic boundary (@zephrax) - [#240](https://github.com/request/request/pull/240) don't error when null is passed for options (@polotek) - [#211](https://github.com/request/request/pull/211) Replace all occurrences of special chars in RFC3986 (@chriso, @vpulim) - [#224](https://github.com/request/request/pull/224) Multipart content-type change (@janjongboom) - [#217](https://github.com/request/request/pull/217) need to use Authorization (titlecase) header with Tumblr OAuth (@visnup) - [#203](https://github.com/request/request/pull/203) Fix cookie and redirect bugs and add auth support for HTTPS tunnel (@vpulim) - [#199](https://github.com/request/request/pull/199) Tunnel (@isaacs) - [#198](https://github.com/request/request/pull/198) Bugfix on forever usage of util.inherits (@isaacs) - [#197](https://github.com/request/request/pull/197) Make ForeverAgent work with HTTPS (@isaacs) - [#193](https://github.com/request/request/pull/193) Fixes GH-119 (@goatslacker) - [#188](https://github.com/request/request/pull/188) Add abort support to the returned request (@itay) - [#176](https://github.com/request/request/pull/176) Querystring option (@csainty) - [#182](https://github.com/request/request/pull/182) Fix request.defaults to support (uri, options, callback) api (@twilson63) - [#180](https://github.com/request/request/pull/180) Modified the post, put, head and del shortcuts to support uri optional param (@twilson63) - [#179](https://github.com/request/request/pull/179) fix to add opts in .pipe(stream, opts) (@substack) - [#177](https://github.com/request/request/pull/177) Issue #173 Support uri as first and optional config as second argument (@twilson63) - [#170](https://github.com/request/request/pull/170) can't create a cookie in a wrapped request (defaults) (@fabianonunes) - [#168](https://github.com/request/request/pull/168) Picking off an EasyFix by adding some missing mimetypes. (@serby) - [#161](https://github.com/request/request/pull/161) Fix cookie jar/headers.cookie collision (#125) (@papandreou) - [#162](https://github.com/request/request/pull/162) Fix issue #159 (@dpetukhov) - [#90](https://github.com/request/request/pull/90) add option followAllRedirects to follow post/put redirects (@jroes) - [#148](https://github.com/request/request/pull/148) Retry Agent (@thejh) - [#146](https://github.com/request/request/pull/146) Multipart should respect content-type if previously set (@apeace) - [#144](https://github.com/request/request/pull/144) added "form" option to readme (@petejkim) - [#133](https://github.com/request/request/pull/133) Fixed cookies parsing (@afanasy) - [#135](https://github.com/request/request/pull/135) host vs hostname (@iangreenleaf) - [#132](https://github.com/request/request/pull/132) return the body as a Buffer when encoding is set to null (@jahewson) - [#112](https://github.com/request/request/pull/112) Support using a custom http-like module (@jhs) - [#104](https://github.com/request/request/pull/104) Cookie handling contains bugs (@janjongboom) - [#121](https://github.com/request/request/pull/121) Another patch for cookie handling regression (@jhurliman) - [#117](https://github.com/request/request/pull/117) Remove the global `i` (@3rd-Eden) - [#110](https://github.com/request/request/pull/110) Update to Iris Couch URL (@jhs) - [#86](https://github.com/request/request/pull/86) Can't post binary to multipart requests (@kkaefer) - [#105](https://github.com/request/request/pull/105) added test for proxy option. (@dominictarr) - [#102](https://github.com/request/request/pull/102) Implemented cookies - closes issue 82: https://github.com/mikeal/request/issues/82 (@alessioalex) - [#97](https://github.com/request/request/pull/97) Typo in previous pull causes TypeError in non-0.5.11 versions (@isaacs) - [#96](https://github.com/request/request/pull/96) Authless parsed url host support (@isaacs) - [#81](https://github.com/request/request/pull/81) Enhance redirect handling (@danmactough) - [#78](https://github.com/request/request/pull/78) Don't try to do strictSSL for non-ssl connections (@isaacs) - [#76](https://github.com/request/request/pull/76) Bug when a request fails and a timeout is set (@Marsup) - [#70](https://github.com/request/request/pull/70) add test script to package.json (@isaacs, @aheckmann) - [#73](https://github.com/request/request/pull/73) Fix #71 Respect the strictSSL flag (@isaacs) - [#69](https://github.com/request/request/pull/69) Flatten chunked requests properly (@isaacs) - [#67](https://github.com/request/request/pull/67) fixed global variable leaks (@aheckmann) - [#66](https://github.com/request/request/pull/66) Do not overwrite established content-type headers for read stream deliver (@voodootikigod) - [#53](https://github.com/request/request/pull/53) Parse json: Issue #51 (@benatkin) - [#45](https://github.com/request/request/pull/45) Added timeout option (@mbrevoort) - [#35](https://github.com/request/request/pull/35) The "end" event isn't emitted for some responses (@voxpelli) - [#31](https://github.com/request/request/pull/31) Error on piping a request to a destination (@tobowers)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/CHANGELOG.md
CHANGELOG.md
[RFC6265](https://tools.ietf.org/html/rfc6265) Cookies and CookieJar for Node.js [![npm package](https://nodei.co/npm/tough-cookie.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/tough-cookie/) [![Build Status](https://travis-ci.org/salesforce/tough-cookie.png?branch=master)](https://travis-ci.org/salesforce/tough-cookie) # Synopsis ``` javascript var tough = require('tough-cookie'); var Cookie = tough.Cookie; var cookie = Cookie.parse(header); cookie.value = 'somethingdifferent'; header = cookie.toString(); var cookiejar = new tough.CookieJar(); cookiejar.setCookie(cookie, 'http://currentdomain.example.com/path', cb); // ... cookiejar.getCookies('http://example.com/otherpath',function(err,cookies) { res.headers['cookie'] = cookies.join('; '); }); ``` # Installation It's _so_ easy! `npm install tough-cookie` Why the name? NPM modules `cookie`, `cookies` and `cookiejar` were already taken. ## Version Support Support for versions of node.js will follow that of the [request](https://www.npmjs.com/package/request) module. # API ## tough Functions on the module you get from `require('tough-cookie')`. All can be used as pure functions and don't need to be "bound". **Note**: prior to 1.0.x, several of these functions took a `strict` parameter. This has since been removed from the API as it was no longer necessary. ### `parseDate(string)` Parse a cookie date string into a `Date`. Parses according to RFC6265 Section 5.1.1, not `Date.parse()`. ### `formatDate(date)` Format a Date into a RFC1123 string (the RFC6265-recommended format). ### `canonicalDomain(str)` Transforms a domain-name into a canonical domain-name. The canonical domain-name is a trimmed, lowercased, stripped-of-leading-dot and optionally punycode-encoded domain-name (Section 5.1.2 of RFC6265). For the most part, this function is idempotent (can be run again on its output without ill effects). ### `domainMatch(str,domStr[,canonicalize=true])` Answers "does this real domain match the domain in a cookie?". The `str` is the "current" domain-name and the `domStr` is the "cookie" domain-name. Matches according to RFC6265 Section 5.1.3, but it helps to think of it as a "suffix match". The `canonicalize` parameter will run the other two parameters through `canonicalDomain` or not. ### `defaultPath(path)` Given a current request/response path, gives the Path apropriate for storing in a cookie. This is basically the "directory" of a "file" in the path, but is specified by Section 5.1.4 of the RFC. The `path` parameter MUST be _only_ the pathname part of a URI (i.e. excludes the hostname, query, fragment, etc.). This is the `.pathname` property of node's `uri.parse()` output. ### `pathMatch(reqPath,cookiePath)` Answers "does the request-path path-match a given cookie-path?" as per RFC6265 Section 5.1.4. Returns a boolean. This is essentially a prefix-match where `cookiePath` is a prefix of `reqPath`. ### `parse(cookieString[, options])` alias for `Cookie.parse(cookieString[, options])` ### `fromJSON(string)` alias for `Cookie.fromJSON(string)` ### `getPublicSuffix(hostname)` Returns the public suffix of this hostname. The public suffix is the shortest domain-name upon which a cookie can be set. Returns `null` if the hostname cannot have cookies set for it. For example: `www.example.com` and `www.subdomain.example.com` both have public suffix `example.com`. For further information, see http://publicsuffix.org/. This module derives its list from that site. This call is currently a wrapper around [`psl`](https://www.npmjs.com/package/psl)'s [get() method](https://www.npmjs.com/package/psl#pslgetdomain). ### `cookieCompare(a,b)` For use with `.sort()`, sorts a list of cookies into the recommended order given in the RFC (Section 5.4 step 2). The sort algorithm is, in order of precedence: * Longest `.path` * oldest `.creation` (which has a 1ms precision, same as `Date`) * lowest `.creationIndex` (to get beyond the 1ms precision) ``` javascript var cookies = [ /* unsorted array of Cookie objects */ ]; cookies = cookies.sort(cookieCompare); ``` **Note**: Since JavaScript's `Date` is limited to a 1ms precision, cookies within the same milisecond are entirely possible. This is especially true when using the `now` option to `.setCookie()`. The `.creationIndex` property is a per-process global counter, assigned during construction with `new Cookie()`. This preserves the spirit of the RFC sorting: older cookies go first. This works great for `MemoryCookieStore`, since `Set-Cookie` headers are parsed in order, but may not be so great for distributed systems. Sophisticated `Store`s may wish to set this to some other _logical clock_ such that if cookies A and B are created in the same millisecond, but cookie A is created before cookie B, then `A.creationIndex < B.creationIndex`. If you want to alter the global counter, which you probably _shouldn't_ do, it's stored in `Cookie.cookiesCreated`. ### `permuteDomain(domain)` Generates a list of all possible domains that `domainMatch()` the parameter. May be handy for implementing cookie stores. ### `permutePath(path)` Generates a list of all possible paths that `pathMatch()` the parameter. May be handy for implementing cookie stores. ## Cookie Exported via `tough.Cookie`. ### `Cookie.parse(cookieString[, options])` Parses a single Cookie or Set-Cookie HTTP header into a `Cookie` object. Returns `undefined` if the string can't be parsed. The options parameter is not required and currently has only one property: * _loose_ - boolean - if `true` enable parsing of key-less cookies like `=abc` and `=`, which are not RFC-compliant. If options is not an object, it is ignored, which means you can use `Array#map` with it. Here's how to process the Set-Cookie header(s) on a node HTTP/HTTPS response: ``` javascript if (res.headers['set-cookie'] instanceof Array) cookies = res.headers['set-cookie'].map(Cookie.parse); else cookies = [Cookie.parse(res.headers['set-cookie'])]; ``` _Note:_ in version 2.3.3, tough-cookie limited the number of spaces before the `=` to 256 characters. This limitation has since been removed. See [Issue 92](https://github.com/salesforce/tough-cookie/issues/92) ### Properties Cookie object properties: * _key_ - string - the name or key of the cookie (default "") * _value_ - string - the value of the cookie (default "") * _expires_ - `Date` - if set, the `Expires=` attribute of the cookie (defaults to the string `"Infinity"`). See `setExpires()` * _maxAge_ - seconds - if set, the `Max-Age=` attribute _in seconds_ of the cookie. May also be set to strings `"Infinity"` and `"-Infinity"` for non-expiry and immediate-expiry, respectively. See `setMaxAge()` * _domain_ - string - the `Domain=` attribute of the cookie * _path_ - string - the `Path=` of the cookie * _secure_ - boolean - the `Secure` cookie flag * _httpOnly_ - boolean - the `HttpOnly` cookie flag * _extensions_ - `Array` - any unrecognized cookie attributes as strings (even if equal-signs inside) * _creation_ - `Date` - when this cookie was constructed * _creationIndex_ - number - set at construction, used to provide greater sort precision (please see `cookieCompare(a,b)` for a full explanation) After a cookie has been passed through `CookieJar.setCookie()` it will have the following additional attributes: * _hostOnly_ - boolean - is this a host-only cookie (i.e. no Domain field was set, but was instead implied) * _pathIsDefault_ - boolean - if true, there was no Path field on the cookie and `defaultPath()` was used to derive one. * _creation_ - `Date` - **modified** from construction to when the cookie was added to the jar * _lastAccessed_ - `Date` - last time the cookie got accessed. Will affect cookie cleaning once implemented. Using `cookiejar.getCookies(...)` will update this attribute. ### `Cookie([{properties}])` Receives an options object that can contain any of the above Cookie properties, uses the default for unspecified properties. ### `.toString()` encode to a Set-Cookie header value. The Expires cookie field is set using `formatDate()`, but is omitted entirely if `.expires` is `Infinity`. ### `.cookieString()` encode to a Cookie header value (i.e. the `.key` and `.value` properties joined with '='). ### `.setExpires(String)` sets the expiry based on a date-string passed through `parseDate()`. If parseDate returns `null` (i.e. can't parse this date string), `.expires` is set to `"Infinity"` (a string) is set. ### `.setMaxAge(number)` sets the maxAge in seconds. Coerces `-Infinity` to `"-Infinity"` and `Infinity` to `"Infinity"` so it JSON serializes correctly. ### `.expiryTime([now=Date.now()])` ### `.expiryDate([now=Date.now()])` expiryTime() Computes the absolute unix-epoch milliseconds that this cookie expires. expiryDate() works similarly, except it returns a `Date` object. Note that in both cases the `now` parameter should be milliseconds. Max-Age takes precedence over Expires (as per the RFC). The `.creation` attribute -- or, by default, the `now` parameter -- is used to offset the `.maxAge` attribute. If Expires (`.expires`) is set, that's returned. Otherwise, `expiryTime()` returns `Infinity` and `expiryDate()` returns a `Date` object for "Tue, 19 Jan 2038 03:14:07 GMT" (latest date that can be expressed by a 32-bit `time_t`; the common limit for most user-agents). ### `.TTL([now=Date.now()])` compute the TTL relative to `now` (milliseconds). The same precedence rules as for `expiryTime`/`expiryDate` apply. The "number" `Infinity` is returned for cookies without an explicit expiry and `0` is returned if the cookie is expired. Otherwise a time-to-live in milliseconds is returned. ### `.canonicalizedDomain()` ### `.cdomain()` return the canonicalized `.domain` field. This is lower-cased and punycode (RFC3490) encoded if the domain has any non-ASCII characters. ### `.toJSON()` For convenience in using `JSON.serialize(cookie)`. Returns a plain-old `Object` that can be JSON-serialized. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are exported in ISO format (`.toISOString()`). **NOTE**: Custom `Cookie` properties will be discarded. In tough-cookie 1.x, since there was no `.toJSON` method explicitly defined, all enumerable properties were captured. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. ### `Cookie.fromJSON(strOrObj)` Does the reverse of `cookie.toJSON()`. If passed a string, will `JSON.parse()` that first. Any `Date` properties (i.e., `.expires`, `.creation`, and `.lastAccessed`) are parsed via `Date.parse()`, not the tough-cookie `parseDate`, since it's JavaScript/JSON-y timestamps being handled at this layer. Returns `null` upon JSON parsing error. ### `.clone()` Does a deep clone of this cookie, exactly implemented as `Cookie.fromJSON(cookie.toJSON())`. ### `.validate()` Status: *IN PROGRESS*. Works for a few things, but is by no means comprehensive. validates cookie attributes for semantic correctness. Useful for "lint" checking any Set-Cookie headers you generate. For now, it returns a boolean, but eventually could return a reason string -- you can future-proof with this construct: ``` javascript if (cookie.validate() === true) { // it's tasty } else { // yuck! } ``` ## CookieJar Exported via `tough.CookieJar`. ### `CookieJar([store],[options])` Simply use `new CookieJar()`. If you'd like to use a custom store, pass that to the constructor otherwise a `MemoryCookieStore` will be created and used. The `options` object can be omitted and can have the following properties: * _rejectPublicSuffixes_ - boolean - default `true` - reject cookies with domains like "com" and "co.uk" * _looseMode_ - boolean - default `false` - accept malformed cookies like `bar` and `=bar`, which have an implied empty name. This is not in the standard, but is used sometimes on the web and is accepted by (most) browsers. Since eventually this module would like to support database/remote/etc. CookieJars, continuation passing style is used for CookieJar methods. ### `.setCookie(cookieOrString, currentUrl, [{options},] cb(err,cookie))` Attempt to set the cookie in the cookie jar. If the operation fails, an error will be given to the callback `cb`, otherwise the cookie is passed through. The cookie will have updated `.creation`, `.lastAccessed` and `.hostOnly` properties. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _ignoreError_ - boolean - default `false` - silently ignore things like parse errors and invalid domains. `Store` errors aren't ignored by this option. As per the RFC, the `.hostOnly` property is set if there was no "Domain=" parameter in the cookie string (or `.domain` was null on the Cookie object). The `.domain` property is set to the fully-qualified hostname of `currentUrl` in this case. Matching this cookie requires an exact hostname match (not a `domainMatch` as per usual). ### `.setCookieSync(cookieOrString, currentUrl, [{options}])` Synchronous version of `setCookie`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookies(currentUrl, [{options},] cb(err,cookies))` Retrieve the list of cookies that can be sent in a Cookie header for the current url. If an error is encountered, that's passed as `err` to the callback, otherwise an `Array` of `Cookie` objects is passed. The array is sorted with `cookieCompare()` unless the `{sort:false}` option is given. The `options` object can be omitted and can have the following properties: * _http_ - boolean - default `true` - indicates if this is an HTTP or non-HTTP API. Affects HttpOnly cookies. * _secure_ - boolean - autodetect from url - indicates if this is a "Secure" API. If the currentUrl starts with `https:` or `wss:` then this is defaulted to `true`, otherwise `false`. * _now_ - Date - default `new Date()` - what to use for the creation/access time of cookies * _expire_ - boolean - default `true` - perform expiry-time checking of cookies and asynchronously remove expired cookies from the store. Using `false` will return expired cookies and **not** remove them from the store (which is useful for replaying Set-Cookie headers, potentially). * _allPaths_ - boolean - default `false` - if `true`, do not scope cookies by path. The default uses RFC-compliant path scoping. **Note**: may not be supported by the underlying store (the default `MemoryCookieStore` supports it). The `.lastAccessed` property of the returned cookies will have been updated. ### `.getCookiesSync(currentUrl, [{options}])` Synchronous version of `getCookies`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getCookieString(...)` Accepts the same options as `.getCookies()` but passes a string suitable for a Cookie header rather than an array to the callback. Simply maps the `Cookie` array via `.cookieString()`. ### `.getCookieStringSync(...)` Synchronous version of `getCookieString`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.getSetCookieStrings(...)` Returns an array of strings suitable for **Set-Cookie** headers. Accepts the same options as `.getCookies()`. Simply maps the cookie array via `.toString()`. ### `.getSetCookieStringsSync(...)` Synchronous version of `getSetCookieStrings`; only works with synchronous stores (e.g. the default `MemoryCookieStore`). ### `.serialize(cb(err,serializedObject))` Serialize the Jar if the underlying store supports `.getAllCookies`. **NOTE**: Custom `Cookie` properties will be discarded. If you want a property to be serialized, add the property name to the `Cookie.serializableProperties` Array. See [Serialization Format]. ### `.serializeSync()` Sync version of .serialize ### `.toJSON()` Alias of .serializeSync() for the convenience of `JSON.stringify(cookiejar)`. ### `CookieJar.deserialize(serialized, [store], cb(err,object))` A new Jar is created and the serialized Cookies are added to the underlying store. Each `Cookie` is added via `store.putCookie` in the order in which they appear in the serialization. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. As a convenience, if `serialized` is a string, it is passed through `JSON.parse` first. If that throws an error, this is passed to the callback. ### `CookieJar.deserializeSync(serialized, [store])` Sync version of `.deserialize`. _Note_ that the `store` must be synchronous for this to work. ### `CookieJar.fromJSON(string)` Alias of `.deserializeSync` to provide consistency with `Cookie.fromJSON()`. ### `.clone([store,]cb(err,newJar))` Produces a deep clone of this jar. Modifications to the original won't affect the clone, and vice versa. The `store` argument is optional, but should be an instance of `Store`. By default, a new instance of `MemoryCookieStore` is created. Transferring between store types is supported so long as the source implements `.getAllCookies()` and the destination implements `.putCookie()`. ### `.cloneSync([store])` Synchronous version of `.clone`, returning a new `CookieJar` instance. The `store` argument is optional, but must be a _synchronous_ `Store` instance if specified. If not passed, a new instance of `MemoryCookieStore` is used. The _source_ and _destination_ must both be synchronous `Store`s. If one or both stores are asynchronous, use `.clone` instead. Recall that `MemoryCookieStore` supports both synchronous and asynchronous API calls. ### `.removeAllCookies(cb(err))` Removes all cookies from the jar. This is a new backwards-compatible feature of `tough-cookie` version 2.5, so not all Stores will implement it efficiently. For Stores that do not implement `removeAllCookies`, the fallback is to call `removeCookie` after `getAllCookies`. If `getAllCookies` fails or isn't implemented in the Store, that error is returned. If one or more of the `removeCookie` calls fail, only the first error is returned. ### `.removeAllCookiesSync()` Sync version of `.removeAllCookies()` ## Store Base class for CookieJar stores. Available as `tough.Store`. ## Store API The storage model for each `CookieJar` instance can be replaced with a custom implementation. The default is `MemoryCookieStore` which can be found in the `lib/memstore.js` file. The API uses continuation-passing-style to allow for asynchronous stores. Stores should inherit from the base `Store` class, which is available as `require('tough-cookie').Store`. Stores are asynchronous by default, but if `store.synchronous` is set to `true`, then the `*Sync` methods on the of the containing `CookieJar` can be used (however, the continuation-passing style All `domain` parameters will have been normalized before calling. The Cookie store must have all of the following methods. ### `store.findCookie(domain, path, key, cb(err,cookie))` Retrieve a cookie with the given domain, path and key (a.k.a. name). The RFC maintains that exactly one of these cookies should exist in a store. If the store is using versioning, this means that the latest/newest such cookie should be returned. Callback takes an error and the resulting `Cookie` object. If no cookie is found then `null` MUST be passed instead (i.e. not an error). ### `store.findCookies(domain, path, cb(err,cookies))` Locates cookies matching the given domain and path. This is most often called in the context of `cookiejar.getCookies()` above. If no cookies are found, the callback MUST be passed an empty array. The resulting list will be checked for applicability to the current request according to the RFC (domain-match, path-match, http-only-flag, secure-flag, expiry, etc.), so it's OK to use an optimistic search algorithm when implementing this method. However, the search algorithm used SHOULD try to find cookies that `domainMatch()` the domain and `pathMatch()` the path in order to limit the amount of checking that needs to be done. As of version 0.9.12, the `allPaths` option to `cookiejar.getCookies()` above will cause the path here to be `null`. If the path is `null`, path-matching MUST NOT be performed (i.e. domain-matching only). ### `store.putCookie(cookie, cb(err))` Adds a new cookie to the store. The implementation SHOULD replace any existing cookie with the same `.domain`, `.path`, and `.key` properties -- depending on the nature of the implementation, it's possible that between the call to `fetchCookie` and `putCookie` that a duplicate `putCookie` can occur. The `cookie` object MUST NOT be modified; the caller will have already updated the `.creation` and `.lastAccessed` properties. Pass an error if the cookie cannot be stored. ### `store.updateCookie(oldCookie, newCookie, cb(err))` Update an existing cookie. The implementation MUST update the `.value` for a cookie with the same `domain`, `.path` and `.key`. The implementation SHOULD check that the old value in the store is equivalent to `oldCookie` - how the conflict is resolved is up to the store. The `.lastAccessed` property will always be different between the two objects (to the precision possible via JavaScript's clock). Both `.creation` and `.creationIndex` are guaranteed to be the same. Stores MAY ignore or defer the `.lastAccessed` change at the cost of affecting how cookies are selected for automatic deletion (e.g., least-recently-used, which is up to the store to implement). Stores may wish to optimize changing the `.value` of the cookie in the store versus storing a new cookie. If the implementation doesn't define this method a stub that calls `putCookie(newCookie,cb)` will be added to the store object. The `newCookie` and `oldCookie` objects MUST NOT be modified. Pass an error if the newCookie cannot be stored. ### `store.removeCookie(domain, path, key, cb(err))` Remove a cookie from the store (see notes on `findCookie` about the uniqueness constraint). The implementation MUST NOT pass an error if the cookie doesn't exist; only pass an error due to the failure to remove an existing cookie. ### `store.removeCookies(domain, path, cb(err))` Removes matching cookies from the store. The `path` parameter is optional, and if missing means all paths in a domain should be removed. Pass an error ONLY if removing any existing cookies failed. ### `store.removeAllCookies(cb(err))` _Optional_. Removes all cookies from the store. Pass an error if one or more cookies can't be removed. **Note**: New method as of `tough-cookie` version 2.5, so not all Stores will implement this, plus some stores may choose not to implement this. ### `store.getAllCookies(cb(err, cookies))` _Optional_. Produces an `Array` of all cookies during `jar.serialize()`. The items in the array can be true `Cookie` objects or generic `Object`s with the [Serialization Format] data structure. Cookies SHOULD be returned in creation order to preserve sorting via `compareCookies()`. For reference, `MemoryCookieStore` will sort by `.creationIndex` since it uses true `Cookie` objects internally. If you don't return the cookies in creation order, they'll still be sorted by creation time, but this only has a precision of 1ms. See `compareCookies` for more detail. Pass an error if retrieval fails. **Note**: not all Stores can implement this due to technical limitations, so it is optional. ## MemoryCookieStore Inherits from `Store`. A just-in-memory CookieJar synchronous store implementation, used by default. Despite being a synchronous implementation, it's usable with both the synchronous and asynchronous forms of the `CookieJar` API. Supports serialization, `getAllCookies`, and `removeAllCookies`. ## Community Cookie Stores These are some Store implementations authored and maintained by the community. They aren't official and we don't vouch for them but you may be interested to have a look: - [`db-cookie-store`](https://github.com/JSBizon/db-cookie-store): SQL including SQLite-based databases - [`file-cookie-store`](https://github.com/JSBizon/file-cookie-store): Netscape cookie file format on disk - [`redis-cookie-store`](https://github.com/benkroeger/redis-cookie-store): Redis - [`tough-cookie-filestore`](https://github.com/mitsuru/tough-cookie-filestore): JSON on disk - [`tough-cookie-web-storage-store`](https://github.com/exponentjs/tough-cookie-web-storage-store): DOM localStorage and sessionStorage # Serialization Format **NOTE**: if you want to have custom `Cookie` properties serialized, add the property name to `Cookie.serializableProperties`. ```js { // The version of tough-cookie that serialized this jar. version: '[email protected]', // add the store type, to make humans happy: storeType: 'MemoryCookieStore', // CookieJar configuration: rejectPublicSuffixes: true, // ... future items go here // Gets filled from jar.store.getAllCookies(): cookies: [ { key: 'string', value: 'string', // ... /* other Cookie.serializableProperties go here */ } ] } ``` # Copyright and License BSD-3-Clause: ```text Copyright (c) 2015, Salesforce.com, Inc. 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. ```
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/node_modules/tough-cookie/README.md
README.md
'use strict'; var Store = require('tough-cookie/lib/store').Store; var permuteDomain = require('tough-cookie/lib/permuteDomain').permuteDomain; var pathMatch = require('tough-cookie/lib/pathMatch').pathMatch; var util = require('util'); function MemoryCookieStore() { Store.call(this); this.idx = {}; } util.inherits(MemoryCookieStore, Store); exports.MemoryCookieStore = MemoryCookieStore; MemoryCookieStore.prototype.idx = null; // Since it's just a struct in RAM, this Store is synchronous MemoryCookieStore.prototype.synchronous = true; // force a default depth: MemoryCookieStore.prototype.inspect = function() { return "{ idx: "+util.inspect(this.idx, false, 2)+' }'; }; // Use the new custom inspection symbol to add the custom inspect function if // available. if (util.inspect.custom) { MemoryCookieStore.prototype[util.inspect.custom] = MemoryCookieStore.prototype.inspect; } MemoryCookieStore.prototype.findCookie = function(domain, path, key, cb) { if (!this.idx[domain]) { return cb(null,undefined); } if (!this.idx[domain][path]) { return cb(null,undefined); } return cb(null,this.idx[domain][path][key]||null); }; MemoryCookieStore.prototype.findCookies = function(domain, path, cb) { var results = []; if (!domain) { return cb(null,[]); } var pathMatcher; if (!path) { // null means "all paths" pathMatcher = function matchAll(domainIndex) { for (var curPath in domainIndex) { var pathIndex = domainIndex[curPath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }; } else { pathMatcher = function matchRFC(domainIndex) { //NOTE: we should use path-match algorithm from S5.1.4 here //(see : https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/canonical_cookie.cc#L299) Object.keys(domainIndex).forEach(function (cookiePath) { if (pathMatch(path, cookiePath)) { var pathIndex = domainIndex[cookiePath]; for (var key in pathIndex) { results.push(pathIndex[key]); } } }); }; } var domains = permuteDomain(domain) || [domain]; var idx = this.idx; domains.forEach(function(curDomain) { var domainIndex = idx[curDomain]; if (!domainIndex) { return; } pathMatcher(domainIndex); }); cb(null,results); }; MemoryCookieStore.prototype.putCookie = function(cookie, cb) { if (!this.idx[cookie.domain]) { this.idx[cookie.domain] = {}; } if (!this.idx[cookie.domain][cookie.path]) { this.idx[cookie.domain][cookie.path] = {}; } this.idx[cookie.domain][cookie.path][cookie.key] = cookie; cb(null); }; MemoryCookieStore.prototype.updateCookie = function(oldCookie, newCookie, cb) { // updateCookie() may avoid updating cookies that are identical. For example, // lastAccessed may not be important to some stores and an equality // comparison could exclude that field. this.putCookie(newCookie,cb); }; MemoryCookieStore.prototype.removeCookie = function(domain, path, key, cb) { if (this.idx[domain] && this.idx[domain][path] && this.idx[domain][path][key]) { delete this.idx[domain][path][key]; } cb(null); }; MemoryCookieStore.prototype.removeCookies = function(domain, path, cb) { if (this.idx[domain]) { if (path) { delete this.idx[domain][path]; } else { delete this.idx[domain]; } } return cb(null); }; MemoryCookieStore.prototype.removeAllCookies = function(cb) { this.idx = {}; return cb(null); } MemoryCookieStore.prototype.getAllCookies = function(cb) { var cookies = []; var idx = this.idx; var domains = Object.keys(idx); domains.forEach(function(domain) { var paths = Object.keys(idx[domain]); paths.forEach(function(path) { var keys = Object.keys(idx[domain][path]); keys.forEach(function(key) { if (key !== null) { cookies.push(idx[domain][path][key]); } }); }); }); // Sort by creationIndex so deserializing retains the creation order. // When implementing your own store, this SHOULD retain the order too cookies.sort(function(a,b) { return (a.creationIndex||0) - (b.creationIndex||0); }); cb(null, cookies); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/node_modules/tough-cookie/lib/memstore.js
memstore.js
'use strict'; var net = require('net'); var urlParse = require('url').parse; var util = require('util'); var pubsuffix = require('tough-cookie/lib/pubsuffix-psl'); var Store = require('tough-cookie/lib/store').Store; var MemoryCookieStore = require('tough-cookie/lib/memstore').MemoryCookieStore; var pathMatch = require('tough-cookie/lib/pathMatch').pathMatch; var VERSION = require('tough-cookie/lib/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: // https://github.com/ChromiumWebApps/chromium/blob/b3d3b4da8bb94c1b2e061600df106d590fda3620/net/cookies/parsed_cookie.cc#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('tough-cookie/lib/permuteDomain').permuteDomain; exports.permutePath = permutePath; exports.canonicalDomain = canonicalDomain;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/node_modules/tough-cookie/lib/cookie.js
cookie.js
'use strict' var url = require('url') var qs = require('qs') var caseless = require('caseless') var uuid = require('uuid/v4') var oauth = require('oauth-sign') var crypto = require('crypto') var Buffer = require('safe-buffer').Buffer function OAuth (request) { this.request = request this.params = null } OAuth.prototype.buildParams = function (_oauth, uri, method, query, form, qsLib) { var oa = {} for (var i in _oauth) { oa['oauth_' + i] = _oauth[i] } if (!oa.oauth_version) { oa.oauth_version = '1.0' } if (!oa.oauth_timestamp) { oa.oauth_timestamp = Math.floor(Date.now() / 1000).toString() } if (!oa.oauth_nonce) { oa.oauth_nonce = uuid().replace(/-/g, '') } if (!oa.oauth_signature_method) { oa.oauth_signature_method = 'HMAC-SHA1' } var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key // eslint-disable-line camelcase delete oa.oauth_consumer_secret delete oa.oauth_private_key var token_secret = oa.oauth_token_secret // eslint-disable-line camelcase delete oa.oauth_token_secret var realm = oa.oauth_realm delete oa.oauth_realm delete oa.oauth_transport_method var baseurl = uri.protocol + '//' + uri.host + uri.pathname var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&')) oa.oauth_signature = oauth.sign( oa.oauth_signature_method, method, baseurl, params, consumer_secret_or_private_key, // eslint-disable-line camelcase token_secret // eslint-disable-line camelcase ) if (realm) { oa.realm = realm } return oa } OAuth.prototype.buildBodyHash = function (_oauth, body) { if (['HMAC-SHA1', 'RSA-SHA1'].indexOf(_oauth.signature_method || 'HMAC-SHA1') < 0) { this.request.emit('error', new Error('oauth: ' + _oauth.signature_method + ' signature_method not supported with body_hash signing.')) } var shasum = crypto.createHash('sha1') shasum.update(body || '') var sha1 = shasum.digest('hex') return Buffer.from(sha1, 'hex').toString('base64') } OAuth.prototype.concatParams = function (oa, sep, wrap) { wrap = wrap || '' var params = Object.keys(oa).filter(function (i) { return i !== 'realm' && i !== 'oauth_signature' }).sort() if (oa.realm) { params.splice(0, 0, 'realm') } params.push('oauth_signature') return params.map(function (i) { return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap }).join(sep) } OAuth.prototype.onRequest = function (_oauth) { var self = this self.params = _oauth var uri = self.request.uri || {} var method = self.request.method || '' var headers = caseless(self.request.headers) var body = self.request.body || '' var qsLib = self.request.qsLib || qs var form var query var contentType = headers.get('content-type') || '' var formContentType = 'application/x-www-form-urlencoded' var transport = _oauth.transport_method || 'header' if (contentType.slice(0, formContentType.length) === formContentType) { contentType = formContentType form = body } if (uri.query) { query = uri.query } if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) { self.request.emit('error', new Error('oauth: transport_method of body requires POST ' + 'and content-type ' + formContentType)) } if (!form && typeof _oauth.body_hash === 'boolean') { _oauth.body_hash = self.buildBodyHash(_oauth, self.request.body.toString()) } var oa = self.buildParams(_oauth, uri, method, query, form, qsLib) switch (transport) { case 'header': self.request.setHeader('Authorization', 'OAuth ' + self.concatParams(oa, ',', '"')) break case 'query': var href = self.request.uri.href += (query ? '&' : '?') + self.concatParams(oa, '&') self.request.uri = url.parse(href) self.request.path = self.request.uri.path break case 'body': self.request.body = (form ? form + '&' : '') + self.concatParams(oa, '&') break default: self.request.emit('error', new Error('oauth: transport_method invalid')) } } exports.OAuth = OAuth
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/oauth.js
oauth.js
'use strict' var uuid = require('uuid/v4') var CombinedStream = require('combined-stream') var isstream = require('isstream') var Buffer = require('safe-buffer').Buffer function Multipart (request) { this.request = request this.boundary = uuid() this.chunked = false this.body = null } Multipart.prototype.isChunked = function (options) { var self = this var chunked = false var parts = options.data || options if (!parts.forEach) { self.request.emit('error', new Error('Argument error, options.multipart.')) } if (options.chunked !== undefined) { chunked = options.chunked } if (self.request.getHeader('transfer-encoding') === 'chunked') { chunked = true } if (!chunked) { parts.forEach(function (part) { if (typeof part.body === 'undefined') { self.request.emit('error', new Error('Body attribute missing in multipart.')) } if (isstream(part.body)) { chunked = true } }) } return chunked } Multipart.prototype.setHeaders = function (chunked) { var self = this if (chunked && !self.request.hasHeader('transfer-encoding')) { self.request.setHeader('transfer-encoding', 'chunked') } var header = self.request.getHeader('content-type') if (!header || header.indexOf('multipart') === -1) { self.request.setHeader('content-type', 'multipart/related; boundary=' + self.boundary) } else { if (header.indexOf('boundary') !== -1) { self.boundary = header.replace(/.*boundary=([^\s;]+).*/, '$1') } else { self.request.setHeader('content-type', header + '; boundary=' + self.boundary) } } } Multipart.prototype.build = function (parts, chunked) { var self = this var body = chunked ? new CombinedStream() : [] function add (part) { if (typeof part === 'number') { part = part.toString() } return chunked ? body.append(part) : body.push(Buffer.from(part)) } if (self.request.preambleCRLF) { add('\r\n') } parts.forEach(function (part) { var preamble = '--' + self.boundary + '\r\n' Object.keys(part).forEach(function (key) { if (key === 'body') { return } preamble += key + ': ' + part[key] + '\r\n' }) preamble += '\r\n' add(preamble) add(part.body) add('\r\n') }) add('--' + self.boundary + '--') if (self.request.postambleCRLF) { add('\r\n') } return body } Multipart.prototype.onRequest = function (options) { var self = this var chunked = self.isChunked(options) var parts = options.data || options self.setHeaders(chunked) self.chunked = chunked self.body = self.build(parts, chunked) } exports.Multipart = Multipart
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/multipart.js
multipart.js
'use strict' function formatHostname (hostname) { // canonicalize the hostname, so that 'oogle.com' won't match 'google.com' return hostname.replace(/^\.*/, '.').toLowerCase() } function parseNoProxyZone (zone) { zone = zone.trim().toLowerCase() var zoneParts = zone.split(':', 2) var zoneHost = formatHostname(zoneParts[0]) var zonePort = zoneParts[1] var hasPort = zone.indexOf(':') > -1 return {hostname: zoneHost, port: zonePort, hasPort: hasPort} } function uriInNoProxy (uri, noProxy) { var port = uri.port || (uri.protocol === 'https:' ? '443' : '80') var hostname = formatHostname(uri.hostname) var noProxyList = noProxy.split(',') // iterate through the noProxyList until it finds a match. return noProxyList.map(parseNoProxyZone).some(function (noProxyZone) { var isMatchedAt = hostname.indexOf(noProxyZone.hostname) var hostnameMatched = ( isMatchedAt > -1 && (isMatchedAt === hostname.length - noProxyZone.hostname.length) ) if (noProxyZone.hasPort) { return (port === noProxyZone.port) && hostnameMatched } return hostnameMatched }) } function getProxyFromURI (uri) { // Decide the proper request proxy to use based on the request URI object and the // environmental variables (NO_PROXY, HTTP_PROXY, etc.) // respect NO_PROXY environment variables (see: https://lynx.invisible-island.net/lynx2.8.7/breakout/lynx_help/keystrokes/environments.html) var noProxy = process.env.NO_PROXY || process.env.no_proxy || '' // if the noProxy is a wildcard then return null if (noProxy === '*') { return null } // if the noProxy is not empty and the uri is found return null if (noProxy !== '' && uriInNoProxy(uri, noProxy)) { return null } // Check for HTTP or HTTPS Proxy in environment Else default to null if (uri.protocol === 'http:') { return process.env.HTTP_PROXY || process.env.http_proxy || null } if (uri.protocol === 'https:') { return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null } // if none of that works, return null // (What uri protocol are you using then?) return null } module.exports = getProxyFromURI
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/getProxyFromURI.js
getProxyFromURI.js
'use strict' var fs = require('fs') var qs = require('querystring') var validate = require('har-validator') var extend = require('extend') function Har (request) { this.request = request } Har.prototype.reducer = function (obj, pair) { // new property ? if (obj[pair.name] === undefined) { obj[pair.name] = pair.value return obj } // existing? convert to array var arr = [ obj[pair.name], pair.value ] obj[pair.name] = arr return obj } Har.prototype.prep = function (data) { // construct utility properties data.queryObj = {} data.headersObj = {} data.postData.jsonObj = false data.postData.paramsObj = false // construct query objects if (data.queryString && data.queryString.length) { data.queryObj = data.queryString.reduce(this.reducer, {}) } // construct headers objects if (data.headers && data.headers.length) { // loweCase header keys data.headersObj = data.headers.reduceRight(function (headers, header) { headers[header.name] = header.value return headers }, {}) } // construct Cookie header if (data.cookies && data.cookies.length) { var cookies = data.cookies.map(function (cookie) { return cookie.name + '=' + cookie.value }) if (cookies.length) { data.headersObj.cookie = cookies.join('; ') } } // prep body function some (arr) { return arr.some(function (type) { return data.postData.mimeType.indexOf(type) === 0 }) } if (some([ 'multipart/mixed', 'multipart/related', 'multipart/form-data', 'multipart/alternative'])) { // reset values data.postData.mimeType = 'multipart/form-data' } else if (some([ 'application/x-www-form-urlencoded'])) { if (!data.postData.params) { data.postData.text = '' } else { data.postData.paramsObj = data.postData.params.reduce(this.reducer, {}) // always overwrite data.postData.text = qs.stringify(data.postData.paramsObj) } } else if (some([ 'text/json', 'text/x-json', 'application/json', 'application/x-json'])) { data.postData.mimeType = 'application/json' if (data.postData.text) { try { data.postData.jsonObj = JSON.parse(data.postData.text) } catch (e) { this.request.debug(e) // force back to text/plain data.postData.mimeType = 'text/plain' } } } return data } Har.prototype.options = function (options) { // skip if no har property defined if (!options.har) { return options } var har = {} extend(har, options.har) // only process the first entry if (har.log && har.log.entries) { har = har.log.entries[0] } // add optional properties to make validation successful har.url = har.url || options.url || options.uri || options.baseUrl || '/' har.httpVersion = har.httpVersion || 'HTTP/1.1' har.queryString = har.queryString || [] har.headers = har.headers || [] har.cookies = har.cookies || [] har.postData = har.postData || {} har.postData.mimeType = har.postData.mimeType || 'application/octet-stream' har.bodySize = 0 har.headersSize = 0 har.postData.size = 0 if (!validate.request(har)) { return options } // clean up and get some utility properties var req = this.prep(har) // construct new options if (req.url) { options.url = req.url } if (req.method) { options.method = req.method } if (Object.keys(req.queryObj).length) { options.qs = req.queryObj } if (Object.keys(req.headersObj).length) { options.headers = req.headersObj } function test (type) { return req.postData.mimeType.indexOf(type) === 0 } if (test('application/x-www-form-urlencoded')) { options.form = req.postData.paramsObj } else if (test('application/json')) { if (req.postData.jsonObj) { options.body = req.postData.jsonObj options.json = true } } else if (test('multipart/form-data')) { options.formData = {} req.postData.params.forEach(function (param) { var attachment = {} if (!param.fileName && !param.contentType) { options.formData[param.name] = param.value return } // attempt to read from disk! if (param.fileName && !param.value) { attachment.value = fs.createReadStream(param.fileName) } else if (param.value) { attachment.value = param.value } if (param.fileName) { attachment.options = { filename: param.fileName, contentType: param.contentType ? param.contentType : null } } options.formData[param.name] = attachment }) } else { if (req.postData.text) { options.body = req.postData.text } } return options } exports.Har = Har
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/har.js
har.js
'use strict' var caseless = require('caseless') var uuid = require('uuid/v4') var helpers = require('request/lib/helpers') var md5 = helpers.md5 var toBase64 = helpers.toBase64 function Auth (request) { // define all public properties here this.request = request this.hasAuth = false this.sentAuth = false this.bearerToken = null this.user = null this.pass = null } Auth.prototype.basic = function (user, pass, sendImmediately) { var self = this if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) { self.request.emit('error', new Error('auth() received invalid user or password')) } self.user = user self.pass = pass self.hasAuth = true var header = user + ':' + (pass || '') if (sendImmediately || typeof sendImmediately === 'undefined') { var authHeader = 'Basic ' + toBase64(header) self.sentAuth = true return authHeader } } Auth.prototype.bearer = function (bearer, sendImmediately) { var self = this self.bearerToken = bearer self.hasAuth = true if (sendImmediately || typeof sendImmediately === 'undefined') { if (typeof bearer === 'function') { bearer = bearer() } var authHeader = 'Bearer ' + (bearer || '') self.sentAuth = true return authHeader } } Auth.prototype.digest = function (method, path, authHeader) { // TODO: More complete implementation of RFC 2617. // - handle challenge.domain // - support qop="auth-int" only // - handle Authentication-Info (not necessarily?) // - check challenge.stale (not necessarily?) // - increase nc (not necessarily?) // For reference: // http://tools.ietf.org/html/rfc2617#section-3 // https://github.com/bagder/curl/blob/master/lib/http_digest.c var self = this var challenge = {} var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi while (true) { var match = re.exec(authHeader) if (!match) { break } challenge[match[1]] = match[2] || match[3] } /** * RFC 2617: handle both MD5 and MD5-sess algorithms. * * If the algorithm directive's value is "MD5" or unspecified, then HA1 is * HA1=MD5(username:realm:password) * If the algorithm directive's value is "MD5-sess", then HA1 is * HA1=MD5(MD5(username:realm:password):nonce:cnonce) */ var ha1Compute = function (algorithm, user, realm, pass, nonce, cnonce) { var ha1 = md5(user + ':' + realm + ':' + pass) if (algorithm && algorithm.toLowerCase() === 'md5-sess') { return md5(ha1 + ':' + nonce + ':' + cnonce) } else { return ha1 } } var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth' var nc = qop && '00000001' var cnonce = qop && uuid().replace(/-/g, '') var ha1 = ha1Compute(challenge.algorithm, self.user, challenge.realm, self.pass, challenge.nonce, cnonce) var ha2 = md5(method + ':' + path) var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2) var authValues = { username: self.user, realm: challenge.realm, nonce: challenge.nonce, uri: path, qop: qop, response: digestResponse, nc: nc, cnonce: cnonce, algorithm: challenge.algorithm, opaque: challenge.opaque } authHeader = [] for (var k in authValues) { if (authValues[k]) { if (k === 'qop' || k === 'nc' || k === 'algorithm') { authHeader.push(k + '=' + authValues[k]) } else { authHeader.push(k + '="' + authValues[k] + '"') } } } authHeader = 'Digest ' + authHeader.join(', ') self.sentAuth = true return authHeader } Auth.prototype.onRequest = function (user, pass, sendImmediately, bearer) { var self = this var request = self.request var authHeader if (bearer === undefined && user === undefined) { self.request.emit('error', new Error('no auth mechanism defined')) } else if (bearer !== undefined) { authHeader = self.bearer(bearer, sendImmediately) } else { authHeader = self.basic(user, pass, sendImmediately) } if (authHeader) { request.setHeader('authorization', authHeader) } } Auth.prototype.onResponse = function (response) { var self = this var request = self.request if (!self.hasAuth || self.sentAuth) { return null } var c = caseless(response.headers) var authHeader = c.get('www-authenticate') var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase() request.debug('reauth', authVerb) switch (authVerb) { case 'basic': return self.basic(self.user, self.pass, true) case 'bearer': return self.bearer(self.bearerToken, true) case 'digest': return self.digest(request.method, request.path, authHeader) } } exports.Auth = Auth
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/auth.js
auth.js
'use strict' var url = require('url') var isUrl = /^https?:/ function Redirect (request) { this.request = request this.followRedirect = true this.followRedirects = true this.followAllRedirects = false this.followOriginalHttpMethod = false this.allowRedirect = function () { return true } this.maxRedirects = 10 this.redirects = [] this.redirectsFollowed = 0 this.removeRefererHeader = false } Redirect.prototype.onRequest = function (options) { var self = this if (options.maxRedirects !== undefined) { self.maxRedirects = options.maxRedirects } if (typeof options.followRedirect === 'function') { self.allowRedirect = options.followRedirect } if (options.followRedirect !== undefined) { self.followRedirects = !!options.followRedirect } if (options.followAllRedirects !== undefined) { self.followAllRedirects = options.followAllRedirects } if (self.followRedirects || self.followAllRedirects) { self.redirects = self.redirects || [] } if (options.removeRefererHeader !== undefined) { self.removeRefererHeader = options.removeRefererHeader } if (options.followOriginalHttpMethod !== undefined) { self.followOriginalHttpMethod = options.followOriginalHttpMethod } } Redirect.prototype.redirectTo = function (response) { var self = this var request = self.request var redirectTo = null if (response.statusCode >= 300 && response.statusCode < 400 && response.caseless.has('location')) { var location = response.caseless.get('location') request.debug('redirect', location) if (self.followAllRedirects) { redirectTo = location } else if (self.followRedirects) { switch (request.method) { case 'PATCH': case 'PUT': case 'POST': case 'DELETE': // Do not follow redirects break default: redirectTo = location break } } } else if (response.statusCode === 401) { var authHeader = request._auth.onResponse(response) if (authHeader) { request.setHeader('authorization', authHeader) redirectTo = request.uri } } return redirectTo } Redirect.prototype.onResponse = function (response) { var self = this var request = self.request var redirectTo = self.redirectTo(response) if (!redirectTo || !self.allowRedirect.call(request, response)) { return false } request.debug('redirect to', redirectTo) // ignore any potential response body. it cannot possibly be useful // to us at this point. // response.resume should be defined, but check anyway before calling. Workaround for browserify. if (response.resume) { response.resume() } if (self.redirectsFollowed >= self.maxRedirects) { request.emit('error', new Error('Exceeded maxRedirects. Probably stuck in a redirect loop ' + request.uri.href)) return false } self.redirectsFollowed += 1 if (!isUrl.test(redirectTo)) { redirectTo = url.resolve(request.uri.href, redirectTo) } var uriPrev = request.uri request.uri = url.parse(redirectTo) // handle the case where we change protocol from https to http or vice versa if (request.uri.protocol !== uriPrev.protocol) { delete request.agent } self.redirects.push({ statusCode: response.statusCode, redirectUri: redirectTo }) if (self.followAllRedirects && request.method !== 'HEAD' && response.statusCode !== 401 && response.statusCode !== 307) { request.method = self.followOriginalHttpMethod ? request.method : 'GET' } // request.method = 'GET' // Force all redirects to use GET || commented out fixes #215 delete request.src delete request.req delete request._started if (response.statusCode !== 401 && response.statusCode !== 307) { // Remove parameters from the previous response, unless this is the second request // for a server that requires digest authentication. delete request.body delete request._form if (request.headers) { request.removeHeader('host') request.removeHeader('content-type') request.removeHeader('content-length') if (request.uri.hostname !== request.originalHost.split(':')[0]) { // Remove authorization if changing hostnames (but not if just // changing ports or protocols). This matches the behavior of curl: // https://github.com/bagder/curl/blob/6beb0eee/lib/http.c#L710 request.removeHeader('authorization') } } } if (!self.removeRefererHeader) { request.setHeader('referer', uriPrev.href) } request.emit('redirect') request.init() return true } exports.Redirect = Redirect
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/redirect.js
redirect.js
'use strict' var crypto = require('crypto') function randomString (size) { var bits = (size + 1) * 6 var buffer = crypto.randomBytes(Math.ceil(bits / 8)) var string = buffer.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '') return string.slice(0, size) } function calculatePayloadHash (payload, algorithm, contentType) { var hash = crypto.createHash(algorithm) hash.update('hawk.1.payload\n') hash.update((contentType ? contentType.split(';')[0].trim().toLowerCase() : '') + '\n') hash.update(payload || '') hash.update('\n') return hash.digest('base64') } exports.calculateMac = function (credentials, opts) { var normalized = 'hawk.1.header\n' + opts.ts + '\n' + opts.nonce + '\n' + (opts.method || '').toUpperCase() + '\n' + opts.resource + '\n' + opts.host.toLowerCase() + '\n' + opts.port + '\n' + (opts.hash || '') + '\n' if (opts.ext) { normalized = normalized + opts.ext.replace('\\', '\\\\').replace('\n', '\\n') } normalized = normalized + '\n' if (opts.app) { normalized = normalized + opts.app + '\n' + (opts.dlg || '') + '\n' } var hmac = crypto.createHmac(credentials.algorithm, credentials.key).update(normalized) var digest = hmac.digest('base64') return digest } exports.header = function (uri, method, opts) { var timestamp = opts.timestamp || Math.floor((Date.now() + (opts.localtimeOffsetMsec || 0)) / 1000) var credentials = opts.credentials if (!credentials || !credentials.id || !credentials.key || !credentials.algorithm) { return '' } if (['sha1', 'sha256'].indexOf(credentials.algorithm) === -1) { return '' } var artifacts = { ts: timestamp, nonce: opts.nonce || randomString(6), method: method, resource: uri.pathname + (uri.search || ''), host: uri.hostname, port: uri.port || (uri.protocol === 'http:' ? 80 : 443), hash: opts.hash, ext: opts.ext, app: opts.app, dlg: opts.dlg } if (!artifacts.hash && (opts.payload || opts.payload === '')) { artifacts.hash = calculatePayloadHash(opts.payload, credentials.algorithm, opts.contentType) } var mac = exports.calculateMac(credentials, artifacts) var hasExt = artifacts.ext !== null && artifacts.ext !== undefined && artifacts.ext !== '' var header = 'Hawk id="' + credentials.id + '", ts="' + artifacts.ts + '", nonce="' + artifacts.nonce + (artifacts.hash ? '", hash="' + artifacts.hash : '') + (hasExt ? '", ext="' + artifacts.ext.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : '') + '", mac="' + mac + '"' if (artifacts.app) { header = header + ', app="' + artifacts.app + (artifacts.dlg ? '", dlg="' + artifacts.dlg : '') + '"' } return header }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/hawk.js
hawk.js
'use strict' var url = require('url') var tunnel = require('tunnel-agent') var defaultProxyHeaderWhiteList = [ 'accept', 'accept-charset', 'accept-encoding', 'accept-language', 'accept-ranges', 'cache-control', 'content-encoding', 'content-language', 'content-location', 'content-md5', 'content-range', 'content-type', 'connection', 'date', 'expect', 'max-forwards', 'pragma', 'referer', 'te', 'user-agent', 'via' ] var defaultProxyHeaderExclusiveList = [ 'proxy-authorization' ] function constructProxyHost (uriObject) { var port = uriObject.port var protocol = uriObject.protocol var proxyHost = uriObject.hostname + ':' if (port) { proxyHost += port } else if (protocol === 'https:') { proxyHost += '443' } else { proxyHost += '80' } return proxyHost } function constructProxyHeaderWhiteList (headers, proxyHeaderWhiteList) { var whiteList = proxyHeaderWhiteList .reduce(function (set, header) { set[header.toLowerCase()] = true return set }, {}) return Object.keys(headers) .filter(function (header) { return whiteList[header.toLowerCase()] }) .reduce(function (set, header) { set[header] = headers[header] return set }, {}) } function constructTunnelOptions (request, proxyHeaders) { var proxy = request.proxy var tunnelOptions = { proxy: { host: proxy.hostname, port: +proxy.port, proxyAuth: proxy.auth, headers: proxyHeaders }, headers: request.headers, ca: request.ca, cert: request.cert, key: request.key, passphrase: request.passphrase, pfx: request.pfx, ciphers: request.ciphers, rejectUnauthorized: request.rejectUnauthorized, secureOptions: request.secureOptions, secureProtocol: request.secureProtocol } return tunnelOptions } function constructTunnelFnName (uri, proxy) { var uriProtocol = (uri.protocol === 'https:' ? 'https' : 'http') var proxyProtocol = (proxy.protocol === 'https:' ? 'Https' : 'Http') return [uriProtocol, proxyProtocol].join('Over') } function getTunnelFn (request) { var uri = request.uri var proxy = request.proxy var tunnelFnName = constructTunnelFnName(uri, proxy) return tunnel[tunnelFnName] } function Tunnel (request) { this.request = request this.proxyHeaderWhiteList = defaultProxyHeaderWhiteList this.proxyHeaderExclusiveList = [] if (typeof request.tunnel !== 'undefined') { this.tunnelOverride = request.tunnel } } Tunnel.prototype.isEnabled = function () { var self = this var request = self.request // Tunnel HTTPS by default. Allow the user to override this setting. // If self.tunnelOverride is set (the user specified a value), use it. if (typeof self.tunnelOverride !== 'undefined') { return self.tunnelOverride } // If the destination is HTTPS, tunnel. if (request.uri.protocol === 'https:') { return true } // Otherwise, do not use tunnel. return false } Tunnel.prototype.setup = function (options) { var self = this var request = self.request options = options || {} if (typeof request.proxy === 'string') { request.proxy = url.parse(request.proxy) } if (!request.proxy || !request.tunnel) { return false } // Setup Proxy Header Exclusive List and White List if (options.proxyHeaderWhiteList) { self.proxyHeaderWhiteList = options.proxyHeaderWhiteList } if (options.proxyHeaderExclusiveList) { self.proxyHeaderExclusiveList = options.proxyHeaderExclusiveList } var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList) var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList) // Setup Proxy Headers and Proxy Headers Host // Only send the Proxy White Listed Header names var proxyHeaders = constructProxyHeaderWhiteList(request.headers, proxyHeaderWhiteList) proxyHeaders.host = constructProxyHost(request.uri) proxyHeaderExclusiveList.forEach(request.removeHeader, request) // Set Agent from Tunnel Data var tunnelFn = getTunnelFn(request) var tunnelOptions = constructTunnelOptions(request, proxyHeaders) request.agent = tunnelFn(tunnelOptions) return true } Tunnel.defaultProxyHeaderWhiteList = defaultProxyHeaderWhiteList Tunnel.defaultProxyHeaderExclusiveList = defaultProxyHeaderExclusiveList exports.Tunnel = Tunnel
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/request/lib/tunnel.js
tunnel.js
# combined-stream A stream that emits multiple other streams one after another. **NB** Currently `combined-stream` works with streams version 1 only. There is ongoing effort to switch this library to streams version 2. Any help is welcome. :) Meanwhile you can explore other libraries that provide streams2 support with more or less compatibility with `combined-stream`. - [combined-stream2](https://www.npmjs.com/package/combined-stream2): A drop-in streams2-compatible replacement for the combined-stream module. - [multistream](https://www.npmjs.com/package/multistream): A stream that emits multiple other streams one after another. ## Installation ``` bash npm install combined-stream ``` ## Usage Here is a simple example that shows how you can use combined-stream to combine two files into one: ``` javascript var CombinedStream = require('combined-stream'); var fs = require('fs'); var combinedStream = CombinedStream.create(); combinedStream.append(fs.createReadStream('file1.txt')); combinedStream.append(fs.createReadStream('file2.txt')); combinedStream.pipe(fs.createWriteStream('combined.txt')); ``` While the example above works great, it will pause all source streams until they are needed. If you don't want that to happen, you can set `pauseStreams` to `false`: ``` javascript var CombinedStream = require('combined-stream'); var fs = require('fs'); var combinedStream = CombinedStream.create({pauseStreams: false}); combinedStream.append(fs.createReadStream('file1.txt')); combinedStream.append(fs.createReadStream('file2.txt')); combinedStream.pipe(fs.createWriteStream('combined.txt')); ``` However, what if you don't have all the source streams yet, or you don't want to allocate the resources (file descriptors, memory, etc.) for them right away? Well, in that case you can simply provide a callback that supplies the stream by calling a `next()` function: ``` javascript var CombinedStream = require('combined-stream'); var fs = require('fs'); var combinedStream = CombinedStream.create(); combinedStream.append(function(next) { next(fs.createReadStream('file1.txt')); }); combinedStream.append(function(next) { next(fs.createReadStream('file2.txt')); }); combinedStream.pipe(fs.createWriteStream('combined.txt')); ``` ## API ### CombinedStream.create([options]) Returns a new combined stream object. Available options are: * `maxDataSize` * `pauseStreams` The effect of those options is described below. ### combinedStream.pauseStreams = `true` Whether to apply back pressure to the underlaying streams. If set to `false`, the underlaying streams will never be paused. If set to `true`, the underlaying streams will be paused right after being appended, as well as when `delayedStream.pipe()` wants to throttle. ### combinedStream.maxDataSize = `2 * 1024 * 1024` The maximum amount of bytes (or characters) to buffer for all source streams. If this value is exceeded, `combinedStream` emits an `'error'` event. ### combinedStream.dataSize = `0` The amount of bytes (or characters) currently buffered by `combinedStream`. ### combinedStream.append(stream) Appends the given `stream` to the combinedStream object. If `pauseStreams` is set to `true, this stream will also be paused right away. `streams` can also be a function that takes one parameter called `next`. `next` is a function that must be invoked in order to provide the `next` stream, see example above. Regardless of how the `stream` is appended, combined-stream always attaches an `'error'` listener to it, so you don't have to do that manually. Special case: `stream` can also be a String or Buffer. ### combinedStream.write(data) You should not call this, `combinedStream` takes care of piping the appended streams into itself for you. ### combinedStream.resume() Causes `combinedStream` to start drain the streams it manages. The function is idempotent, and also emits a `'resume'` event each time which usually goes to the stream that is currently being drained. ### combinedStream.pause(); If `combinedStream.pauseStreams` is set to `false`, this does nothing. Otherwise a `'pause'` event is emitted, this goes to the stream that is currently being drained, so you can use it to apply back pressure. ### combinedStream.end(); Sets `combinedStream.writable` to false, emits an `'end'` event, and removes all streams from the queue. ### combinedStream.destroy(); Same as `combinedStream.end()`, except it emits a `'close'` event instead of `'end'`. ## License combined-stream is licensed under the MIT license.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/combined-stream/Readme.md
Readme.md
var util = require('util'); var Stream = require('stream').Stream; var DelayedStream = require('delayed-stream'); 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; this._insideLoop = false; this._pendingNext = false; } 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; if (this._insideLoop) { this._pendingNext = true; return; // defer call } this._insideLoop = true; try { do { this._pendingNext = false; this._realGetNext(); } while (this._pendingNext); } finally { this._insideLoop = false; } }; CombinedStream.prototype._realGetNext = function() { 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); } this._pipeNext(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); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/combined-stream/lib/combined_stream.js
combined_stream.js
# fast-deep-equal The fastest deep equal with ES6 Map, Set and Typed arrays support. [![Build Status](https://travis-ci.org/epoberezkin/fast-deep-equal.svg?branch=master)](https://travis-ci.org/epoberezkin/fast-deep-equal) [![npm](https://img.shields.io/npm/v/fast-deep-equal.svg)](https://www.npmjs.com/package/fast-deep-equal) [![Coverage Status](https://coveralls.io/repos/github/epoberezkin/fast-deep-equal/badge.svg?branch=master)](https://coveralls.io/github/epoberezkin/fast-deep-equal?branch=master) ## Install ```bash npm install fast-deep-equal ``` ## Features - ES5 compatible - works in node.js (8+) and browsers (IE9+) - checks equality of Date and RegExp objects by value. ES6 equal (`require('fast-deep-equal/es6')`) also supports: - Maps - Sets - Typed arrays ## Usage ```javascript var equal = require('fast-deep-equal'); console.log(equal({foo: 'bar'}, {foo: 'bar'})); // true ``` To support ES6 Maps, Sets and Typed arrays equality use: ```javascript var equal = require('fast-deep-equal/es6'); console.log(equal(Int16Array([1, 2]), Int16Array([1, 2]))); // true ``` To use with React (avoiding the traversal of React elements' _owner property that contains circular references and is not needed when comparing the elements - borrowed from [react-fast-compare](https://github.com/FormidableLabs/react-fast-compare)): ```javascript var equal = require('fast-deep-equal/react'); var equal = require('fast-deep-equal/es6/react'); ``` ## Performance benchmark Node.js v12.6.0: ``` fast-deep-equal x 261,950 ops/sec ±0.52% (89 runs sampled) fast-deep-equal/es6 x 212,991 ops/sec ±0.34% (92 runs sampled) fast-equals x 230,957 ops/sec ±0.83% (85 runs sampled) nano-equal x 187,995 ops/sec ±0.53% (88 runs sampled) shallow-equal-fuzzy x 138,302 ops/sec ±0.49% (90 runs sampled) underscore.isEqual x 74,423 ops/sec ±0.38% (89 runs sampled) lodash.isEqual x 36,637 ops/sec ±0.72% (90 runs sampled) deep-equal x 2,310 ops/sec ±0.37% (90 runs sampled) deep-eql x 35,312 ops/sec ±0.67% (91 runs sampled) ramda.equals x 12,054 ops/sec ±0.40% (91 runs sampled) util.isDeepStrictEqual x 46,440 ops/sec ±0.43% (90 runs sampled) assert.deepStrictEqual x 456 ops/sec ±0.71% (88 runs sampled) The fastest is fast-deep-equal ``` To run benchmark (requires node.js 6+): ```bash npm run benchmark ``` __Please note__: this benchmark runs against the available test cases. To choose the most performant library for your application, it is recommended to benchmark against your data and to NOT expect this benchmark to reflect the performance difference in your application. ## Enterprise support fast-deep-equal package is a part of [Tidelift enterprise subscription](https://tidelift.com/subscription/pkg/npm-fast-deep-equal?utm_source=npm-fast-deep-equal&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) - it provides a centralised commercial support to open-source software users, in addition to the support provided by software maintainers. ## Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerability via GitHub issues. ## License [MIT](https://github.com/epoberezkin/fast-deep-equal/blob/master/LICENSE)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/fast-deep-equal/README.md
README.md
'use strict'; // do not edit .js files directly - edit src/index.jst var envHasBigInt64Array = typeof BigInt64Array !== 'undefined'; module.exports = function equal(a, b) { if (a === b) return true; if (a && b && typeof a == 'object' && typeof b == 'object') { if (a.constructor !== b.constructor) return false; var length, i, keys; if (Array.isArray(a)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; return true; } if ((a instanceof Map) && (b instanceof Map)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; for (i of a.entries()) if (!equal(i[1], b.get(i[0]))) return false; return true; } if ((a instanceof Set) && (b instanceof Set)) { if (a.size !== b.size) return false; for (i of a.entries()) if (!b.has(i[0])) return false; return true; } if (ArrayBuffer.isView(a) && ArrayBuffer.isView(b)) { length = a.length; if (length != b.length) return false; for (i = length; i-- !== 0;) if (a[i] !== b[i]) return false; return true; } if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); keys = Object.keys(a); length = keys.length; if (length !== Object.keys(b).length) return false; for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; for (i = length; i-- !== 0;) { var key = keys[i]; if (key === '_owner' && a.$$typeof) { // React-specific: avoid traversing React elements' _owner. // _owner contains circular references // and is not needed when comparing the actual elements (and not their owners) continue; } if (!equal(a[key], b[key])) return false; } return true; } // true if both NaN, false otherwise return a!==a && b!==b; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/fast-deep-equal/es6/react.js
react.js
# performance-now [![Build Status](https://travis-ci.org/braveg1rl/performance-now.png?branch=master)](https://travis-ci.org/braveg1rl/performance-now) [![Dependency Status](https://david-dm.org/braveg1rl/performance-now.png)](https://david-dm.org/braveg1rl/performance-now) Implements a function similar to `performance.now` (based on `process.hrtime`). Modern browsers have a `window.performance` object with - among others - a `now` method which gives time in milliseconds, but with sub-millisecond precision. This module offers the same function based on the Node.js native `process.hrtime` function. Using `process.hrtime` means that the reported time will be monotonically increasing, and not subject to clock-drift. According to the [High Resolution Time specification](http://www.w3.org/TR/hr-time/), the number of milliseconds reported by `performance.now` should be relative to the value of `performance.timing.navigationStart`. In the current version of the module (2.0) the reported time is relative to the time the current Node process has started (inferred from `process.uptime()`). Version 1.0 reported a different time. The reported time was relative to the time the module was loaded (i.e. the time it was first `require`d). If you need this functionality, version 1.0 is still available on NPM. ## Example usage ```javascript var now = require("performance-now") var start = now() var end = now() console.log(start.toFixed(3)) // the number of milliseconds the current node process is running console.log((start-end).toFixed(3)) // ~ 0.002 on my system ``` Running the now function two times right after each other yields a time difference of a few microseconds. Given this overhead, I think it's best to assume that the precision of intervals computed with this method is not higher than 10 microseconds, if you don't know the exact overhead on your own system. ## License performance-now is released under the [MIT License](http://opensource.org/licenses/MIT). Copyright (c) 2017 Braveg1rl
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/performance-now/README.md
README.md
'use strict' var net = require('net') , tls = require('tls') , http = require('http') , https = require('https') , events = require('events') , assert = require('assert') , util = require('util') , Buffer = require('safe-buffer').Buffer ; exports.httpOverHttp = httpOverHttp exports.httpsOverHttp = httpsOverHttp exports.httpOverHttps = httpOverHttps exports.httpsOverHttps = httpsOverHttps function httpOverHttp(options) { var agent = new TunnelingAgent(options) agent.request = http.request return agent } function httpsOverHttp(options) { var agent = new TunnelingAgent(options) agent.request = http.request agent.createSocket = createSecureSocket agent.defaultPort = 443 return agent } function httpOverHttps(options) { var agent = new TunnelingAgent(options) agent.request = https.request return agent } function httpsOverHttps(options) { var agent = new TunnelingAgent(options) agent.request = https.request agent.createSocket = createSecureSocket agent.defaultPort = 443 return agent } function TunnelingAgent(options) { var self = this self.options = options || {} self.proxyOptions = self.options.proxy || {} self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets self.requests = [] self.sockets = [] self.on('free', function onFree(socket, host, port) { for (var i = 0, len = self.requests.length; i < len; ++i) { var pending = self.requests[i] if (pending.host === host && pending.port === port) { // Detect the request to connect same origin server, // reuse the connection. self.requests.splice(i, 1) pending.request.onSocket(socket) return } } socket.destroy() self.removeSocket(socket) }) } util.inherits(TunnelingAgent, events.EventEmitter) TunnelingAgent.prototype.addRequest = function addRequest(req, options) { var self = this // Legacy API: addRequest(req, host, port, path) if (typeof options === 'string') { options = { host: options, port: arguments[2], path: arguments[3] }; } if (self.sockets.length >= this.maxSockets) { // We are over limit so we'll add it to the queue. self.requests.push({host: options.host, port: options.port, request: req}) return } // If we are under maxSockets create a new one. self.createConnection({host: options.host, port: options.port, request: req}) } TunnelingAgent.prototype.createConnection = function createConnection(pending) { var self = this self.createSocket(pending, function(socket) { socket.on('free', onFree) socket.on('close', onCloseOrRemove) socket.on('agentRemove', onCloseOrRemove) pending.request.onSocket(socket) function onFree() { self.emit('free', socket, pending.host, pending.port) } function onCloseOrRemove(err) { self.removeSocket(socket) socket.removeListener('free', onFree) socket.removeListener('close', onCloseOrRemove) socket.removeListener('agentRemove', onCloseOrRemove) } }) } TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { var self = this var placeholder = {} self.sockets.push(placeholder) var connectOptions = mergeOptions({}, self.proxyOptions, { method: 'CONNECT' , path: options.host + ':' + options.port , agent: false } ) if (connectOptions.proxyAuth) { connectOptions.headers = connectOptions.headers || {} connectOptions.headers['Proxy-Authorization'] = 'Basic ' + Buffer.from(connectOptions.proxyAuth).toString('base64') } debug('making CONNECT request') var connectReq = self.request(connectOptions) connectReq.useChunkedEncodingByDefault = false // for v0.6 connectReq.once('response', onResponse) // for v0.6 connectReq.once('upgrade', onUpgrade) // for v0.6 connectReq.once('connect', onConnect) // for v0.7 or later connectReq.once('error', onError) connectReq.end() function onResponse(res) { // Very hacky. This is necessary to avoid http-parser leaks. res.upgrade = true } function onUpgrade(res, socket, head) { // Hacky. process.nextTick(function() { onConnect(res, socket, head) }) } function onConnect(res, socket, head) { connectReq.removeAllListeners() socket.removeAllListeners() if (res.statusCode === 200) { assert.equal(head.length, 0) debug('tunneling connection has established') self.sockets[self.sockets.indexOf(placeholder)] = socket cb(socket) } else { debug('tunneling socket could not be established, statusCode=%d', res.statusCode) var error = new Error('tunneling socket could not be established, ' + 'statusCode=' + res.statusCode) error.code = 'ECONNRESET' options.request.emit('error', error) self.removeSocket(placeholder) } } function onError(cause) { connectReq.removeAllListeners() debug('tunneling socket could not be established, cause=%s\n', cause.message, cause.stack) var error = new Error('tunneling socket could not be established, ' + 'cause=' + cause.message) error.code = 'ECONNRESET' options.request.emit('error', error) self.removeSocket(placeholder) } } TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { var pos = this.sockets.indexOf(socket) if (pos === -1) return this.sockets.splice(pos, 1) var pending = this.requests.shift() if (pending) { // If we have pending requests and a socket gets closed a new one // needs to be created to take over in the pool for the one that closed. this.createConnection(pending) } } function createSecureSocket(options, cb) { var self = this TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { // 0 is dummy port for v0.6 var secureSocket = tls.connect(0, mergeOptions({}, self.options, { servername: options.host , socket: socket } )) self.sockets[self.sockets.indexOf(socket)] = secureSocket cb(secureSocket) }) } function mergeOptions(target) { for (var i = 1, len = arguments.length; i < len; ++i) { var overrides = arguments[i] if (typeof overrides === 'object') { var keys = Object.keys(overrides) for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { var k = keys[j] if (overrides[k] !== undefined) { target[k] = overrides[k] } } } } return target } var debug if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { debug = function() { var args = Array.prototype.slice.call(arguments) if (typeof args[0] === 'string') { args[0] = 'TUNNEL: ' + args[0] } else { args.unshift('TUNNEL:') } console.error.apply(console, args) } } else { debug = function() {} } exports.debug = debug // for test
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/tunnel-agent/index.js
index.js
<img align="right" alt="Ajv logo" width="160" src="https://ajv.js.org/images/ajv_logo.png"> # Ajv: Another JSON Schema Validator The fastest JSON Schema validator for Node.js and browser. Supports draft-04/06/07. [![Build Status](https://travis-ci.org/ajv-validator/ajv.svg?branch=master)](https://travis-ci.org/ajv-validator/ajv) [![npm](https://img.shields.io/npm/v/ajv.svg)](https://www.npmjs.com/package/ajv) [![npm downloads](https://img.shields.io/npm/dm/ajv.svg)](https://www.npmjs.com/package/ajv) [![Coverage Status](https://coveralls.io/repos/github/ajv-validator/ajv/badge.svg?branch=master)](https://coveralls.io/github/ajv-validator/ajv?branch=master) [![Gitter](https://img.shields.io/gitter/room/ajv-validator/ajv.svg)](https://gitter.im/ajv-validator/ajv) [![GitHub Sponsors](https://img.shields.io/badge/$-sponsors-brightgreen)](https://github.com/sponsors/epoberezkin) ## Please [sponsor Ajv development](https://github.com/sponsors/epoberezkin) I will get straight to the point - I need your support to ensure that the development of Ajv continues. I have developed Ajv for 5 years in my free time, but it is not sustainable. I'd appreciate if you consider supporting its further development with donations: - [GitHub sponsors page](https://github.com/sponsors/epoberezkin) (GitHub will match it) - [Ajv Open Collective️](https://opencollective.com/ajv) There are many small and large improvements that are long due, including the support of the next versions of JSON Schema specification, improving website and documentation, and making Ajv more modular and maintainable to address its limitations - what Ajv needs to evolve is much more than what I can contribute in my free time. I would also really appreciate any advice you could give on how to raise funds for Ajv development - whether some suitable open-source fund I could apply to or some sponsor I should approach. Since 2015 Ajv has become widely used, thanks to your help and contributions: - **90** contributors 🏗 - **5,000** dependent npm packages ⚙️ - **7,000** github stars, from GitHub users [all over the world](https://www.google.com/maps/d/u/0/viewer?mid=1MGRV8ciFUGIbO1l0EKFWNJGYE7iSkDxP&ll=-3.81666561775622e-14%2C4.821737100000007&z=2) ⭐️ - **5,000,000** dependent repositories on GitHub 🚀 - **120,000,000** npm downloads per month! 💯 I believe it would benefit all Ajv users to help put together the fund that will be used for its further development - it would allow to bring some additional maintainers to the project. Thank you #### Open Collective sponsors <a href="https://opencollective.com/ajv"><img src="https://opencollective.com/ajv/individuals.svg?width=890"></a> <a href="https://opencollective.com/ajv/organization/0/website"><img src="https://opencollective.com/ajv/organization/0/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/1/website"><img src="https://opencollective.com/ajv/organization/1/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/2/website"><img src="https://opencollective.com/ajv/organization/2/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/3/website"><img src="https://opencollective.com/ajv/organization/3/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/4/website"><img src="https://opencollective.com/ajv/organization/4/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/5/website"><img src="https://opencollective.com/ajv/organization/5/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/6/website"><img src="https://opencollective.com/ajv/organization/6/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/7/website"><img src="https://opencollective.com/ajv/organization/7/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/8/website"><img src="https://opencollective.com/ajv/organization/8/avatar.svg"></a> <a href="https://opencollective.com/ajv/organization/9/website"><img src="https://opencollective.com/ajv/organization/9/avatar.svg"></a> ## Using version 6 [JSON Schema draft-07](http://json-schema.org/latest/json-schema-validation.html) is published. [Ajv version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0) that supports draft-07 is released. It may require either migrating your schemas or updating your code (to continue using draft-04 and v5 schemas, draft-06 schemas will be supported without changes). __Please note__: To use Ajv with draft-06 schemas you need to explicitly add the meta-schema to the validator instance: ```javascript ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json')); ``` To use Ajv with draft-04 schemas in addition to explicitly adding meta-schema you also need to use option schemaId: ```javascript var ajv = new Ajv({schemaId: 'id'}); // If you want to use both draft-04 and draft-06/07 schemas: // var ajv = new Ajv({schemaId: 'auto'}); ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-04.json')); ``` ## Contents - [Performance](#performance) - [Features](#features) - [Getting started](#getting-started) - [Frequently Asked Questions](https://github.com/ajv-validator/ajv/blob/master/FAQ.md) - [Using in browser](#using-in-browser) - [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) - [Command line interface](#command-line-interface) - Validation - [Keywords](#validation-keywords) - [Annotation keywords](#annotation-keywords) - [Formats](#formats) - [Combining schemas with $ref](#ref) - [$data reference](#data-reference) - NEW: [$merge and $patch keywords](#merge-and-patch-keywords) - [Defining custom keywords](#defining-custom-keywords) - [Asynchronous schema compilation](#asynchronous-schema-compilation) - [Asynchronous validation](#asynchronous-validation) - [Security considerations](#security-considerations) - [Security contact](#security-contact) - [Untrusted schemas](#untrusted-schemas) - [Circular references in objects](#circular-references-in-javascript-objects) - [Trusted schemas](#security-risks-of-trusted-schemas) - [ReDoS attack](#redos-attack) - Modifying data during validation - [Filtering data](#filtering-data) - [Assigning defaults](#assigning-defaults) - [Coercing data types](#coercing-data-types) - API - [Methods](#api) - [Options](#options) - [Validation errors](#validation-errors) - [Plugins](#plugins) - [Related packages](#related-packages) - [Some packages using Ajv](#some-packages-using-ajv) - [Tests, Contributing, Changes history](#tests) - [Support, Code of conduct, License](#open-source-software-support) ## Performance Ajv generates code using [doT templates](https://github.com/olado/doT) to turn JSON Schemas into super-fast validation functions that are efficient for v8 optimization. Currently Ajv is the fastest and the most standard compliant validator according to these benchmarks: - [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark) - 50% faster than the second place - [jsck benchmark](https://github.com/pandastrike/jsck#benchmarks) - 20-190% faster - [z-schema benchmark](https://rawgit.com/zaggino/z-schema/master/benchmark/results.html) - [themis benchmark](https://cdn.rawgit.com/playlyfe/themis/master/benchmark/results.html) Performance of different validators by [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark): [![performance](https://chart.googleapis.com/chart?chxt=x,y&cht=bhs&chco=76A4FB&chls=2.0&chbh=32,4,1&chs=600x416&chxl=-1:|djv|ajv|json-schema-validator-generator|jsen|is-my-json-valid|themis|z-schema|jsck|skeemas|json-schema-library|tv4&chd=t:100,98,72.1,66.8,50.1,15.1,6.1,3.8,1.2,0.7,0.2)](https://github.com/ebdrup/json-schema-benchmark/blob/master/README.md#performance) ## Features - Ajv implements full JSON Schema [draft-06/07](http://json-schema.org/) and draft-04 standards: - all validation keywords (see [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md)) - full support of remote refs (remote schemas have to be added with `addSchema` or compiled to be available) - support of circular references between schemas - correct string lengths for strings with unicode pairs (can be turned off) - [formats](#formats) defined by JSON Schema draft-07 standard and custom formats (can be turned off) - [validates schemas against meta-schema](#api-validateschema) - supports [browsers](#using-in-browser) and Node.js 0.10-14.x - [asynchronous loading](#asynchronous-schema-compilation) of referenced schemas during compilation - "All errors" validation mode with [option allErrors](#options) - [error messages with parameters](#validation-errors) describing error reasons to allow creating custom error messages - i18n error messages support with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package - [filtering data](#filtering-data) from additional properties - [assigning defaults](#assigning-defaults) to missing properties and items - [coercing data](#coercing-data-types) to the types specified in `type` keywords - [custom keywords](#defining-custom-keywords) - draft-06/07 keywords `const`, `contains`, `propertyNames` and `if/then/else` - draft-06 boolean schemas (`true`/`false` as a schema to always pass/fail). - keywords `switch`, `patternRequired`, `formatMaximum` / `formatMinimum` and `formatExclusiveMaximum` / `formatExclusiveMinimum` from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) with [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - [$data reference](#data-reference) to use values from the validated data as values for the schema keywords - [asynchronous validation](#asynchronous-validation) of custom formats and keywords Currently Ajv is the only validator that passes all the tests from [JSON Schema Test Suite](https://github.com/json-schema/JSON-Schema-Test-Suite) (according to [json-schema-benchmark](https://github.com/ebdrup/json-schema-benchmark), apart from the test that requires that `1.0` is not an integer that is impossible to satisfy in JavaScript). ## Install ``` npm install ajv ``` ## <a name="usage"></a>Getting started Try it in the Node.js REPL: https://tonicdev.com/npm/ajv The fastest validation call: ```javascript // Node.js require: var Ajv = require('ajv'); // or ESM/TypeScript import import Ajv from 'ajv'; var ajv = new Ajv(); // options can be passed, e.g. {allErrors: true} var validate = ajv.compile(schema); var valid = validate(data); if (!valid) console.log(validate.errors); ``` or with less code ```javascript // ... var valid = ajv.validate(schema, data); if (!valid) console.log(ajv.errors); // ... ``` or ```javascript // ... var valid = ajv.addSchema(schema, 'mySchema') .validate('mySchema', data); if (!valid) console.log(ajv.errorsText()); // ... ``` See [API](#api) and [Options](#options) for more details. Ajv compiles schemas to functions and caches them in all cases (using schema serialized with [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) or a custom function as a key), so that the next time the same schema is used (not necessarily the same object instance) it won't be compiled again. The best performance is achieved when using compiled functions returned by `compile` or `getSchema` methods (there is no additional function call). __Please note__: every time a validation function or `ajv.validate` are called `errors` property is overwritten. You need to copy `errors` array reference to another variable if you want to use it later (e.g., in the callback). See [Validation errors](#validation-errors) __Note for TypeScript users__: `ajv` provides its own TypeScript declarations out of the box, so you don't need to install the deprecated `@types/ajv` module. ## Using in browser You can require Ajv directly from the code you browserify - in this case Ajv will be a part of your bundle. If you need to use Ajv in several bundles you can create a separate UMD bundle using `npm run bundle` script (thanks to [siddo420](https://github.com/siddo420)). Then you need to load Ajv in the browser: ```html <script src="ajv.min.js"></script> ``` This bundle can be used with different module systems; it creates global `Ajv` if no module system is found. The browser bundle is available on [cdnjs](https://cdnjs.com/libraries/ajv). Ajv is tested with these browsers: [![Sauce Test Status](https://saucelabs.com/browser-matrix/epoberezkin.svg)](https://saucelabs.com/u/epoberezkin) __Please note__: some frameworks, e.g. Dojo, may redefine global require in such way that is not compatible with CommonJS module format. In such case Ajv bundle has to be loaded before the framework and then you can use global Ajv (see issue [#234](https://github.com/ajv-validator/ajv/issues/234)). ### Ajv and Content Security Policies (CSP) If you're using Ajv to compile a schema (the typical use) in a browser document that is loaded with a Content Security Policy (CSP), that policy will require a `script-src` directive that includes the value `'unsafe-eval'`. :warning: NOTE, however, that `unsafe-eval` is NOT recommended in a secure CSP[[1]](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval), as it has the potential to open the document to cross-site scripting (XSS) attacks. In order to make use of Ajv without easing your CSP, you can [pre-compile a schema using the CLI](https://github.com/ajv-validator/ajv-cli#compile-schemas). This will transpile the schema JSON into a JavaScript file that exports a `validate` function that works simlarly to a schema compiled at runtime. Note that pre-compilation of schemas is performed using [ajv-pack](https://github.com/ajv-validator/ajv-pack) and there are [some limitations to the schema features it can compile](https://github.com/ajv-validator/ajv-pack#limitations). A successfully pre-compiled schema is equivalent to the same schema compiled at runtime. ## Command line interface CLI is available as a separate npm package [ajv-cli](https://github.com/ajv-validator/ajv-cli). It supports: - compiling JSON Schemas to test their validity - BETA: generating standalone module exporting a validation function to be used without Ajv (using [ajv-pack](https://github.com/ajv-validator/ajv-pack)) - migrate schemas to draft-07 (using [json-schema-migrate](https://github.com/epoberezkin/json-schema-migrate)) - validating data file(s) against JSON Schema - testing expected validity of data against JSON Schema - referenced schemas - custom meta-schemas - files in JSON, JSON5, YAML, and JavaScript format - all Ajv options - reporting changes in data after validation in [JSON-patch](https://tools.ietf.org/html/rfc6902) format ## Validation keywords Ajv supports all validation keywords from draft-07 of JSON Schema standard: - [type](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#type) - [for numbers](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-numbers) - maximum, minimum, exclusiveMaximum, exclusiveMinimum, multipleOf - [for strings](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-strings) - maxLength, minLength, pattern, format - [for arrays](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-arrays) - maxItems, minItems, uniqueItems, items, additionalItems, [contains](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#contains) - [for objects](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-objects) - maxProperties, minProperties, required, properties, patternProperties, additionalProperties, dependencies, [propertyNames](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#propertynames) - [for all types](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#keywords-for-all-types) - enum, [const](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#const) - [compound keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#compound-keywords) - not, oneOf, anyOf, allOf, [if/then/else](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#ifthenelse) With [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package Ajv also supports validation keywords from [JSON Schema extension proposals](https://github.com/json-schema/json-schema/wiki/v5-Proposals) for JSON Schema standard: - [patternRequired](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#patternrequired-proposed) - like `required` but with patterns that some property should match. - [formatMaximum, formatMinimum, formatExclusiveMaximum, formatExclusiveMinimum](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md#formatmaximum--formatminimum-and-exclusiveformatmaximum--exclusiveformatminimum-proposed) - setting limits for date, time, etc. See [JSON Schema validation keywords](https://github.com/ajv-validator/ajv/blob/master/KEYWORDS.md) for more details. ## Annotation keywords JSON Schema specification defines several annotation keywords that describe schema itself but do not perform any validation. - `title` and `description`: information about the data represented by that schema - `$comment` (NEW in draft-07): information for developers. With option `$comment` Ajv logs or passes the comment string to the user-supplied function. See [Options](#options). - `default`: a default value of the data instance, see [Assigning defaults](#assigning-defaults). - `examples` (NEW in draft-06): an array of data instances. Ajv does not check the validity of these instances against the schema. - `readOnly` and `writeOnly` (NEW in draft-07): marks data-instance as read-only or write-only in relation to the source of the data (database, api, etc.). - `contentEncoding`: [RFC 2045](https://tools.ietf.org/html/rfc2045#section-6.1 ), e.g., "base64". - `contentMediaType`: [RFC 2046](https://tools.ietf.org/html/rfc2046), e.g., "image/png". __Please note__: Ajv does not implement validation of the keywords `examples`, `contentEncoding` and `contentMediaType` but it reserves them. If you want to create a plugin that implements some of them, it should remove these keywords from the instance. ## Formats Ajv implements formats defined by JSON Schema specification and several other formats. It is recommended NOT to use "format" keyword implementations with untrusted data, as they use potentially unsafe regular expressions - see [ReDoS attack](#redos-attack). __Please note__: if you need to use "format" keyword to validate untrusted data, you MUST assess their suitability and safety for your validation scenarios. The following formats are implemented for string validation with "format" keyword: - _date_: full-date according to [RFC3339](http://tools.ietf.org/html/rfc3339#section-5.6). - _time_: time with optional time-zone. - _date-time_: date-time from the same source (time-zone is mandatory). `date`, `time` and `date-time` validate ranges in `full` mode and only regexp in `fast` mode (see [options](#options)). - _uri_: full URI. - _uri-reference_: URI reference, including full and relative URIs. - _uri-template_: URI template according to [RFC6570](https://tools.ietf.org/html/rfc6570) - _url_ (deprecated): [URL record](https://url.spec.whatwg.org/#concept-url). - _email_: email address. - _hostname_: host name according to [RFC1034](http://tools.ietf.org/html/rfc1034#section-3.5). - _ipv4_: IP address v4. - _ipv6_: IP address v6. - _regex_: tests whether a string is a valid regular expression by passing it to RegExp constructor. - _uuid_: Universally Unique IDentifier according to [RFC4122](http://tools.ietf.org/html/rfc4122). - _json-pointer_: JSON-pointer according to [RFC6901](https://tools.ietf.org/html/rfc6901). - _relative-json-pointer_: relative JSON-pointer according to [this draft](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00). __Please note__: JSON Schema draft-07 also defines formats `iri`, `iri-reference`, `idn-hostname` and `idn-email` for URLs, hostnames and emails with international characters. Ajv does not implement these formats. If you create Ajv plugin that implements them please make a PR to mention this plugin here. There are two modes of format validation: `fast` and `full`. This mode affects formats `date`, `time`, `date-time`, `uri`, `uri-reference`, and `email`. See [Options](#options) for details. You can add additional formats and replace any of the formats above using [addFormat](#api-addformat) method. The option `unknownFormats` allows changing the default behaviour when an unknown format is encountered. In this case Ajv can either fail schema compilation (default) or ignore it (default in versions before 5.0.0). You also can whitelist specific format(s) to be ignored. See [Options](#options) for details. You can find regular expressions used for format validation and the sources that were used in [formats.js](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js). ## <a name="ref"></a>Combining schemas with $ref You can structure your validation logic across multiple schema files and have schemas reference each other using `$ref` keyword. Example: ```javascript var schema = { "$id": "http://example.com/schemas/schema.json", "type": "object", "properties": { "foo": { "$ref": "defs.json#/definitions/int" }, "bar": { "$ref": "defs.json#/definitions/str" } } }; var defsSchema = { "$id": "http://example.com/schemas/defs.json", "definitions": { "int": { "type": "integer" }, "str": { "type": "string" } } }; ``` Now to compile your schema you can either pass all schemas to Ajv instance: ```javascript var ajv = new Ajv({schemas: [schema, defsSchema]}); var validate = ajv.getSchema('http://example.com/schemas/schema.json'); ``` or use `addSchema` method: ```javascript var ajv = new Ajv; var validate = ajv.addSchema(defsSchema) .compile(schema); ``` See [Options](#options) and [addSchema](#api) method. __Please note__: - `$ref` is resolved as the uri-reference using schema $id as the base URI (see the example). - References can be recursive (and mutually recursive) to implement the schemas for different data structures (such as linked lists, trees, graphs, etc.). - You don't have to host your schema files at the URIs that you use as schema $id. These URIs are only used to identify the schemas, and according to JSON Schema specification validators should not expect to be able to download the schemas from these URIs. - The actual location of the schema file in the file system is not used. - You can pass the identifier of the schema as the second parameter of `addSchema` method or as a property name in `schemas` option. This identifier can be used instead of (or in addition to) schema $id. - You cannot have the same $id (or the schema identifier) used for more than one schema - the exception will be thrown. - You can implement dynamic resolution of the referenced schemas using `compileAsync` method. In this way you can store schemas in any system (files, web, database, etc.) and reference them without explicitly adding to Ajv instance. See [Asynchronous schema compilation](#asynchronous-schema-compilation). ## $data reference With `$data` option you can use values from the validated data as the values for the schema keywords. See [proposal](https://github.com/json-schema-org/json-schema-spec/issues/51) for more information about how it works. `$data` reference is supported in the keywords: const, enum, format, maximum/minimum, exclusiveMaximum / exclusiveMinimum, maxLength / minLength, maxItems / minItems, maxProperties / minProperties, formatMaximum / formatMinimum, formatExclusiveMaximum / formatExclusiveMinimum, multipleOf, pattern, required, uniqueItems. The value of "$data" should be a [JSON-pointer](https://tools.ietf.org/html/rfc6901) to the data (the root is always the top level data object, even if the $data reference is inside a referenced subschema) or a [relative JSON-pointer](http://tools.ietf.org/html/draft-luff-relative-json-pointer-00) (it is relative to the current point in data; if the $data reference is inside a referenced subschema it cannot point to the data outside of the root level for this subschema). Examples. This schema requires that the value in property `smaller` is less or equal than the value in the property larger: ```javascript var ajv = new Ajv({$data: true}); var schema = { "properties": { "smaller": { "type": "number", "maximum": { "$data": "1/larger" } }, "larger": { "type": "number" } } }; var validData = { smaller: 5, larger: 7 }; ajv.validate(schema, validData); // true ``` This schema requires that the properties have the same format as their field names: ```javascript var schema = { "additionalProperties": { "type": "string", "format": { "$data": "0#" } } }; var validData = { 'date-time': '1963-06-19T08:30:06.283185Z', email: '[email protected]' } ``` `$data` reference is resolved safely - it won't throw even if some property is undefined. If `$data` resolves to `undefined` the validation succeeds (with the exclusion of `const` keyword). If `$data` resolves to incorrect type (e.g. not "number" for maximum keyword) the validation fails. ## $merge and $patch keywords With the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) you can use the keywords `$merge` and `$patch` that allow extending JSON Schemas with patches using formats [JSON Merge Patch (RFC 7396)](https://tools.ietf.org/html/rfc7396) and [JSON Patch (RFC 6902)](https://tools.ietf.org/html/rfc6902). To add keywords `$merge` and `$patch` to Ajv instance use this code: ```javascript require('ajv-merge-patch')(ajv); ``` Examples. Using `$merge`: ```json { "$merge": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": { "properties": { "q": { "type": "number" } } } } } ``` Using `$patch`: ```json { "$patch": { "source": { "type": "object", "properties": { "p": { "type": "string" } }, "additionalProperties": false }, "with": [ { "op": "add", "path": "/properties/q", "value": { "type": "number" } } ] } } ``` The schemas above are equivalent to this schema: ```json { "type": "object", "properties": { "p": { "type": "string" }, "q": { "type": "number" } }, "additionalProperties": false } ``` The properties `source` and `with` in the keywords `$merge` and `$patch` can use absolute or relative `$ref` to point to other schemas previously added to the Ajv instance or to the fragments of the current schema. See the package [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) for more information. ## Defining custom keywords The advantages of using custom keywords are: - allow creating validation scenarios that cannot be expressed using JSON Schema - simplify your schemas - help bringing a bigger part of the validation logic to your schemas - make your schemas more expressive, less verbose and closer to your application domain - implement custom data processors that modify your data (`modifying` option MUST be used in keyword definition) and/or create side effects while the data is being validated If a keyword is used only for side-effects and its validation result is pre-defined, use option `valid: true/false` in keyword definition to simplify both generated code (no error handling in case of `valid: true`) and your keyword functions (no need to return any validation result). The concerns you have to be aware of when extending JSON Schema standard with custom keywords are the portability and understanding of your schemas. You will have to support these custom keywords on other platforms and to properly document these keywords so that everybody can understand them in your schemas. You can define custom keywords with [addKeyword](#api-addkeyword) method. Keywords are defined on the `ajv` instance level - new instances will not have previously defined keywords. Ajv allows defining keywords with: - validation function - compilation function - macro function - inline compilation function that should return code (as string) that will be inlined in the currently compiled schema. Example. `range` and `exclusiveRange` keywords using compiled schema: ```javascript ajv.addKeyword('range', { type: 'number', compile: function (sch, parentSchema) { var min = sch[0]; var max = sch[1]; return parentSchema.exclusiveRange === true ? function (data) { return data > min && data < max; } : function (data) { return data >= min && data <= max; } } }); var schema = { "range": [2, 4], "exclusiveRange": true }; var validate = ajv.compile(schema); console.log(validate(2.01)); // true console.log(validate(3.99)); // true console.log(validate(2)); // false console.log(validate(4)); // false ``` Several custom keywords (typeof, instanceof, range and propertyNames) are defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package - they can be used for your schemas and as a starting point for your own custom keywords. See [Defining custom keywords](https://github.com/ajv-validator/ajv/blob/master/CUSTOM.md) for more details. ## Asynchronous schema compilation During asynchronous compilation remote references are loaded using supplied function. See `compileAsync` [method](#api-compileAsync) and `loadSchema` [option](#options). Example: ```javascript var ajv = new Ajv({ loadSchema: loadSchema }); ajv.compileAsync(schema).then(function (validate) { var valid = validate(data); // ... }); function loadSchema(uri) { return request.json(uri).then(function (res) { if (res.statusCode >= 400) throw new Error('Loading error: ' + res.statusCode); return res.body; }); } ``` __Please note__: [Option](#options) `missingRefs` should NOT be set to `"ignore"` or `"fail"` for asynchronous compilation to work. ## Asynchronous validation Example in Node.js REPL: https://tonicdev.com/esp/ajv-asynchronous-validation You can define custom formats and keywords that perform validation asynchronously by accessing database or some other service. You should add `async: true` in the keyword or format definition (see [addFormat](#api-addformat), [addKeyword](#api-addkeyword) and [Defining custom keywords](#defining-custom-keywords)). If your schema uses asynchronous formats/keywords or refers to some schema that contains them it should have `"$async": true` keyword so that Ajv can compile it correctly. If asynchronous format/keyword or reference to asynchronous schema is used in the schema without `$async` keyword Ajv will throw an exception during schema compilation. __Please note__: all asynchronous subschemas that are referenced from the current or other schemas should have `"$async": true` keyword as well, otherwise the schema compilation will fail. Validation function for an asynchronous custom format/keyword should return a promise that resolves with `true` or `false` (or rejects with `new Ajv.ValidationError(errors)` if you want to return custom errors from the keyword function). Ajv compiles asynchronous schemas to [es7 async functions](http://tc39.github.io/ecmascript-asyncawait/) that can optionally be transpiled with [nodent](https://github.com/MatAtBread/nodent). Async functions are supported in Node.js 7+ and all modern browsers. You can also supply any other transpiler as a function via `processCode` option. See [Options](#options). The compiled validation function has `$async: true` property (if the schema is asynchronous), so you can differentiate these functions if you are using both synchronous and asynchronous schemas. Validation result will be a promise that resolves with validated data or rejects with an exception `Ajv.ValidationError` that contains the array of validation errors in `errors` property. Example: ```javascript var ajv = new Ajv; // require('ajv-async')(ajv); ajv.addKeyword('idExists', { async: true, type: 'number', validate: checkIdExists }); function checkIdExists(schema, data) { return knex(schema.table) .select('id') .where('id', data) .then(function (rows) { return !!rows.length; // true if record is found }); } var schema = { "$async": true, "properties": { "userId": { "type": "integer", "idExists": { "table": "users" } }, "postId": { "type": "integer", "idExists": { "table": "posts" } } } }; var validate = ajv.compile(schema); validate({ userId: 1, postId: 19 }) .then(function (data) { console.log('Data is valid', data); // { userId: 1, postId: 19 } }) .catch(function (err) { if (!(err instanceof Ajv.ValidationError)) throw err; // data is invalid console.log('Validation errors:', err.errors); }); ``` ### Using transpilers with asynchronous validation functions. [ajv-async](https://github.com/ajv-validator/ajv-async) uses [nodent](https://github.com/MatAtBread/nodent) to transpile async functions. To use another transpiler you should separately install it (or load its bundle in the browser). #### Using nodent ```javascript var ajv = new Ajv; require('ajv-async')(ajv); // in the browser if you want to load ajv-async bundle separately you can: // window.ajvAsync(ajv); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` #### Using other transpilers ```javascript var ajv = new Ajv({ processCode: transpileFunc }); var validate = ajv.compile(schema); // transpiled es7 async function validate(data).then(successFunc).catch(errorFunc); ``` See [Options](#options). ## Security considerations JSON Schema, if properly used, can replace data sanitisation. It doesn't replace other API security considerations. It also introduces additional security aspects to consider. ##### Security contact To report a security vulnerability, please use the [Tidelift security contact](https://tidelift.com/security). Tidelift will coordinate the fix and disclosure. Please do NOT report security vulnerabilities via GitHub issues. ##### Untrusted schemas Ajv treats JSON schemas as trusted as your application code. This security model is based on the most common use case, when the schemas are static and bundled together with the application. If your schemas are received from untrusted sources (or generated from untrusted data) there are several scenarios you need to prevent: - compiling schemas can cause stack overflow (if they are too deep) - compiling schemas can be slow (e.g. [#557](https://github.com/ajv-validator/ajv/issues/557)) - validating certain data can be slow It is difficult to predict all the scenarios, but at the very least it may help to limit the size of untrusted schemas (e.g. limit JSON string length) and also the maximum schema object depth (that can be high for relatively small JSON strings). You also may want to mitigate slow regular expressions in `pattern` and `patternProperties` keywords. Regardless the measures you take, using untrusted schemas increases security risks. ##### Circular references in JavaScript objects Ajv does not support schemas and validated data that have circular references in objects. See [issue #802](https://github.com/ajv-validator/ajv/issues/802). An attempt to compile such schemas or validate such data would cause stack overflow (or will not complete in case of asynchronous validation). Depending on the parser you use, untrusted data can lead to circular references. ##### Security risks of trusted schemas Some keywords in JSON Schemas can lead to very slow validation for certain data. These keywords include (but may be not limited to): - `pattern` and `format` for large strings - in some cases using `maxLength` can help mitigate it, but certain regular expressions can lead to exponential validation time even with relatively short strings (see [ReDoS attack](#redos-attack)). - `patternProperties` for large property names - use `propertyNames` to mitigate, but some regular expressions can have exponential evaluation time as well. - `uniqueItems` for large non-scalar arrays - use `maxItems` to mitigate __Please note__: The suggestions above to prevent slow validation would only work if you do NOT use `allErrors: true` in production code (using it would continue validation after validation errors). You can validate your JSON schemas against [this meta-schema](https://github.com/ajv-validator/ajv/blob/master/lib/refs/json-schema-secure.json) to check that these recommendations are followed: ```javascript const isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json')); const schema1 = {format: 'email'}; isSchemaSecure(schema1); // false const schema2 = {format: 'email', maxLength: MAX_LENGTH}; isSchemaSecure(schema2); // true ``` __Please note__: following all these recommendation is not a guarantee that validation of untrusted data is safe - it can still lead to some undesirable results. ##### Content Security Policies (CSP) See [Ajv and Content Security Policies (CSP)](#ajv-and-content-security-policies-csp) ## ReDoS attack Certain regular expressions can lead to the exponential evaluation time even with relatively short strings. Please assess the regular expressions you use in the schemas on their vulnerability to this attack - see [safe-regex](https://github.com/substack/safe-regex), for example. __Please note__: some formats that Ajv implements use [regular expressions](https://github.com/ajv-validator/ajv/blob/master/lib/compile/formats.js) that can be vulnerable to ReDoS attack, so if you use Ajv to validate data from untrusted sources __it is strongly recommended__ to consider the following: - making assessment of "format" implementations in Ajv. - using `format: 'fast'` option that simplifies some of the regular expressions (although it does not guarantee that they are safe). - replacing format implementations provided by Ajv with your own implementations of "format" keyword that either uses different regular expressions or another approach to format validation. Please see [addFormat](#api-addformat) method. - disabling format validation by ignoring "format" keyword with option `format: false` Whatever mitigation you choose, please assume all formats provided by Ajv as potentially unsafe and make your own assessment of their suitability for your validation scenarios. ## Filtering data With [option `removeAdditional`](#options) (added by [andyscott](https://github.com/andyscott)) you can filter data during the validation. This option modifies original data. Example: ```javascript var ajv = new Ajv({ removeAdditional: true }); var schema = { "additionalProperties": false, "properties": { "foo": { "type": "number" }, "bar": { "additionalProperties": { "type": "number" }, "properties": { "baz": { "type": "string" } } } } } var data = { "foo": 0, "additional1": 1, // will be removed; `additionalProperties` == false "bar": { "baz": "abc", "additional2": 2 // will NOT be removed; `additionalProperties` != false }, } var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 0, "bar": { "baz": "abc", "additional2": 2 } ``` If `removeAdditional` option in the example above were `"all"` then both `additional1` and `additional2` properties would have been removed. If the option were `"failing"` then property `additional1` would have been removed regardless of its value and property `additional2` would have been removed only if its value were failing the schema in the inner `additionalProperties` (so in the example above it would have stayed because it passes the schema, but any non-number would have been removed). __Please note__: If you use `removeAdditional` option with `additionalProperties` keyword inside `anyOf`/`oneOf` keywords your validation can fail with this schema, for example: ```json { "type": "object", "oneOf": [ { "properties": { "foo": { "type": "string" } }, "required": [ "foo" ], "additionalProperties": false }, { "properties": { "bar": { "type": "integer" } }, "required": [ "bar" ], "additionalProperties": false } ] } ``` The intention of the schema above is to allow objects with either the string property "foo" or the integer property "bar", but not with both and not with any other properties. With the option `removeAdditional: true` the validation will pass for the object `{ "foo": "abc"}` but will fail for the object `{"bar": 1}`. It happens because while the first subschema in `oneOf` is validated, the property `bar` is removed because it is an additional property according to the standard (because it is not included in `properties` keyword in the same schema). While this behaviour is unexpected (issues [#129](https://github.com/ajv-validator/ajv/issues/129), [#134](https://github.com/ajv-validator/ajv/issues/134)), it is correct. To have the expected behaviour (both objects are allowed and additional properties are removed) the schema has to be refactored in this way: ```json { "type": "object", "properties": { "foo": { "type": "string" }, "bar": { "type": "integer" } }, "additionalProperties": false, "oneOf": [ { "required": [ "foo" ] }, { "required": [ "bar" ] } ] } ``` The schema above is also more efficient - it will compile into a faster function. ## Assigning defaults With [option `useDefaults`](#options) Ajv will assign values from `default` keyword in the schemas of `properties` and `items` (when it is the array of schemas) to the missing properties and items. With the option value `"empty"` properties and items equal to `null` or `""` (empty string) will be considered missing and assigned defaults. This option modifies original data. __Please note__: the default value is inserted in the generated validation code as a literal, so the value inserted in the data will be the deep clone of the default in the schema. Example 1 (`default` in `properties`): ```javascript var ajv = new Ajv({ useDefaults: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "string", "default": "baz" } }, "required": [ "foo", "bar" ] }; var data = { "foo": 1 }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": "baz" } ``` Example 2 (`default` in `items`): ```javascript var schema = { "type": "array", "items": [ { "type": "number" }, { "type": "string", "default": "foo" } ] } var data = [ 1 ]; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // [ 1, "foo" ] ``` `default` keywords in other cases are ignored: - not in `properties` or `items` subschemas - in schemas inside `anyOf`, `oneOf` and `not` (see [#42](https://github.com/ajv-validator/ajv/issues/42)) - in `if` subschema of `switch` keyword - in schemas generated by custom macro keywords The [`strictDefaults` option](#options) customizes Ajv's behavior for the defaults that Ajv ignores (`true` raises an error, and `"log"` outputs a warning). ## Coercing data types When you are validating user inputs all your data properties are usually strings. The option `coerceTypes` allows you to have your data types coerced to the types specified in your schema `type` keywords, both to pass the validation and to use the correctly typed data afterwards. This option modifies original data. __Please note__: if you pass a scalar value to the validating function its type will be coerced and it will pass the validation, but the value of the variable you pass won't be updated because scalars are passed by value. Example 1: ```javascript var ajv = new Ajv({ coerceTypes: true }); var schema = { "type": "object", "properties": { "foo": { "type": "number" }, "bar": { "type": "boolean" } }, "required": [ "foo", "bar" ] }; var data = { "foo": "1", "bar": "false" }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": 1, "bar": false } ``` Example 2 (array coercions): ```javascript var ajv = new Ajv({ coerceTypes: 'array' }); var schema = { "properties": { "foo": { "type": "array", "items": { "type": "number" } }, "bar": { "type": "boolean" } } }; var data = { "foo": "1", "bar": ["false"] }; var validate = ajv.compile(schema); console.log(validate(data)); // true console.log(data); // { "foo": [1], "bar": false } ``` The coercion rules, as you can see from the example, are different from JavaScript both to validate user input as expected and to have the coercion reversible (to correctly validate cases where different types are defined in subschemas of "anyOf" and other compound keywords). See [Coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md) for details. ## API ##### new Ajv(Object options) -&gt; Object Create Ajv instance. ##### .compile(Object schema) -&gt; Function&lt;Object data&gt; Generate validating function and cache the compiled schema for future use. Validating function returns a boolean value. This function has properties `errors` and `schema`. Errors encountered during the last validation are assigned to `errors` property (it is assigned `null` if there was no errors). `schema` property contains the reference to the original schema. The schema passed to this method will be validated against meta-schema unless `validateSchema` option is false. If schema is invalid, an error will be thrown. See [options](#options). ##### <a name="api-compileAsync"></a>.compileAsync(Object schema [, Boolean meta] [, Function callback]) -&gt; Promise Asynchronous version of `compile` method that loads missing remote schemas using asynchronous function in `options.loadSchema`. This function returns a Promise that resolves to a validation function. An optional callback passed to `compileAsync` will be called with 2 parameters: error (or null) and validating function. The returned promise will reject (and the callback will be called with an error) when: - missing schema can't be loaded (`loadSchema` returns a Promise that rejects). - a schema containing a missing reference is loaded, but the reference cannot be resolved. - schema (or some loaded/referenced schema) is invalid. The function compiles schema and loads the first missing schema (or meta-schema) until all missing schemas are loaded. You can asynchronously compile meta-schema by passing `true` as the second parameter. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### .validate(Object schema|String key|String ref, data) -&gt; Boolean Validate data using passed schema (it will be compiled and cached). Instead of the schema you can use the key that was previously passed to `addSchema`, the schema id if it was present in the schema or any previously resolved reference. Validation errors will be available in the `errors` property of Ajv instance (`null` if there were no errors). __Please note__: every time this method is called the errors are overwritten so you need to copy them to another variable if you want to use them later. If the schema is asynchronous (has `$async` keyword on the top level) this method returns a Promise. See [Asynchronous validation](#asynchronous-validation). ##### .addSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Add schema(s) to validator instance. This method does not compile schemas (but it still validates them). Because of that dependencies can be added in any order and circular dependencies are supported. It also prevents unnecessary compilation of schemas that are containers for other schemas but not used as a whole. Array of schemas can be passed (schemas should have ids), the second parameter will be ignored. Key can be passed that can be used to reference the schema and will be used as the schema id if there is no id inside the schema. If the key is not passed, the schema id will be used as the key. Once the schema is added, it (and all the references inside it) can be referenced in other schemas and used to validate data. Although `addSchema` does not compile schemas, explicit compilation is not required - the schema will be compiled when it is used first time. By default the schema is validated against meta-schema before it is added, and if the schema does not pass validation the exception is thrown. This behaviour is controlled by `validateSchema` option. __Please note__: Ajv uses the [method chaining syntax](https://en.wikipedia.org/wiki/Method_chaining) for all methods with the prefix `add*` and `remove*`. This allows you to do nice things like the following. ```javascript var validate = new Ajv().addSchema(schema).addFormat(name, regex).getSchema(uri); ``` ##### .addMetaSchema(Array&lt;Object&gt;|Object schema [, String key]) -&gt; Ajv Adds meta schema(s) that can be used to validate other schemas. That function should be used instead of `addSchema` because there may be instance options that would compile a meta schema incorrectly (at the moment it is `removeAdditional` option). There is no need to explicitly add draft-07 meta schema (http://json-schema.org/draft-07/schema) - it is added by default, unless option `meta` is set to `false`. You only need to use it if you have a changed meta-schema that you want to use to validate your schemas. See `validateSchema`. ##### <a name="api-validateschema"></a>.validateSchema(Object schema) -&gt; Boolean Validates schema. This method should be used to validate schemas rather than `validate` due to the inconsistency of `uri` format in JSON Schema standard. By default this method is called automatically when the schema is added, so you rarely need to use it directly. If schema doesn't have `$schema` property, it is validated against draft 6 meta-schema (option `meta` should not be false). If schema has `$schema` property, then the schema with this id (that should be previously added) is used to validate passed schema. Errors will be available at `ajv.errors`. ##### .getSchema(String key) -&gt; Function&lt;Object data&gt; Retrieve compiled schema previously added with `addSchema` by the key passed to `addSchema` or by its full reference (id). The returned validating function has `schema` property with the reference to the original schema. ##### .removeSchema([Object schema|String key|String ref|RegExp pattern]) -&gt; Ajv Remove added/cached schema. Even if schema is referenced by other schemas it can be safely removed as dependent schemas have local references. Schema can be removed using: - key passed to `addSchema` - it's full reference (id) - RegExp that should match schema id or key (meta-schemas won't be removed) - actual schema object that will be stable-stringified to remove schema from cache If no parameter is passed all schemas but meta-schemas will be removed and the cache will be cleared. ##### <a name="api-addformat"></a>.addFormat(String name, String|RegExp|Function|Object format) -&gt; Ajv Add custom format to validate strings or numbers. It can also be used to replace pre-defined formats for Ajv instance. Strings are converted to RegExp. Function should return validation result as `true` or `false`. If object is passed it should have properties `validate`, `compare` and `async`: - _validate_: a string, RegExp or a function as described above. - _compare_: an optional comparison function that accepts two strings and compares them according to the format meaning. This function is used with keywords `formatMaximum`/`formatMinimum` (defined in [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) package). It should return `1` if the first value is bigger than the second value, `-1` if it is smaller and `0` if it is equal. - _async_: an optional `true` value if `validate` is an asynchronous function; in this case it should return a promise that resolves with a value `true` or `false`. - _type_: an optional type of data that the format applies to. It can be `"string"` (default) or `"number"` (see https://github.com/ajv-validator/ajv/issues/291#issuecomment-259923858). If the type of data is different, the validation will pass. Custom formats can be also added via `formats` option. ##### <a name="api-addkeyword"></a>.addKeyword(String keyword, Object definition) -&gt; Ajv Add custom validation keyword to Ajv instance. Keyword should be different from all standard JSON Schema keywords and different from previously defined keywords. There is no way to redefine keywords or to remove keyword definition from the instance. Keyword must start with a letter, `_` or `$`, and may continue with letters, numbers, `_`, `$`, or `-`. It is recommended to use an application-specific prefix for keywords to avoid current and future name collisions. Example Keywords: - `"xyz-example"`: valid, and uses prefix for the xyz project to avoid name collisions. - `"example"`: valid, but not recommended as it could collide with future versions of JSON Schema etc. - `"3-example"`: invalid as numbers are not allowed to be the first character in a keyword Keyword definition is an object with the following properties: - _type_: optional string or array of strings with data type(s) that the keyword applies to. If not present, the keyword will apply to all types. - _validate_: validating function - _compile_: compiling function - _macro_: macro function - _inline_: compiling function that returns code (as string) - _schema_: an optional `false` value used with "validate" keyword to not pass schema - _metaSchema_: an optional meta-schema for keyword schema - _dependencies_: an optional list of properties that must be present in the parent schema - it will be checked during schema compilation - _modifying_: `true` MUST be passed if keyword modifies data - _statements_: `true` can be passed in case inline keyword generates statements (as opposed to expression) - _valid_: pass `true`/`false` to pre-define validation result, the result returned from validation function will be ignored. This option cannot be used with macro keywords. - _$data_: an optional `true` value to support [$data reference](#data-reference) as the value of custom keyword. The reference will be resolved at validation time. If the keyword has meta-schema it would be extended to allow $data and it will be used to validate the resolved value. Supporting $data reference requires that keyword has validating function (as the only option or in addition to compile, macro or inline function). - _async_: an optional `true` value if the validation function is asynchronous (whether it is compiled or passed in _validate_ property); in this case it should return a promise that resolves with a value `true` or `false`. This option is ignored in case of "macro" and "inline" keywords. - _errors_: an optional boolean or string `"full"` indicating whether keyword returns errors. If this property is not set Ajv will determine if the errors were set in case of failed validation. _compile_, _macro_ and _inline_ are mutually exclusive, only one should be used at a time. _validate_ can be used separately or in addition to them to support $data reference. __Please note__: If the keyword is validating data type that is different from the type(s) in its definition, the validation function will not be called (and expanded macro will not be used), so there is no need to check for data type inside validation function or inside schema returned by macro function (unless you want to enforce a specific type and for some reason do not want to use a separate `type` keyword for that). In the same way as standard keywords work, if the keyword does not apply to the data type being validated, the validation of this keyword will succeed. See [Defining custom keywords](#defining-custom-keywords) for more details. ##### .getKeyword(String keyword) -&gt; Object|Boolean Returns custom keyword definition, `true` for pre-defined keywords and `false` if the keyword is unknown. ##### .removeKeyword(String keyword) -&gt; Ajv Removes custom or pre-defined keyword so you can redefine them. While this method can be used to extend pre-defined keywords, it can also be used to completely change their meaning - it may lead to unexpected results. __Please note__: schemas compiled before the keyword is removed will continue to work without changes. To recompile schemas use `removeSchema` method and compile them again. ##### .errorsText([Array&lt;Object&gt; errors [, Object options]]) -&gt; String Returns the text with all errors in a String. Options can have properties `separator` (string used to separate errors, ", " by default) and `dataVar` (the variable name that dataPaths are prefixed with, "data" by default). ## Options Defaults: ```javascript { // validation and reporting options: $data: false, allErrors: false, verbose: false, $comment: false, // NEW in Ajv version 6.0 jsonPointers: false, uniqueItems: true, unicode: true, nullable: false, format: 'fast', formats: {}, unknownFormats: true, schemas: {}, logger: undefined, // referenced schema options: schemaId: '$id', missingRefs: true, extendRefs: 'ignore', // recommended 'fail' loadSchema: undefined, // function(uri: string): Promise {} // options to modify validated data: removeAdditional: false, useDefaults: false, coerceTypes: false, // strict mode options strictDefaults: false, strictKeywords: false, strictNumbers: false, // asynchronous validation options: transpile: undefined, // requires ajv-async package // advanced options: meta: true, validateSchema: true, addUsedSchema: true, inlineRefs: true, passContext: false, loopRequired: Infinity, ownProperties: false, multipleOfPrecision: false, errorDataPath: 'object', // deprecated messages: true, sourceCode: false, processCode: undefined, // function (str: string, schema: object): string {} cache: new Cache, serialize: undefined } ``` ##### Validation and reporting options - _$data_: support [$data references](#data-reference). Draft 6 meta-schema that is added by default will be extended to allow them. If you want to use another meta-schema you need to use $dataMetaSchema method to add support for $data reference. See [API](#api). - _allErrors_: check all rules collecting all errors. Default is to return after the first error. - _verbose_: include the reference to the part of the schema (`schema` and `parentSchema`) and validated data in errors (false by default). - _$comment_ (NEW in Ajv version 6.0): log or pass the value of `$comment` keyword to a function. Option values: - `false` (default): ignore $comment keyword. - `true`: log the keyword value to console. - function: pass the keyword value, its schema path and root schema to the specified function - _jsonPointers_: set `dataPath` property of errors using [JSON Pointers](https://tools.ietf.org/html/rfc6901) instead of JavaScript property access notation. - _uniqueItems_: validate `uniqueItems` keyword (true by default). - _unicode_: calculate correct length of strings with unicode pairs (true by default). Pass `false` to use `.length` of strings that is faster, but gives "incorrect" lengths of strings with unicode pairs - each unicode pair is counted as two characters. - _nullable_: support keyword "nullable" from [Open API 3 specification](https://swagger.io/docs/specification/data-models/data-types/). - _format_: formats validation mode. Option values: - `"fast"` (default) - simplified and fast validation (see [Formats](#formats) for details of which formats are available and affected by this option). - `"full"` - more restrictive and slow validation. E.g., 25:00:00 and 2015/14/33 will be invalid time and date in 'full' mode but it will be valid in 'fast' mode. - `false` - ignore all format keywords. - _formats_: an object with custom formats. Keys and values will be passed to `addFormat` method. - _keywords_: an object with custom keywords. Keys and values will be passed to `addKeyword` method. - _unknownFormats_: handling of unknown formats. Option values: - `true` (default) - if an unknown format is encountered the exception is thrown during schema compilation. If `format` keyword value is [$data reference](#data-reference) and it is unknown the validation will fail. - `[String]` - an array of unknown format names that will be ignored. This option can be used to allow usage of third party schemas with format(s) for which you don't have definitions, but still fail if another unknown format is used. If `format` keyword value is [$data reference](#data-reference) and it is not in this array the validation will fail. - `"ignore"` - to log warning during schema compilation and always pass validation (the default behaviour in versions before 5.0.0). This option is not recommended, as it allows to mistype format name and it won't be validated without any error message. This behaviour is required by JSON Schema specification. - _schemas_: an array or object of schemas that will be added to the instance. In case you pass the array the schemas must have IDs in them. When the object is passed the method `addSchema(value, key)` will be called for each schema in this object. - _logger_: sets the logging method. Default is the global `console` object that should have methods `log`, `warn` and `error`. See [Error logging](#error-logging). Option values: - custom logger - it should have methods `log`, `warn` and `error`. If any of these methods is missing an exception will be thrown. - `false` - logging is disabled. ##### Referenced schema options - _schemaId_: this option defines which keywords are used as schema URI. Option value: - `"$id"` (default) - only use `$id` keyword as schema URI (as specified in JSON Schema draft-06/07), ignore `id` keyword (if it is present a warning will be logged). - `"id"` - only use `id` keyword as schema URI (as specified in JSON Schema draft-04), ignore `$id` keyword (if it is present a warning will be logged). - `"auto"` - use both `$id` and `id` keywords as schema URI. If both are present (in the same schema object) and different the exception will be thrown during schema compilation. - _missingRefs_: handling of missing referenced schemas. Option values: - `true` (default) - if the reference cannot be resolved during compilation the exception is thrown. The thrown error has properties `missingRef` (with hash fragment) and `missingSchema` (without it). Both properties are resolved relative to the current base id (usually schema id, unless it was substituted). - `"ignore"` - to log error during compilation and always pass validation. - `"fail"` - to log error and successfully compile schema but fail validation if this rule is checked. - _extendRefs_: validation of other keywords when `$ref` is present in the schema. Option values: - `"ignore"` (default) - when `$ref` is used other keywords are ignored (as per [JSON Reference](https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3) standard). A warning will be logged during the schema compilation. - `"fail"` (recommended) - if other validation keywords are used together with `$ref` the exception will be thrown when the schema is compiled. This option is recommended to make sure schema has no keywords that are ignored, which can be confusing. - `true` - validate all keywords in the schemas with `$ref` (the default behaviour in versions before 5.0.0). - _loadSchema_: asynchronous function that will be used to load remote schemas when `compileAsync` [method](#api-compileAsync) is used and some reference is missing (option `missingRefs` should NOT be 'fail' or 'ignore'). This function should accept remote schema uri as a parameter and return a Promise that resolves to a schema. See example in [Asynchronous compilation](#asynchronous-schema-compilation). ##### Options to modify validated data - _removeAdditional_: remove additional properties - see example in [Filtering data](#filtering-data). This option is not used if schema is added with `addMetaSchema` method. Option values: - `false` (default) - not to remove additional properties - `"all"` - all additional properties are removed, regardless of `additionalProperties` keyword in schema (and no validation is made for them). - `true` - only additional properties with `additionalProperties` keyword equal to `false` are removed. - `"failing"` - additional properties that fail schema validation will be removed (where `additionalProperties` keyword is `false` or schema). - _useDefaults_: replace missing or undefined properties and items with the values from corresponding `default` keywords. Default behaviour is to ignore `default` keywords. This option is not used if schema is added with `addMetaSchema` method. See examples in [Assigning defaults](#assigning-defaults). Option values: - `false` (default) - do not use defaults - `true` - insert defaults by value (object literal is used). - `"empty"` - in addition to missing or undefined, use defaults for properties and items that are equal to `null` or `""` (an empty string). - `"shared"` (deprecated) - insert defaults by reference. If the default is an object, it will be shared by all instances of validated data. If you modify the inserted default in the validated data, it will be modified in the schema as well. - _coerceTypes_: change data type of data to match `type` keyword. See the example in [Coercing data types](#coercing-data-types) and [coercion rules](https://github.com/ajv-validator/ajv/blob/master/COERCION.md). Option values: - `false` (default) - no type coercion. - `true` - coerce scalar data types. - `"array"` - in addition to coercions between scalar types, coerce scalar data to an array with one element and vice versa (as required by the schema). ##### Strict mode options - _strictDefaults_: report ignored `default` keywords in schemas. Option values: - `false` (default) - ignored defaults are not reported - `true` - if an ignored default is present, throw an error - `"log"` - if an ignored default is present, log warning - _strictKeywords_: report unknown keywords in schemas. Option values: - `false` (default) - unknown keywords are not reported - `true` - if an unknown keyword is present, throw an error - `"log"` - if an unknown keyword is present, log warning - _strictNumbers_: validate numbers strictly, failing validation for NaN and Infinity. Option values: - `false` (default) - NaN or Infinity will pass validation for numeric types - `true` - NaN or Infinity will not pass validation for numeric types ##### Asynchronous validation options - _transpile_: Requires [ajv-async](https://github.com/ajv-validator/ajv-async) package. It determines whether Ajv transpiles compiled asynchronous validation function. Option values: - `undefined` (default) - transpile with [nodent](https://github.com/MatAtBread/nodent) if async functions are not supported. - `true` - always transpile with nodent. - `false` - do not transpile; if async functions are not supported an exception will be thrown. ##### Advanced options - _meta_: add [meta-schema](http://json-schema.org/documentation.html) so it can be used by other schemas (true by default). If an object is passed, it will be used as the default meta-schema for schemas that have no `$schema` keyword. This default meta-schema MUST have `$schema` keyword. - _validateSchema_: validate added/compiled schemas against meta-schema (true by default). `$schema` property in the schema can be http://json-schema.org/draft-07/schema or absent (draft-07 meta-schema will be used) or can be a reference to the schema previously added with `addMetaSchema` method. Option values: - `true` (default) - if the validation fails, throw the exception. - `"log"` - if the validation fails, log error. - `false` - skip schema validation. - _addUsedSchema_: by default methods `compile` and `validate` add schemas to the instance if they have `$id` (or `id`) property that doesn't start with "#". If `$id` is present and it is not unique the exception will be thrown. Set this option to `false` to skip adding schemas to the instance and the `$id` uniqueness check when these methods are used. This option does not affect `addSchema` method. - _inlineRefs_: Affects compilation of referenced schemas. Option values: - `true` (default) - the referenced schemas that don't have refs in them are inlined, regardless of their size - that substantially improves performance at the cost of the bigger size of compiled schema functions. - `false` - to not inline referenced schemas (they will be compiled as separate functions). - integer number - to limit the maximum number of keywords of the schema that will be inlined. - _passContext_: pass validation context to custom keyword functions. If this option is `true` and you pass some context to the compiled validation function with `validate.call(context, data)`, the `context` will be available as `this` in your custom keywords. By default `this` is Ajv instance. - _loopRequired_: by default `required` keyword is compiled into a single expression (or a sequence of statements in `allErrors` mode). In case of a very large number of properties in this keyword it may result in a very big validation function. Pass integer to set the number of properties above which `required` keyword will be validated in a loop - smaller validation function size but also worse performance. - _ownProperties_: by default Ajv iterates over all enumerable object properties; when this option is `true` only own enumerable object properties (i.e. found directly on the object rather than on its prototype) are iterated. Contributed by @mbroadst. - _multipleOfPrecision_: by default `multipleOf` keyword is validated by comparing the result of division with parseInt() of that result. It works for dividers that are bigger than 1. For small dividers such as 0.01 the result of the division is usually not integer (even when it should be integer, see issue [#84](https://github.com/ajv-validator/ajv/issues/84)). If you need to use fractional dividers set this option to some positive integer N to have `multipleOf` validated using this formula: `Math.abs(Math.round(division) - division) < 1e-N` (it is slower but allows for float arithmetics deviations). - _errorDataPath_ (deprecated): set `dataPath` to point to 'object' (default) or to 'property' when validating keywords `required`, `additionalProperties` and `dependencies`. - _messages_: Include human-readable messages in errors. `true` by default. `false` can be passed when custom messages are used (e.g. with [ajv-i18n](https://github.com/ajv-validator/ajv-i18n)). - _sourceCode_: add `sourceCode` property to validating function (for debugging; this code can be different from the result of toString call). - _processCode_: an optional function to process generated code before it is passed to Function constructor. It can be used to either beautify (the validating function is generated without line-breaks) or to transpile code. Starting from version 5.0.0 this option replaced options: - `beautify` that formatted the generated function using [js-beautify](https://github.com/beautify-web/js-beautify). If you want to beautify the generated code pass a function calling `require('js-beautify').js_beautify` as `processCode: code => js_beautify(code)`. - `transpile` that transpiled asynchronous validation function. You can still use `transpile` option with [ajv-async](https://github.com/ajv-validator/ajv-async) package. See [Asynchronous validation](#asynchronous-validation) for more information. - _cache_: an optional instance of cache to store compiled schemas using stable-stringified schema as a key. For example, set-associative cache [sacjs](https://github.com/epoberezkin/sacjs) can be used. If not passed then a simple hash is used which is good enough for the common use case (a limited number of statically defined schemas). Cache should have methods `put(key, value)`, `get(key)`, `del(key)` and `clear()`. - _serialize_: an optional function to serialize schema to cache key. Pass `false` to use schema itself as a key (e.g., if WeakMap used as a cache). By default [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used. ## Validation errors In case of validation failure, Ajv assigns the array of errors to `errors` property of validation function (or to `errors` property of Ajv instance when `validate` or `validateSchema` methods were called). In case of [asynchronous validation](#asynchronous-validation), the returned promise is rejected with exception `Ajv.ValidationError` that has `errors` property. ### Error objects Each error is an object with the following properties: - _keyword_: validation keyword. - _dataPath_: the path to the part of the data that was validated. By default `dataPath` uses JavaScript property access notation (e.g., `".prop[1].subProp"`). When the option `jsonPointers` is true (see [Options](#options)) `dataPath` will be set using JSON pointer standard (e.g., `"/prop/1/subProp"`). - _schemaPath_: the path (JSON-pointer as a URI fragment) to the schema of the keyword that failed validation. - _params_: the object with the additional information about error that can be used to create custom error messages (e.g., using [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) package). See below for parameters set by all keywords. - _message_: the standard error message (can be excluded with option `messages` set to false). - _schema_: the schema of the keyword (added with `verbose` option). - _parentSchema_: the schema containing the keyword (added with `verbose` option) - _data_: the data validated by the keyword (added with `verbose` option). __Please note__: `propertyNames` keyword schema validation errors have an additional property `propertyName`, `dataPath` points to the object. After schema validation for each property name, if it is invalid an additional error is added with the property `keyword` equal to `"propertyNames"`. ### Error parameters Properties of `params` object in errors depend on the keyword that failed validation. - `maxItems`, `minItems`, `maxLength`, `minLength`, `maxProperties`, `minProperties` - property `limit` (number, the schema of the keyword). - `additionalItems` - property `limit` (the maximum number of allowed items in case when `items` keyword is an array of schemas and `additionalItems` is false). - `additionalProperties` - property `additionalProperty` (the property not used in `properties` and `patternProperties` keywords). - `dependencies` - properties: - `property` (dependent property), - `missingProperty` (required missing dependency - only the first one is reported currently) - `deps` (required dependencies, comma separated list as a string), - `depsCount` (the number of required dependencies). - `format` - property `format` (the schema of the keyword). - `maximum`, `minimum` - properties: - `limit` (number, the schema of the keyword), - `exclusive` (boolean, the schema of `exclusiveMaximum` or `exclusiveMinimum`), - `comparison` (string, comparison operation to compare the data to the limit, with the data on the left and the limit on the right; can be "<", "<=", ">", ">=") - `multipleOf` - property `multipleOf` (the schema of the keyword) - `pattern` - property `pattern` (the schema of the keyword) - `required` - property `missingProperty` (required property that is missing). - `propertyNames` - property `propertyName` (an invalid property name). - `patternRequired` (in ajv-keywords) - property `missingPattern` (required pattern that did not match any property). - `type` - property `type` (required type(s), a string, can be a comma-separated list) - `uniqueItems` - properties `i` and `j` (indices of duplicate items). - `const` - property `allowedValue` pointing to the value (the schema of the keyword). - `enum` - property `allowedValues` pointing to the array of values (the schema of the keyword). - `$ref` - property `ref` with the referenced schema URI. - `oneOf` - property `passingSchemas` (array of indices of passing schemas, null if no schema passes). - custom keywords (in case keyword definition doesn't create errors) - property `keyword` (the keyword name). ### Error logging Using the `logger` option when initiallizing Ajv will allow you to define custom logging. Here you can build upon the exisiting logging. The use of other logging packages is supported as long as the package or its associated wrapper exposes the required methods. If any of the required methods are missing an exception will be thrown. - **Required Methods**: `log`, `warn`, `error` ```javascript var otherLogger = new OtherLogger(); var ajv = new Ajv({ logger: { log: console.log.bind(console), warn: function warn() { otherLogger.logWarn.apply(otherLogger, arguments); }, error: function error() { otherLogger.logError.apply(otherLogger, arguments); console.error.apply(console, arguments); } } }); ``` ## Plugins Ajv can be extended with plugins that add custom keywords, formats or functions to process generated code. When such plugin is published as npm package it is recommended that it follows these conventions: - it exports a function - this function accepts ajv instance as the first parameter and returns the same instance to allow chaining - this function can accept an optional configuration as the second parameter If you have published a useful plugin please submit a PR to add it to the next section. ## Related packages - [ajv-async](https://github.com/ajv-validator/ajv-async) - plugin to configure async validation mode - [ajv-bsontype](https://github.com/BoLaMN/ajv-bsontype) - plugin to validate mongodb's bsonType formats - [ajv-cli](https://github.com/jessedc/ajv-cli) - command line interface - [ajv-errors](https://github.com/ajv-validator/ajv-errors) - plugin for custom error messages - [ajv-i18n](https://github.com/ajv-validator/ajv-i18n) - internationalised error messages - [ajv-istanbul](https://github.com/ajv-validator/ajv-istanbul) - plugin to instrument generated validation code to measure test coverage of your schemas - [ajv-keywords](https://github.com/ajv-validator/ajv-keywords) - plugin with custom validation keywords (select, typeof, etc.) - [ajv-merge-patch](https://github.com/ajv-validator/ajv-merge-patch) - plugin with keywords $merge and $patch - [ajv-pack](https://github.com/ajv-validator/ajv-pack) - produces a compact module exporting validation functions - [ajv-formats-draft2019](https://github.com/luzlab/ajv-formats-draft2019) - format validators for draft2019 that aren't already included in ajv (ie. `idn-hostname`, `idn-email`, `iri`, `iri-reference` and `duration`). ## Some packages using Ajv - [webpack](https://github.com/webpack/webpack) - a module bundler. Its main purpose is to bundle JavaScript files for usage in a browser - [jsonscript-js](https://github.com/JSONScript/jsonscript-js) - the interpreter for [JSONScript](http://www.jsonscript.org) - scripted processing of existing endpoints and services - [osprey-method-handler](https://github.com/mulesoft-labs/osprey-method-handler) - Express middleware for validating requests and responses based on a RAML method object, used in [osprey](https://github.com/mulesoft/osprey) - validating API proxy generated from a RAML definition - [har-validator](https://github.com/ahmadnassri/har-validator) - HTTP Archive (HAR) validator - [jsoneditor](https://github.com/josdejong/jsoneditor) - a web-based tool to view, edit, format, and validate JSON http://jsoneditoronline.org - [JSON Schema Lint](https://github.com/nickcmaynard/jsonschemalint) - a web tool to validate JSON/YAML document against a single JSON Schema http://jsonschemalint.com - [objection](https://github.com/vincit/objection.js) - SQL-friendly ORM for Node.js - [table](https://github.com/gajus/table) - formats data into a string table - [ripple-lib](https://github.com/ripple/ripple-lib) - a JavaScript API for interacting with [Ripple](https://ripple.com) in Node.js and the browser - [restbase](https://github.com/wikimedia/restbase) - distributed storage with REST API & dispatcher for backend services built to provide a low-latency & high-throughput API for Wikipedia / Wikimedia content - [hippie-swagger](https://github.com/CacheControl/hippie-swagger) - [Hippie](https://github.com/vesln/hippie) wrapper that provides end to end API testing with swagger validation - [react-form-controlled](https://github.com/seeden/react-form-controlled) - React controlled form components with validation - [rabbitmq-schema](https://github.com/tjmehta/rabbitmq-schema) - a schema definition module for RabbitMQ graphs and messages - [@query/schema](https://www.npmjs.com/package/@query/schema) - stream filtering with a URI-safe query syntax parsing to JSON Schema - [chai-ajv-json-schema](https://github.com/peon374/chai-ajv-json-schema) - chai plugin to us JSON Schema with expect in mocha tests - [grunt-jsonschema-ajv](https://github.com/SignpostMarv/grunt-jsonschema-ajv) - Grunt plugin for validating files against JSON Schema - [extract-text-webpack-plugin](https://github.com/webpack-contrib/extract-text-webpack-plugin) - extract text from bundle into a file - [electron-builder](https://github.com/electron-userland/electron-builder) - a solution to package and build a ready for distribution Electron app - [addons-linter](https://github.com/mozilla/addons-linter) - Mozilla Add-ons Linter - [gh-pages-generator](https://github.com/epoberezkin/gh-pages-generator) - multi-page site generator converting markdown files to GitHub pages - [ESLint](https://github.com/eslint/eslint) - the pluggable linting utility for JavaScript and JSX ## Tests ``` npm install git submodule update --init npm test ``` ## Contributing All validation functions are generated using doT templates in [dot](https://github.com/ajv-validator/ajv/tree/master/lib/dot) folder. Templates are precompiled so doT is not a run-time dependency. `npm run build` - compiles templates to [dotjs](https://github.com/ajv-validator/ajv/tree/master/lib/dotjs) folder. `npm run watch` - automatically compiles templates when files in dot folder change Please see [Contributing guidelines](https://github.com/ajv-validator/ajv/blob/master/CONTRIBUTING.md) ## Changes history See https://github.com/ajv-validator/ajv/releases __Please note__: [Changes in version 6.0.0](https://github.com/ajv-validator/ajv/releases/tag/v6.0.0). [Version 5.0.0](https://github.com/ajv-validator/ajv/releases/tag/5.0.0). [Version 4.0.0](https://github.com/ajv-validator/ajv/releases/tag/4.0.0). [Version 3.0.0](https://github.com/ajv-validator/ajv/releases/tag/3.0.0). [Version 2.0.0](https://github.com/ajv-validator/ajv/releases/tag/2.0.0). ## Code of conduct Please review and follow the [Code of conduct](https://github.com/ajv-validator/ajv/blob/master/CODE_OF_CONDUCT.md). Please report any unacceptable behaviour to [email protected] - it will be reviewed by the project team. ## Open-source software support Ajv is a part of [Tidelift subscription](https://tidelift.com/subscription/pkg/npm-ajv?utm_source=npm-ajv&utm_medium=referral&utm_campaign=readme) - it provides a centralised support to open-source software users, in addition to the support provided by software maintainers. ## License [MIT](https://github.com/ajv-validator/ajv/blob/master/LICENSE)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/README.md
README.md
'use strict'; var glob = require('glob') , fs = require('fs') , path = require('path') , doT = require('dot') , beautify = require('js-beautify').js_beautify; var defsRootPath = process.argv[2] || path.join(__dirname, '../lib'); var defs = {}; var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath }); defFiles.forEach(function (f) { var name = path.basename(f, '.def'); defs[name] = fs.readFileSync(path.join(defsRootPath, f)); }); var filesRootPath = process.argv[3] || path.join(__dirname, '../lib'); var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath }); var dotjsPath = path.join(filesRootPath, './dotjs'); try { fs.mkdirSync(dotjsPath); } catch(e) {} console.log('\n\nCompiling:'); var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/; var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g; var ISTANBUL = /'(istanbul[^']+)';/g; var ERROR_KEYWORD = /\$errorKeyword/g; var ERROR_KEYWORD_OR = /\$errorKeyword\s+\|\|/g; var VARS = [ '$errs', '$valid', '$lvl', '$data', '$dataLvl', '$errorKeyword', '$closingBraces', '$schemaPath', '$validate' ]; files.forEach(function (f) { var keyword = path.basename(f, '.jst'); var targetPath = path.join(dotjsPath, keyword + '.js'); var template = fs.readFileSync(path.join(filesRootPath, f)); var code = doT.compile(template, defs); code = code.toString() .replace(OUT_EMPTY_STRING, '') .replace(FUNCTION_NAME, 'function generate_' + keyword + '(it, $keyword, $ruleType) {') .replace(ISTANBUL, '/* $1 */'); removeAlwaysFalsyInOr(); VARS.forEach(removeUnusedVar); code = "'use strict';\nmodule.exports = " + code; code = beautify(code, { indent_size: 2 }) + '\n'; fs.writeFileSync(targetPath, code); console.log('compiled', keyword); function removeUnusedVar(v) { v = v.replace(/\$/g, '\\$$'); var regexp = new RegExp(v + '[^A-Za-z0-9_$]', 'g'); var count = occurrences(regexp); if (count == 1) { regexp = new RegExp('var\\s+' + v + '\\s*=[^;]+;|var\\s+' + v + ';'); code = code.replace(regexp, ''); } } function removeAlwaysFalsyInOr() { var countUsed = occurrences(ERROR_KEYWORD); var countOr = occurrences(ERROR_KEYWORD_OR); if (countUsed == countOr + 1) code = code.replace(ERROR_KEYWORD_OR, ''); } function occurrences(regexp) { return (code.match(regexp) || []).length; } });
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/scripts/compile-dots.js
compile-dots.js
'use strict'; var compileSchema = require('ajv/lib/compile') , resolve = require('ajv/lib/compile/resolve') , Cache = require('ajv/lib/cache') , SchemaObject = require('ajv/lib/compile/schema_obj') , stableStringify = require('fast-json-stable-stringify') , formats = require('ajv/lib/compile/formats') , rules = require('ajv/lib/compile/rules') , $dataMetaSchema = require('ajv/lib/data') , util = require('ajv/lib/compile/util'); module.exports = Ajv; Ajv.prototype.validate = validate; Ajv.prototype.compile = compile; Ajv.prototype.addSchema = addSchema; Ajv.prototype.addMetaSchema = addMetaSchema; Ajv.prototype.validateSchema = validateSchema; Ajv.prototype.getSchema = getSchema; Ajv.prototype.removeSchema = removeSchema; Ajv.prototype.addFormat = addFormat; Ajv.prototype.errorsText = errorsText; Ajv.prototype._addSchema = _addSchema; Ajv.prototype._compile = _compile; Ajv.prototype.compileAsync = require('ajv/lib/compile/async'); var customKeyword = require('ajv/lib/keyword'); Ajv.prototype.addKeyword = customKeyword.add; Ajv.prototype.getKeyword = customKeyword.get; Ajv.prototype.removeKeyword = customKeyword.remove; Ajv.prototype.validateKeyword = customKeyword.validate; var errorClasses = require('ajv/lib/compile/error_classes'); Ajv.ValidationError = errorClasses.Validation; Ajv.MissingRefError = errorClasses.MissingRef; Ajv.$dataMetaSchema = $dataMetaSchema; var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema'; var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ]; var META_SUPPORT_DATA = ['/properties']; /** * Creates validator instance. * Usage: `Ajv(opts)` * @param {Object} opts optional options * @return {Object} ajv instance */ function Ajv(opts) { if (!(this instanceof Ajv)) return new Ajv(opts); opts = this._opts = util.copy(opts) || {}; setLogger(this); this._schemas = {}; this._refs = {}; this._fragments = {}; this._formats = formats(opts.format); this._cache = opts.cache || new Cache; this._loadingSchemas = {}; this._compilations = []; this.RULES = rules(); this._getId = chooseGetId(opts); opts.loopRequired = opts.loopRequired || Infinity; if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true; if (opts.serialize === undefined) opts.serialize = stableStringify; this._metaOpts = getMetaSchemaOptions(this); if (opts.formats) addInitialFormats(this); if (opts.keywords) addInitialKeywords(this); addDefaultMetaSchema(this); if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta); if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}}); addInitialSchemas(this); } /** * Validate data using schema * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize. * @this Ajv * @param {String|Object} schemaKeyRef key, ref or schema object * @param {Any} data to be validated * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). */ function validate(schemaKeyRef, data) { var v; if (typeof schemaKeyRef == 'string') { v = this.getSchema(schemaKeyRef); if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"'); } else { var schemaObj = this._addSchema(schemaKeyRef); v = schemaObj.validate || this._compile(schemaObj); } var valid = v(data); if (v.$async !== true) this.errors = v.errors; return valid; } /** * Create validating function for passed schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords. * @return {Function} validating function */ function compile(schema, _meta) { var schemaObj = this._addSchema(schema, undefined, _meta); return schemaObj.validate || this._compile(schemaObj); } /** * Adds schema to the instance. * @this Ajv * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead. * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. * @return {Ajv} this for method chaining */ function addSchema(schema, key, _skipValidation, _meta) { if (Array.isArray(schema)){ for (var i=0; i<schema.length; i++) this.addSchema(schema[i], undefined, _skipValidation, _meta); return this; } var id = this._getId(schema); if (id !== undefined && typeof id != 'string') throw new Error('schema id must be string'); key = resolve.normalizeId(key || id); checkUnique(this, key); this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true); return this; } /** * Add schema that will be used to validate other schemas * options in META_IGNORE_OPTIONS are alway set to false * @this Ajv * @param {Object} schema schema object * @param {String} key optional schema key * @param {Boolean} skipValidation true to skip schema validation, can be used to override validateSchema option for meta-schema * @return {Ajv} this for method chaining */ function addMetaSchema(schema, key, skipValidation) { this.addSchema(schema, key, skipValidation, true); return this; } /** * Validate schema * @this Ajv * @param {Object} schema schema to validate * @param {Boolean} throwOrLogError pass true to throw (or log) an error if invalid * @return {Boolean} true if schema is valid */ function validateSchema(schema, throwOrLogError) { var $schema = schema.$schema; if ($schema !== undefined && typeof $schema != 'string') throw new Error('$schema must be a string'); $schema = $schema || this._opts.defaultMeta || defaultMeta(this); if (!$schema) { this.logger.warn('meta-schema not available'); this.errors = null; return true; } var valid = this.validate($schema, schema); if (!valid && throwOrLogError) { var message = 'schema is invalid: ' + this.errorsText(); if (this._opts.validateSchema == 'log') this.logger.error(message); else throw new Error(message); } return valid; } function defaultMeta(self) { var meta = self._opts.meta; self._opts.defaultMeta = typeof meta == 'object' ? self._getId(meta) || meta : self.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined; return self._opts.defaultMeta; } /** * Get compiled schema from the instance by `key` or `ref`. * @this Ajv * @param {String} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). * @return {Function} schema validating function (with property `schema`). */ function getSchema(keyRef) { var schemaObj = _getSchemaObj(this, keyRef); switch (typeof schemaObj) { case 'object': return schemaObj.validate || this._compile(schemaObj); case 'string': return this.getSchema(schemaObj); case 'undefined': return _getSchemaFragment(this, keyRef); } } function _getSchemaFragment(self, ref) { var res = resolve.schema.call(self, { schema: {} }, ref); if (res) { var schema = res.schema , root = res.root , baseId = res.baseId; var v = compileSchema.call(self, schema, root, undefined, baseId); self._fragments[ref] = new SchemaObject({ ref: ref, fragment: true, schema: schema, root: root, baseId: baseId, validate: v }); return v; } } function _getSchemaObj(self, keyRef) { keyRef = resolve.normalizeId(keyRef); return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef]; } /** * Remove cached schema(s). * If no parameter is passed all schemas but meta-schemas are removed. * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. * @this Ajv * @param {String|Object|RegExp} schemaKeyRef key, ref, pattern to match key/ref or schema object * @return {Ajv} this for method chaining */ function removeSchema(schemaKeyRef) { if (schemaKeyRef instanceof RegExp) { _removeAllSchemas(this, this._schemas, schemaKeyRef); _removeAllSchemas(this, this._refs, schemaKeyRef); return this; } switch (typeof schemaKeyRef) { case 'undefined': _removeAllSchemas(this, this._schemas); _removeAllSchemas(this, this._refs); this._cache.clear(); return this; case 'string': var schemaObj = _getSchemaObj(this, schemaKeyRef); if (schemaObj) this._cache.del(schemaObj.cacheKey); delete this._schemas[schemaKeyRef]; delete this._refs[schemaKeyRef]; return this; case 'object': var serialize = this._opts.serialize; var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef; this._cache.del(cacheKey); var id = this._getId(schemaKeyRef); if (id) { id = resolve.normalizeId(id); delete this._schemas[id]; delete this._refs[id]; } } return this; } function _removeAllSchemas(self, schemas, regex) { for (var keyRef in schemas) { var schemaObj = schemas[keyRef]; if (!schemaObj.meta && (!regex || regex.test(keyRef))) { self._cache.del(schemaObj.cacheKey); delete schemas[keyRef]; } } } /* @this Ajv */ function _addSchema(schema, skipValidation, meta, shouldAddSchema) { if (typeof schema != 'object' && typeof schema != 'boolean') throw new Error('schema should be object or boolean'); var serialize = this._opts.serialize; var cacheKey = serialize ? serialize(schema) : schema; var cached = this._cache.get(cacheKey); if (cached) return cached; shouldAddSchema = shouldAddSchema || this._opts.addUsedSchema !== false; var id = resolve.normalizeId(this._getId(schema)); if (id && shouldAddSchema) checkUnique(this, id); var willValidate = this._opts.validateSchema !== false && !skipValidation; var recursiveMeta; if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) this.validateSchema(schema, true); var localRefs = resolve.ids.call(this, schema); var schemaObj = new SchemaObject({ id: id, schema: schema, localRefs: localRefs, cacheKey: cacheKey, meta: meta }); if (id[0] != '#' && shouldAddSchema) this._refs[id] = schemaObj; this._cache.put(cacheKey, schemaObj); if (willValidate && recursiveMeta) this.validateSchema(schema, true); return schemaObj; } /* @this Ajv */ function _compile(schemaObj, root) { if (schemaObj.compiling) { schemaObj.validate = callValidate; callValidate.schema = schemaObj.schema; callValidate.errors = null; callValidate.root = root ? root : callValidate; if (schemaObj.schema.$async === true) callValidate.$async = true; return callValidate; } schemaObj.compiling = true; var currentOpts; if (schemaObj.meta) { currentOpts = this._opts; this._opts = this._metaOpts; } var v; try { v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs); } catch(e) { delete schemaObj.validate; throw e; } finally { schemaObj.compiling = false; if (schemaObj.meta) this._opts = currentOpts; } schemaObj.validate = v; schemaObj.refs = v.refs; schemaObj.refVal = v.refVal; schemaObj.root = v.root; return v; /* @this {*} - custom context, see passContext option */ function callValidate() { /* jshint validthis: true */ var _validate = schemaObj.validate; var result = _validate.apply(this, arguments); callValidate.errors = _validate.errors; return result; } } function chooseGetId(opts) { switch (opts.schemaId) { case 'auto': return _get$IdOrId; case 'id': return _getId; default: return _get$Id; } } /* @this Ajv */ function _getId(schema) { if (schema.$id) this.logger.warn('schema $id ignored', schema.$id); return schema.id; } /* @this Ajv */ function _get$Id(schema) { if (schema.id) this.logger.warn('schema id ignored', schema.id); return schema.$id; } function _get$IdOrId(schema) { if (schema.$id && schema.id && schema.$id != schema.id) throw new Error('schema $id is different from id'); return schema.$id || schema.id; } /** * Convert array of error message objects to string * @this Ajv * @param {Array<Object>} errors optional array of validation errors, if not passed errors from the instance are used. * @param {Object} options optional options with properties `separator` and `dataVar`. * @return {String} human readable string with all errors descriptions */ function errorsText(errors, options) { errors = errors || this.errors; if (!errors) return 'No errors'; options = options || {}; var separator = options.separator === undefined ? ', ' : options.separator; var dataVar = options.dataVar === undefined ? 'data' : options.dataVar; var text = ''; for (var i=0; i<errors.length; i++) { var e = errors[i]; if (e) text += dataVar + e.dataPath + ' ' + e.message + separator; } return text.slice(0, -separator.length); } /** * Add custom format * @this Ajv * @param {String} name format name * @param {String|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) * @return {Ajv} this for method chaining */ function addFormat(name, format) { if (typeof format == 'string') format = new RegExp(format); this._formats[name] = format; return this; } function addDefaultMetaSchema(self) { var $dataSchema; if (self._opts.$data) { $dataSchema = require('ajv/lib/refs/data.json'); self.addMetaSchema($dataSchema, $dataSchema.$id, true); } if (self._opts.meta === false) return; var metaSchema = require('ajv/lib/refs/json-schema-draft-07.json'); if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA); self.addMetaSchema(metaSchema, META_SCHEMA_ID, true); self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID; } function addInitialSchemas(self) { var optsSchemas = self._opts.schemas; if (!optsSchemas) return; if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas); else for (var key in optsSchemas) self.addSchema(optsSchemas[key], key); } function addInitialFormats(self) { for (var name in self._opts.formats) { var format = self._opts.formats[name]; self.addFormat(name, format); } } function addInitialKeywords(self) { for (var name in self._opts.keywords) { var keyword = self._opts.keywords[name]; self.addKeyword(name, keyword); } } function checkUnique(self, id) { if (self._schemas[id] || self._refs[id]) throw new Error('schema with key or id "' + id + '" already exists'); } function getMetaSchemaOptions(self) { var metaOpts = util.copy(self._opts); for (var i=0; i<META_IGNORE_OPTIONS.length; i++) delete metaOpts[META_IGNORE_OPTIONS[i]]; return metaOpts; } function setLogger(self) { var logger = self._opts.logger; if (logger === false) { self.logger = {log: noop, warn: noop, error: noop}; } else { if (logger === undefined) logger = console; if (!(typeof logger == 'object' && logger.log && logger.warn && logger.error)) throw new Error('logger must implement log, warn and error methods'); self.logger = logger; } } function noop() {}
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/ajv.js
ajv.js
'use strict'; var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i; var customRuleCode = require('ajv/lib/dotjs/custom'); var definitionSchema = require('ajv/lib/definition_schema'); module.exports = { add: addKeyword, get: getKeyword, remove: removeKeyword, validate: validateKeyword }; /** * Define custom keyword * @this Ajv * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords). * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. * @return {Ajv} this for method chaining */ function addKeyword(keyword, definition) { /* jshint validthis: true */ /* eslint no-shadow: 0 */ var RULES = this.RULES; if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined'); if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier'); if (definition) { this.validateKeyword(definition, true); var dataType = definition.type; if (Array.isArray(dataType)) { for (var i=0; i<dataType.length; i++) _addRule(keyword, dataType[i], definition); } else { _addRule(keyword, dataType, definition); } var metaSchema = definition.metaSchema; if (metaSchema) { if (definition.$data && this._opts.$data) { metaSchema = { anyOf: [ metaSchema, { '$ref': 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#' } ] }; } definition.validateSchema = this.compile(metaSchema, true); } } RULES.keywords[keyword] = RULES.all[keyword] = true; function _addRule(keyword, dataType, definition) { var ruleGroup; for (var i=0; i<RULES.length; i++) { var rg = RULES[i]; if (rg.type == dataType) { ruleGroup = rg; break; } } if (!ruleGroup) { ruleGroup = { type: dataType, rules: [] }; RULES.push(ruleGroup); } var rule = { keyword: keyword, definition: definition, custom: true, code: customRuleCode, implements: definition.implements }; ruleGroup.rules.push(rule); RULES.custom[keyword] = rule; } return this; } /** * Get keyword * @this Ajv * @param {String} keyword pre-defined or custom keyword. * @return {Object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. */ function getKeyword(keyword) { /* jshint validthis: true */ var rule = this.RULES.custom[keyword]; return rule ? rule.definition : this.RULES.keywords[keyword] || false; } /** * Remove keyword * @this Ajv * @param {String} keyword pre-defined or custom keyword. * @return {Ajv} this for method chaining */ function removeKeyword(keyword) { /* jshint validthis: true */ var RULES = this.RULES; delete RULES.keywords[keyword]; delete RULES.all[keyword]; delete RULES.custom[keyword]; for (var i=0; i<RULES.length; i++) { var rules = RULES[i].rules; for (var j=0; j<rules.length; j++) { if (rules[j].keyword == keyword) { rules.splice(j, 1); break; } } } return this; } /** * Validate keyword definition * @this Ajv * @param {Object} definition keyword definition object. * @param {Boolean} throwError true to throw exception if definition is invalid * @return {boolean} validation result */ function validateKeyword(definition, throwError) { validateKeyword.errors = null; var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true); if (v(definition)) return true; validateKeyword.errors = v.errors; if (throwError) throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors)); else return false; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/keyword.js
keyword.js
declare var ajv: { (options?: ajv.Options): ajv.Ajv; new(options?: ajv.Options): ajv.Ajv; ValidationError: typeof AjvErrors.ValidationError; MissingRefError: typeof AjvErrors.MissingRefError; $dataMetaSchema: object; } declare namespace AjvErrors { class ValidationError extends Error { constructor(errors: Array<ajv.ErrorObject>); message: string; errors: Array<ajv.ErrorObject>; ajv: true; validation: true; } class MissingRefError extends Error { constructor(baseId: string, ref: string, message?: string); static message: (baseId: string, ref: string) => string; message: string; missingRef: string; missingSchema: string; } } declare namespace ajv { type ValidationError = AjvErrors.ValidationError; type MissingRefError = AjvErrors.MissingRefError; interface Ajv { /** * Validate data using schema * Schema will be compiled and cached (using serialized JSON as key, [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize by default). * @param {string|object|Boolean} schemaKeyRef key, ref or schema object * @param {Any} data to be validated * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`). */ validate(schemaKeyRef: object | string | boolean, data: any): boolean | PromiseLike<any>; /** * Create validating function for passed schema. * @param {object|Boolean} schema schema object * @return {Function} validating function */ compile(schema: object | boolean): ValidateFunction; /** * Creates validating function for passed schema with asynchronous loading of missing schemas. * `loadSchema` option should be a function that accepts schema uri and node-style callback. * @this Ajv * @param {object|Boolean} schema schema object * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped * @param {Function} callback optional node-style callback, it is always called with 2 parameters: error (or null) and validating function. * @return {PromiseLike<ValidateFunction>} validating function */ compileAsync(schema: object | boolean, meta?: Boolean, callback?: (err: Error, validate: ValidateFunction) => any): PromiseLike<ValidateFunction>; /** * Adds schema to the instance. * @param {object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored. * @param {string} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. * @return {Ajv} this for method chaining */ addSchema(schema: Array<object> | object, key?: string): Ajv; /** * Add schema that will be used to validate other schemas * options in META_IGNORE_OPTIONS are alway set to false * @param {object} schema schema object * @param {string} key optional schema key * @return {Ajv} this for method chaining */ addMetaSchema(schema: object, key?: string): Ajv; /** * Validate schema * @param {object|Boolean} schema schema to validate * @return {Boolean} true if schema is valid */ validateSchema(schema: object | boolean): boolean; /** * Get compiled schema from the instance by `key` or `ref`. * @param {string} keyRef `key` that was passed to `addSchema` or full schema reference (`schema.id` or resolved id). * @return {Function} schema validating function (with property `schema`). Returns undefined if keyRef can't be resolved to an existing schema. */ getSchema(keyRef: string): ValidateFunction | undefined; /** * Remove cached schema(s). * If no parameter is passed all schemas but meta-schemas are removed. * If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. * Even if schema is referenced by other schemas it still can be removed as other schemas have local references. * @param {string|object|RegExp|Boolean} schemaKeyRef key, ref, pattern to match key/ref or schema object * @return {Ajv} this for method chaining */ removeSchema(schemaKeyRef?: object | string | RegExp | boolean): Ajv; /** * Add custom format * @param {string} name format name * @param {string|RegExp|Function} format string is converted to RegExp; function should return boolean (true when valid) * @return {Ajv} this for method chaining */ addFormat(name: string, format: FormatValidator | FormatDefinition): Ajv; /** * Define custom keyword * @this Ajv * @param {string} keyword custom keyword, should be a valid identifier, should be different from all standard, custom and macro keywords. * @param {object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`. * @return {Ajv} this for method chaining */ addKeyword(keyword: string, definition: KeywordDefinition): Ajv; /** * Get keyword definition * @this Ajv * @param {string} keyword pre-defined or custom keyword. * @return {object|Boolean} custom keyword definition, `true` if it is a predefined keyword, `false` otherwise. */ getKeyword(keyword: string): object | boolean; /** * Remove keyword * @this Ajv * @param {string} keyword pre-defined or custom keyword. * @return {Ajv} this for method chaining */ removeKeyword(keyword: string): Ajv; /** * Validate keyword * @this Ajv * @param {object} definition keyword definition object * @param {boolean} throwError true to throw exception if definition is invalid * @return {boolean} validation result */ validateKeyword(definition: KeywordDefinition, throwError: boolean): boolean; /** * Convert array of error message objects to string * @param {Array<object>} errors optional array of validation errors, if not passed errors from the instance are used. * @param {object} options optional options with properties `separator` and `dataVar`. * @return {string} human readable string with all errors descriptions */ errorsText(errors?: Array<ErrorObject> | null, options?: ErrorsTextOptions): string; errors?: Array<ErrorObject> | null; } interface CustomLogger { log(...args: any[]): any; warn(...args: any[]): any; error(...args: any[]): any; } interface ValidateFunction { ( data: any, dataPath?: string, parentData?: object | Array<any>, parentDataProperty?: string | number, rootData?: object | Array<any> ): boolean | PromiseLike<any>; schema?: object | boolean; errors?: null | Array<ErrorObject>; refs?: object; refVal?: Array<any>; root?: ValidateFunction | object; $async?: true; source?: object; } interface Options { $data?: boolean; allErrors?: boolean; verbose?: boolean; jsonPointers?: boolean; uniqueItems?: boolean; unicode?: boolean; format?: false | string; formats?: object; keywords?: object; unknownFormats?: true | string[] | 'ignore'; schemas?: Array<object> | object; schemaId?: '$id' | 'id' | 'auto'; missingRefs?: true | 'ignore' | 'fail'; extendRefs?: true | 'ignore' | 'fail'; loadSchema?: (uri: string, cb?: (err: Error, schema: object) => void) => PromiseLike<object | boolean>; removeAdditional?: boolean | 'all' | 'failing'; useDefaults?: boolean | 'empty' | 'shared'; coerceTypes?: boolean | 'array'; strictDefaults?: boolean | 'log'; strictKeywords?: boolean | 'log'; strictNumbers?: boolean; async?: boolean | string; transpile?: string | ((code: string) => string); meta?: boolean | object; validateSchema?: boolean | 'log'; addUsedSchema?: boolean; inlineRefs?: boolean | number; passContext?: boolean; loopRequired?: number; ownProperties?: boolean; multipleOfPrecision?: boolean | number; errorDataPath?: string, messages?: boolean; sourceCode?: boolean; processCode?: (code: string, schema: object) => string; cache?: object; logger?: CustomLogger | false; nullable?: boolean; serialize?: ((schema: object | boolean) => any) | false; } type FormatValidator = string | RegExp | ((data: string) => boolean | PromiseLike<any>); type NumberFormatValidator = ((data: number) => boolean | PromiseLike<any>); interface NumberFormatDefinition { type: "number", validate: NumberFormatValidator; compare?: (data1: number, data2: number) => number; async?: boolean; } interface StringFormatDefinition { type?: "string", validate: FormatValidator; compare?: (data1: string, data2: string) => number; async?: boolean; } type FormatDefinition = NumberFormatDefinition | StringFormatDefinition; interface KeywordDefinition { type?: string | Array<string>; async?: boolean; $data?: boolean; errors?: boolean | string; metaSchema?: object; // schema: false makes validate not to expect schema (ValidateFunction) schema?: boolean; statements?: boolean; dependencies?: Array<string>; modifying?: boolean; valid?: boolean; // one and only one of the following properties should be present validate?: SchemaValidateFunction | ValidateFunction; compile?: (schema: any, parentSchema: object, it: CompilationContext) => ValidateFunction; macro?: (schema: any, parentSchema: object, it: CompilationContext) => object | boolean; inline?: (it: CompilationContext, keyword: string, schema: any, parentSchema: object) => string; } interface CompilationContext { level: number; dataLevel: number; dataPathArr: string[]; schema: any; schemaPath: string; baseId: string; async: boolean; opts: Options; formats: { [index: string]: FormatDefinition | undefined; }; keywords: { [index: string]: KeywordDefinition | undefined; }; compositeRule: boolean; validate: (schema: object) => boolean; util: { copy(obj: any, target?: any): any; toHash(source: string[]): { [index: string]: true | undefined }; equal(obj: any, target: any): boolean; getProperty(str: string): string; schemaHasRules(schema: object, rules: any): string; escapeQuotes(str: string): string; toQuotedString(str: string): string; getData(jsonPointer: string, dataLevel: number, paths: string[]): string; escapeJsonPointer(str: string): string; unescapeJsonPointer(str: string): string; escapeFragment(str: string): string; unescapeFragment(str: string): string; }; self: Ajv; } interface SchemaValidateFunction { ( schema: any, data: any, parentSchema?: object, dataPath?: string, parentData?: object | Array<any>, parentDataProperty?: string | number, rootData?: object | Array<any> ): boolean | PromiseLike<any>; errors?: Array<ErrorObject>; } interface ErrorsTextOptions { separator?: string; dataVar?: string; } interface ErrorObject { keyword: string; dataPath: string; schemaPath: string; params: ErrorParameters; // Added to validation errors of propertyNames keyword schema propertyName?: string; // Excluded if messages set to false. message?: string; // These are added with the `verbose` option. schema?: any; parentSchema?: object; data?: any; } type ErrorParameters = RefParams | LimitParams | AdditionalPropertiesParams | DependenciesParams | FormatParams | ComparisonParams | MultipleOfParams | PatternParams | RequiredParams | TypeParams | UniqueItemsParams | CustomParams | PatternRequiredParams | PropertyNamesParams | IfParams | SwitchParams | NoParams | EnumParams; interface RefParams { ref: string; } interface LimitParams { limit: number; } interface AdditionalPropertiesParams { additionalProperty: string; } interface DependenciesParams { property: string; missingProperty: string; depsCount: number; deps: string; } interface FormatParams { format: string } interface ComparisonParams { comparison: string; limit: number | string; exclusive: boolean; } interface MultipleOfParams { multipleOf: number; } interface PatternParams { pattern: string; } interface RequiredParams { missingProperty: string; } interface TypeParams { type: string; } interface UniqueItemsParams { i: number; j: number; } interface CustomParams { keyword: string; } interface PatternRequiredParams { missingPattern: string; } interface PropertyNamesParams { propertyName: string; } interface IfParams { failingKeyword: string; } interface SwitchParams { caseIndex: number; } interface NoParams { } interface EnumParams { allowedValues: Array<any>; } } export = ajv;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/ajv.d.ts
ajv.d.ts
'use strict'; module.exports = function generate_validate(it, $keyword, $ruleType) { var out = ''; var $async = it.schema.$async === true, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), $id = it.self._getId(it.schema); if (it.opts.strictKeywords) { var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords); if ($unknownKwd) { var $keywordsMsg = 'unknown keyword: ' + $unknownKwd; if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg); else throw new Error($keywordsMsg); } } if (it.isTop) { out += ' var validate = '; if ($async) { it.async = true; out += 'async '; } out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; '; if ($id && (it.opts.sourceCode || it.opts.processCode)) { out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' '; } } if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) { var $keyword = 'false schema'; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; if (it.schema === false) { if (it.isTop) { $breakOnError = true; } else { out += ' var ' + ($valid) + ' = false; '; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'boolean schema is false\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { if (it.isTop) { if ($async) { out += ' return data; '; } else { out += ' validate.errors = null; return true; '; } } else { out += ' var ' + ($valid) + ' = true; '; } } if (it.isTop) { out += ' }; return validate; '; } return out; } if (it.isTop) { var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = 'data'; it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema)); it.baseId = it.baseId || it.rootId; delete it.isTop; it.dataPathArr = [undefined]; if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) { var $defaultMsg = 'default is ignored in the schema root'; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } out += ' var vErrors = null; '; out += ' var errors = 0; '; out += ' if (rootData === undefined) rootData = data; '; } else { var $lvl = it.level, $dataLvl = it.dataLevel, $data = 'data' + ($dataLvl || ''); if ($id) it.baseId = it.resolve.url(it.baseId, $id); if ($async && !it.async) throw new Error('async schema in sync schema'); out += ' var errs_' + ($lvl) + ' = errors;'; } var $valid = 'valid' + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = '', $closingBraces2 = ''; var $errorKeyword; var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema); if ($typeSchema && it.opts.nullable && it.schema.nullable === true) { if ($typeIsArray) { if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null'); } else if ($typeSchema != 'null') { $typeSchema = [$typeSchema, 'null']; $typeIsArray = true; } } if ($typeIsArray && $typeSchema.length == 1) { $typeSchema = $typeSchema[0]; $typeIsArray = false; } if (it.schema.$ref && $refKeywords) { if (it.opts.extendRefs == 'fail') { throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)'); } else if (it.opts.extendRefs !== true) { $refKeywords = false; it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"'); } } if (it.schema.$comment && it.opts.$comment) { out += ' ' + (it.RULES.all.$comment.code(it, '$comment')); } if ($typeSchema) { if (it.opts.coerceTypes) { var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema); } var $rulesGroup = it.RULES.types[$typeSchema]; if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) { var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type', $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType'; out += ' if (' + (it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true)) + ') { '; if ($coerceToTypes) { var $dataType = 'dataType' + $lvl, $coerced = 'coerced' + $lvl; out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; '; if (it.opts.coerceTypes == 'array') { out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; '; } out += ' var ' + ($coerced) + ' = undefined; '; var $bracesCoercion = ''; var arr1 = $coerceToTypes; if (arr1) { var $type, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $type = arr1[$i += 1]; if ($i) { out += ' if (' + ($coerced) + ' === undefined) { '; $bracesCoercion += '}'; } if (it.opts.coerceTypes == 'array' && $type != 'array') { out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } '; } if ($type == 'string') { out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; '; } else if ($type == 'number' || $type == 'integer') { out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' '; if ($type == 'integer') { out += ' && !(' + ($data) + ' % 1)'; } out += ')) ' + ($coerced) + ' = +' + ($data) + '; '; } else if ($type == 'boolean') { out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; '; } else if ($type == 'null') { out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; '; } else if (it.opts.coerceTypes == 'array' && $type == 'array') { out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; '; } } } out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' ' + ($data) + ' = ' + ($coerced) + '; '; if (!$dataLvl) { out += 'if (' + ($parentData) + ' !== undefined)'; } out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } '; } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } out += ' } '; } } if (it.schema.$ref && !$refKeywords) { out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' '; if ($breakOnError) { out += ' } if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } else { var arr2 = it.RULES; if (arr2) { var $rulesGroup, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $rulesGroup = arr2[i2 += 1]; if ($shouldUseGroup($rulesGroup)) { if ($rulesGroup.type) { out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers)) + ') { '; } if (it.opts.useDefaults) { if ($rulesGroup.type == 'object' && it.schema.properties) { var $schema = it.schema.properties, $schemaKeys = Object.keys($schema); var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ($sch.default !== undefined) { var $passData = $data + it.util.getProperty($propertyKey); if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) { var arr4 = it.schema.items; if (arr4) { var $sch, $i = -1, l4 = arr4.length - 1; while ($i < l4) { $sch = arr4[$i += 1]; if ($sch.default !== undefined) { var $passData = $data + '[' + $i + ']'; if (it.compositeRule) { if (it.opts.strictDefaults) { var $defaultMsg = 'default is ignored for: ' + $passData; if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg); else throw new Error($defaultMsg); } } else { out += ' if (' + ($passData) + ' === undefined '; if (it.opts.useDefaults == 'empty') { out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' '; } out += ' ) ' + ($passData) + ' = '; if (it.opts.useDefaults == 'shared') { out += ' ' + (it.useDefault($sch.default)) + ' '; } else { out += ' ' + (JSON.stringify($sch.default)) + ' '; } out += '; '; } } } } } } var arr5 = $rulesGroup.rules; if (arr5) { var $rule, i5 = -1, l5 = arr5.length - 1; while (i5 < l5) { $rule = arr5[i5 += 1]; if ($shouldUseRule($rule)) { var $code = $rule.code(it, $rule.keyword, $rulesGroup.type); if ($code) { out += ' ' + ($code) + ' '; if ($breakOnError) { $closingBraces1 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces1) + ' '; $closingBraces1 = ''; } if ($rulesGroup.type) { out += ' } '; if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) { out += ' else { '; var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \''; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should be '; if ($typeIsArray) { out += '' + ($typeSchema.join(",")); } else { out += '' + ($typeSchema); } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; } } if ($breakOnError) { out += ' if (errors === '; if ($top) { out += '0'; } else { out += 'errs_' + ($lvl); } out += ') { '; $closingBraces2 += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces2) + ' '; } if ($top) { if ($async) { out += ' if (errors === 0) return data; '; out += ' else throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; '; out += ' return errors === 0; '; } out += ' }; return validate;'; } else { out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';'; } function $shouldUseGroup($rulesGroup) { var rules = $rulesGroup.rules; for (var i = 0; i < rules.length; i++) if ($shouldUseRule(rules[i])) return true; } function $shouldUseRule($rule) { return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule)); } function $ruleImplementsSomeKeyword($rule) { var impl = $rule.implements; for (var i = 0; i < impl.length; i++) if (it.schema[impl[i]] !== undefined) return true; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/validate.js
validate.js
'use strict'; module.exports = function generate_properties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl; var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; var $required = it.schema.required; if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) { var $requiredHash = it.util.toHash($required); } function notProto(p) { return p !== '__proto__'; } out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;'; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined;'; } if ($checkAdditional) { if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } if ($someProperties) { out += ' var isAdditional' + ($lvl) + ' = !(false '; if ($schemaKeys.length) { if ($schemaKeys.length > 8) { out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') '; } else { var arr1 = $schemaKeys; if (arr1) { var $propertyKey, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $propertyKey = arr1[i1 += 1]; out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' '; } } } } if ($pPropertyKeys.length) { var arr2 = $pPropertyKeys; if (arr2) { var $pProperty, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $pProperty = arr2[$i += 1]; out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') '; } } } out += ' ); if (isAdditional' + ($lvl) + ') { '; } if ($removeAdditional == 'all') { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { var $currentErrorPath = it.errorPath; var $additionalProperty = '\' + ' + $key + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); } if ($noAdditional) { if ($removeAdditional) { out += ' delete ' + ($data) + '[' + ($key) + ']; '; } else { out += ' ' + ($nextValid) + ' = false; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalProperties'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is an invalid additional property'; } else { out += 'should NOT have additional properties'; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { out += ' break; '; } } } else if ($additionalIsSchema) { if ($removeAdditional == 'failing') { out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } '; it.compositeRule = $it.compositeRule = $wasComposite; } else { $it.schema = $aProperties; $it.schemaPath = it.schemaPath + '.additionalProperties'; $it.errSchemaPath = it.errSchemaPath + '/additionalProperties'; $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } } } it.errorPath = $currentErrorPath; } if ($someProperties) { out += ' } '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } var $useDefaults = it.opts.useDefaults && !it.compositeRule; if ($schemaKeys.length) { var arr3 = $schemaKeys; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $sch = $schema[$propertyKey]; if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) { var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== undefined; $it.schema = $sch; $it.schemaPath = $schemaPath + $prop; $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey); $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers); $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey); var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { $code = it.util.varReplace($code, $nextData, $passData); var $useData = $passData; } else { var $useData = $nextData; out += ' var ' + ($nextData) + ' = ' + ($passData) + '; '; } if ($hasDefault) { out += ' ' + ($code) + ' '; } else { if ($requiredHash && $requiredHash[$propertyKey]) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = false; '; var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey); if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } $errSchemaPath = it.errSchemaPath + '/required'; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } $errSchemaPath = $currErrSchemaPath; it.errorPath = $currentErrorPath; out += ' } else { '; } else { if ($breakOnError) { out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { ' + ($nextValid) + ' = true; } else { '; } else { out += ' if (' + ($useData) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ' ) { '; } } out += ' ' + ($code) + ' } '; } } if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if ($pPropertyKeys.length) { var arr4 = $pPropertyKeys; if (arr4) { var $pProperty, i4 = -1, l4 = arr4.length - 1; while (i4 < l4) { $pProperty = arr4[i4 += 1]; var $sch = $pProperties[$pProperty]; if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty); $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty); if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers); var $passData = $data + '[' + $key + ']'; $it.dataPathArr[$dataNxt] = $key; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } '; if ($breakOnError) { out += ' else ' + ($nextValid) + ' = true; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/properties.js
properties.js
'use strict'; module.exports = function generate_required(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $vSchema = 'schema' + $lvl; if (!$isData) { if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) { var $required = []; var arr1 = $schema; if (arr1) { var $property, i1 = -1, l1 = arr1.length - 1; while (i1 < l1) { $property = arr1[i1 += 1]; var $propertySch = it.schema.properties[$property]; if (!($propertySch && (it.opts.strictKeywords ? typeof $propertySch == 'object' && Object.keys($propertySch).length > 0 : it.util.schemaHasRules($propertySch, it.RULES.all)))) { $required[$required.length] = $property; } } } } else { var $required = $schema; } } if ($isData || $required.length) { var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties; if ($breakOnError) { out += ' var missing' + ($lvl) + '; '; if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } out += ' var ' + ($valid) + ' = true; '; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += '; if (!' + ($valid) + ') break; } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } else { out += ' if ( '; var arr2 = $required; if (arr2) { var $propertyKey, $i = -1, l2 = arr2.length - 1; while ($i < l2) { $propertyKey = arr2[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ') { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; } } else { if ($loopRequired) { if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; '; } var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers); } if ($isData) { out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { '; } out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } '; if ($isData) { out += ' } '; } } else { var arr3 = $required; if (arr3) { var $propertyKey, i3 = -1, l3 = arr3.length - 1; while (i3 < l3) { $propertyKey = arr3[i3 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \''; if (it.opts._errorDataPathProperty) { out += 'is a required property'; } else { out += 'should have required property \\\'' + ($missingProperty) + '\\\''; } out += '\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } } it.errorPath = $currentErrorPath; } else if ($breakOnError) { out += ' if (true) {'; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/required.js
required.js
'use strict'; module.exports = function generate_format(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); if (it.opts.format === false) { if ($breakOnError) { out += ' if (true) { '; } return out; } var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats); if ($isData) { var $format = 'format' + $lvl, $isObject = 'isObject' + $lvl, $formatType = 'formatType' + $lvl; out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { '; if (it.async) { out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; '; } out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' ('; if ($unknownFormats != 'ignore') { out += ' (' + ($schemaValue) + ' && !' + ($format) + ' '; if ($allowUnknown) { out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 '; } out += ') || '; } out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? '; if (it.async) { out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) '; } else { out += ' ' + ($format) + '(' + ($data) + ') '; } out += ' : ' + ($format) + '.test(' + ($data) + '))))) {'; } else { var $format = it.formats[$schema]; if (!$format) { if ($unknownFormats == 'ignore') { it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"'); if ($breakOnError) { out += ' if (true) { '; } return out; } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) { if ($breakOnError) { out += ' if (true) { '; } return out; } else { throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"'); } } var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate; var $formatType = $isObject && $format.type || 'string'; if ($isObject) { var $async = $format.async === true; $format = $format.validate; } if ($formatType != $ruleType) { if ($breakOnError) { out += ' if (true) { '; } return out; } if ($async) { if (!it.async) throw new Error('async format in sync schema'); var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate'; out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { '; } else { out += ' if (! '; var $formatRef = 'formats' + it.util.getProperty($schema); if ($isObject) $formatRef += '.validate'; if (typeof $format == 'function') { out += ' ' + ($formatRef) + '(' + ($data) + ') '; } else { out += ' ' + ($formatRef) + '.test(' + ($data) + ') '; } out += ') { '; } } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match format "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/format.js
format.js
'use strict'; module.exports = function generate__limitProperties(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxProperties' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxProperties') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' properties\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/_limitProperties.js
_limitProperties.js
'use strict'; module.exports = function generate_enum(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $i = 'i' + $lvl, $vSchema = 'schema' + $lvl; if (!$isData) { out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ';'; if ($isData) { out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {'; } out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }'; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to one of the allowed values\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/enum.js
enum.js
'use strict'; module.exports = function generate_pattern(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema); out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || '; } out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: '; if ($isData) { out += '' + ($schemaValue); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match pattern "'; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + (it.util.escapeQuotes($schema)); } out += '"\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + (it.util.toQuotedString($schema)); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/pattern.js
pattern.js
'use strict'; module.exports = function generate_custom(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $rule = this, $definition = 'definition' + $lvl, $rDef = $rule.definition, $closingBraces = ''; var $compile, $inline, $macro, $ruleValidate, $validateCode; if ($isData && $rDef.$data) { $validateCode = 'keywordValidate' + $lvl; var $validateSchema = $rDef.validateSchema; out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;'; } else { $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it); if (!$ruleValidate) return; $schemaValue = 'validate.schema' + $schemaPath; $validateCode = $ruleValidate.code; $compile = $rDef.compile; $inline = $rDef.inline; $macro = $rDef.macro; } var $ruleErrs = $validateCode + '.errors', $i = 'i' + $lvl, $ruleErr = 'ruleErr' + $lvl, $asyncKeyword = $rDef.async; if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema'); if (!($inline || $macro)) { out += '' + ($ruleErrs) + ' = null;'; } out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($isData && $rDef.$data) { $closingBraces += '}'; out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { '; if ($validateSchema) { $closingBraces += '}'; out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { '; } } if ($inline) { if ($rDef.statements) { out += ' ' + ($ruleValidate.validate) + ' '; } else { out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; '; } } else if ($macro) { var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $ruleValidate.validate; $it.schemaPath = ''; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it).replace(/validate\.schema/g, $validateCode); it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($code); } else { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; out += ' ' + ($validateCode) + '.call( '; if (it.opts.passContext) { out += 'this'; } else { out += 'self'; } if ($compile || $rDef.schema === false) { out += ' , ' + ($data) + ' '; } else { out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' '; } out += ' , (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) '; var def_callRuleValidate = out; out = $$outStack.pop(); if ($rDef.errors === false) { out += ' ' + ($valid) + ' = '; if ($asyncKeyword) { out += 'await '; } out += '' + (def_callRuleValidate) + '; '; } else { if ($asyncKeyword) { $ruleErrs = 'customErrors' + $lvl; out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } '; } else { out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; '; } } } if ($rDef.modifying) { out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];'; } out += '' + ($closingBraces); if ($rDef.valid) { if ($breakOnError) { out += ' if (true) { '; } } else { out += ' if ( '; if ($rDef.valid === undefined) { out += ' !'; if ($macro) { out += '' + ($nextValid); } else { out += '' + ($valid); } } else { out += ' ' + (!$rDef.valid) + ' '; } out += ') { '; $errorKeyword = $rule.keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } var def_customError = out; out = $$outStack.pop(); if ($inline) { if ($rDef.errors) { if ($rDef.errors != 'full') { out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; if (it.opts.verbose) { out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; } out += ' } '; } } else { if ($rDef.errors === false) { out += ' ' + (def_customError) + ' '; } else { out += ' if (' + ($errs) + ' == errors) { ' + (def_customError) + ' } else { for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; if (' + ($ruleErr) + '.schemaPath === undefined) { ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; } '; if (it.opts.verbose) { out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; } out += ' } } '; } } } else if ($macro) { out += ' var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } } else { if ($rDef.errors === false) { out += ' ' + (def_customError) + ' '; } else { out += ' if (Array.isArray(' + ($ruleErrs) + ')) { if (vErrors === null) vErrors = ' + ($ruleErrs) + '; else vErrors = vErrors.concat(' + ($ruleErrs) + '); errors = vErrors.length; for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + '<errors; ' + ($i) + '++) { var ' + ($ruleErr) + ' = vErrors[' + ($i) + ']; if (' + ($ruleErr) + '.dataPath === undefined) ' + ($ruleErr) + '.dataPath = (dataPath || \'\') + ' + (it.errorPath) + '; ' + ($ruleErr) + '.schemaPath = "' + ($errSchemaPath) + '"; '; if (it.opts.verbose) { out += ' ' + ($ruleErr) + '.schema = ' + ($schemaValue) + '; ' + ($ruleErr) + '.data = ' + ($data) + '; '; } out += ' } } else { ' + (def_customError) + ' } '; } } out += ' } '; if ($breakOnError) { out += ' else { '; } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/custom.js
custom.js
'use strict'; module.exports = function generate_const(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!$isData) { out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';'; } out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be equal to constant\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' }'; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/const.js
const.js
'use strict'; module.exports = function generate_anyOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $noEmptySchema = $schema.every(function($sch) { return (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all)); }); if ($noEmptySchema) { var $currentBaseId = $it.baseId; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { '; $closingBraces += '}'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should match some schema in anyOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/anyOf.js
anyOf.js
'use strict'; module.exports = function generate_if(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; var $thenSch = it.schema['then'], $elseSch = it.schema['else'], $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? typeof $thenSch == 'object' && Object.keys($thenSch).length > 0 : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? typeof $elseSch == 'object' && Object.keys($elseSch).length > 0 : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId; if ($thenPresent || $elsePresent) { var $ifClause; $it.createErrors = false; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; $it.createErrors = true; out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; it.compositeRule = $it.compositeRule = $wasComposite; if ($thenPresent) { out += ' if (' + ($nextValid) + ') { '; $it.schema = it.schema['then']; $it.schemaPath = it.schemaPath + '.then'; $it.errSchemaPath = it.errSchemaPath + '/then'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'then\'; '; } else { $ifClause = '\'then\''; } out += ' } '; if ($elsePresent) { out += ' else { '; } } else { out += ' if (!' + ($nextValid) + ') { '; } if ($elsePresent) { $it.schema = it.schema['else']; $it.schemaPath = it.schemaPath + '.else'; $it.errSchemaPath = it.errSchemaPath + '/else'; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' ' + ($valid) + ' = ' + ($nextValid) + '; '; if ($thenPresent && $elsePresent) { $ifClause = 'ifClause' + $lvl; out += ' var ' + ($ifClause) + ' = \'else\'; '; } else { $ifClause = '\'else\''; } out += ' } '; } out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/if.js
if.js
'use strict'; module.exports = function generate_dependencies(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties; for ($property in $schema) { if ($property == '__proto__') continue; var $sch = $schema[$property]; var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps; $deps[$property] = $sch; } out += 'var ' + ($errs) + ' = errors;'; var $currentErrorPath = it.errorPath; out += 'var missing' + ($lvl) + ';'; for (var $property in $propertyDeps) { $deps = $propertyDeps[$property]; if ($deps.length) { out += ' if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } if ($breakOnError) { out += ' && ( '; var arr1 = $deps; if (arr1) { var $propertyKey, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $propertyKey = arr1[$i += 1]; if ($i) { out += ' || '; } var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop; out += ' ( ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) '; } } out += ')) { '; var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \''; if (it.opts._errorDataPathProperty) { it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } } else { out += ' ) { '; var arr2 = $deps; if (arr2) { var $propertyKey, i2 = -1, l2 = arr2.length - 1; while (i2 < l2) { $propertyKey = arr2[i2 += 1]; var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop; if (it.opts._errorDataPathProperty) { it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers); } out += ' if ( ' + ($useData) + ' === undefined '; if ($ownProperties) { out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') '; } out += ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('dependencies') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { property: \'' + (it.util.escapeQuotes($property)) + '\', missingProperty: \'' + ($missingProperty) + '\', depsCount: ' + ($deps.length) + ', deps: \'' + (it.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", "))) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'should have '; if ($deps.length == 1) { out += 'property ' + (it.util.escapeQuotes($deps[0])); } else { out += 'properties ' + (it.util.escapeQuotes($deps.join(", "))); } out += ' when property ' + (it.util.escapeQuotes($property)) + ' is present\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } '; } } } out += ' } '; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } } it.errorPath = $currentErrorPath; var $currentBaseId = $it.baseId; for (var $property in $schemaDeps) { var $sch = $schemaDeps[$property]; if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined '; if ($ownProperties) { out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') '; } out += ') { '; $it.schema = $sch; $it.schemaPath = $schemaPath + it.util.getProperty($property); $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property); out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/dependencies.js
dependencies.js
'use strict'; module.exports = function generate__limitLength(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxLength' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } if (it.opts.unicode === false) { out += ' ' + ($data) + '.length '; } else { out += ' ucs2length(' + ($data) + ') '; } out += ' ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be '; if ($keyword == 'maxLength') { out += 'longer'; } else { out += 'shorter'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' characters\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/_limitLength.js
_limitLength.js
'use strict'; module.exports = function generate__limitItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } var $op = $keyword == 'maxItems' ? '>' : '<'; out += 'if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { '; var $errorKeyword = $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have '; if ($keyword == 'maxItems') { out += 'more'; } else { out += 'fewer'; } out += ' than '; if ($isData) { out += '\' + ' + ($schemaValue) + ' + \''; } else { out += '' + ($schema); } out += ' items\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/_limitItems.js
_limitItems.js
'use strict'; module.exports = function generate_oneOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $currentBaseId = $it.baseId, $prevValid = 'prevValid' + $lvl, $passingSchemas = 'passingSchemas' + $lvl; out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) { $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; out += ' ' + (it.validate($it)) + ' '; $it.baseId = $currentBaseId; } else { out += ' var ' + ($nextValid) + ' = true; '; } if ($i) { out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { '; $closingBraces += '}'; } out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }'; } } it.compositeRule = $it.compositeRule = $wasComposite; out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should match exactly one schema in oneOf\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }'; if (it.opts.allErrors) { out += ' } '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/oneOf.js
oneOf.js
'use strict'; module.exports = function generate_multipleOf(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (!($isData || typeof $schema == 'number')) { throw new Error($keyword + ' must be number'); } out += 'var division' + ($lvl) + ';if ('; if ($isData) { out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || '; } out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', '; if (it.opts.multipleOfPrecision) { out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' '; } else { out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') '; } out += ' ) '; if ($isData) { out += ' ) '; } out += ' ) { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be multiple of '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += '} '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/multipleOf.js
multipleOf.js
'use strict'; module.exports = function generate__limit(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $errorKeyword; var $data = 'data' + ($dataLvl || ''); var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } var $isMax = $keyword == 'maximum', $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? '<' : '>', $notOp = $isMax ? '>' : '<', $errorKeyword = undefined; if (!($isData || typeof $schema == 'number' || $schema === undefined)) { throw new Error($keyword + ' must be number'); } if (!($isDataExcl || $schemaExcl === undefined || typeof $schemaExcl == 'number' || typeof $schemaExcl == 'boolean')) { throw new Error($exclusiveKeyword + ' must be number or boolean'); } if ($isDataExcl) { var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = 'exclusive' + $lvl, $exclType = 'exclType' + $lvl, $exclIsNumber = 'exclIsNumber' + $lvl, $opExpr = 'op' + $lvl, $opStr = '\' + ' + $opExpr + ' + \''; out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; '; $schemaValueExcl = 'schemaExcl' + $lvl; out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { '; var $errorKeyword = $exclusiveKeyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; '; if ($schema === undefined) { $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaValueExcl; $isData = $isDataExcl; } } else { var $exclIsNumber = typeof $schemaExcl == 'number', $opStr = $op; if ($exclIsNumber && $isData) { var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { '; } else { if ($exclIsNumber && $schema === undefined) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $schemaValue = $schemaExcl; $notOp += '='; } else { if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema); if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) { $exclusive = true; $errorKeyword = $exclusiveKeyword; $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword; $notOp += '='; } else { $exclusive = false; $opStr += '='; } } var $opExpr = '\'' + $opStr + '\''; out += ' if ( '; if ($isData) { out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || '; } out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { '; } } $errorKeyword = $errorKeyword || $keyword; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should be ' + ($opStr) + ' '; if ($isData) { out += '\' + ' + ($schemaValue); } else { out += '' + ($schemaValue) + '\''; } } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/_limit.js
_limit.js
'use strict'; module.exports = function generate_uniqueItems(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue; if ($isData) { out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; '; $schemaValue = 'schema' + $lvl; } else { $schemaValue = $schema; } if (($schema || $isData) && it.opts.uniqueItems !== false) { if ($isData) { out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { '; } out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { '; var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType); if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) { out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } '; } else { out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; '; var $method = 'checkDataType' + ($typeIsArray ? 's' : ''); out += ' if (' + (it.util[$method]($itemType, 'item', it.opts.strictNumbers, true)) + ') continue; '; if ($typeIsArray) { out += ' if (typeof item == \'string\') item = \'"\' + item; '; } out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } '; } out += ' } '; if ($isData) { out += ' } '; } out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' '; } if (it.opts.verbose) { out += ' , schema: '; if ($isData) { out += 'validate.schema' + ($schemaPath); } else { out += '' + ($schema); } out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; if ($breakOnError) { out += ' else { '; } } else { if ($breakOnError) { out += ' if (true) { '; } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/uniqueItems.js
uniqueItems.js
'use strict'; module.exports = function generate_contains(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = (it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all)); out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if ($nonEmptySchema) { var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' if (' + ($nextValid) + ') break; } '; it.compositeRule = $it.compositeRule = $wasComposite; out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {'; } else { out += ' if (' + ($data) + '.length == 0) {'; } var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should contain a valid item\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { '; if ($nonEmptySchema) { out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; } if (it.opts.allErrors) { out += ' } '; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/contains.js
contains.js
'use strict'; module.exports = function generate_ref(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $async, $refCode; if ($schema == '#' || $schema == '#/') { if (it.isRoot) { $async = it.async; $refCode = 'validate'; } else { $async = it.root.schema.$async === true; $refCode = 'root.refVal[0]'; } } else { var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot); if ($refVal === undefined) { var $message = it.MissingRefError.message(it.baseId, $schema); if (it.opts.missingRefs == 'fail') { it.logger.error($message); var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('$ref') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { ref: \'' + (it.util.escapeQuotes($schema)) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'can\\\'t resolve reference ' + (it.util.escapeQuotes($schema)) + '\' '; } if (it.opts.verbose) { out += ' , schema: ' + (it.util.toQuotedString($schema)) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } if ($breakOnError) { out += ' if (false) { '; } } else if (it.opts.missingRefs == 'ignore') { it.logger.warn($message); if ($breakOnError) { out += ' if (true) { '; } } else { throw new it.MissingRefError(it.baseId, $schema, $message); } } else if ($refVal.inline) { var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; $it.schema = $refVal.schema; $it.schemaPath = ''; $it.errSchemaPath = $schema; var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code); out += ' ' + ($code) + ' '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; } } else { $async = $refVal.$async === true || (it.async && $refVal.$async !== false); $refCode = $refVal.code; } } if ($refCode) { var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; if (it.opts.passContext) { out += ' ' + ($refCode) + '.call(this, '; } else { out += ' ' + ($refCode) + '( '; } out += ' ' + ($data) + ', (dataPath || \'\')'; if (it.errorPath != '""') { out += ' + ' + (it.errorPath); } var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty'; out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ', rootData) '; var __callValidate = out; out = $$outStack.pop(); if ($async) { if (!it.async) throw new Error('async schema referenced by sync schema'); if ($breakOnError) { out += ' var ' + ($valid) + '; '; } out += ' try { await ' + (__callValidate) + '; '; if ($breakOnError) { out += ' ' + ($valid) + ' = true; '; } out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; '; if ($breakOnError) { out += ' ' + ($valid) + ' = false; '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($valid) + ') { '; } } else { out += ' if (!' + (__callValidate) + ') { if (vErrors === null) vErrors = ' + ($refCode) + '.errors; else vErrors = vErrors.concat(' + ($refCode) + '.errors); errors = vErrors.length; } '; if ($breakOnError) { out += ' else { '; } } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/ref.js
ref.js
'use strict'; module.exports = function generate_not(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); $it.level++; var $nextValid = 'valid' + $it.level; if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' var ' + ($errs) + ' = errors; '; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; $it.createErrors = false; var $allErrorsOption; if ($it.opts.allErrors) { $allErrorsOption = $it.opts.allErrors; $it.opts.allErrors = false; } out += ' ' + (it.validate($it)) + ' '; $it.createErrors = true; if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption; it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (' + ($nextValid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } '; if (it.opts.allErrors) { out += ' } '; } } else { out += ' var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} '; if (it.opts.messages !== false) { out += ' , message: \'should NOT be valid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if ($breakOnError) { out += ' if (false) { '; } } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/not.js
not.js
'use strict'; module.exports = function generate_propertyNames(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; out += 'var ' + ($errs) + ' = errors;'; if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $i = 'i' + $lvl, $invalidName = '\' + ' + $key + ' + \'', $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId; if ($ownProperties) { out += ' var ' + ($dataProperties) + ' = undefined; '; } if ($ownProperties) { out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; '; } else { out += ' for (var ' + ($key) + ' in ' + ($data) + ') { '; } out += ' var startErrs' + ($lvl) + ' = errors; '; var $passData = $key; var $wasComposite = it.compositeRule; it.compositeRule = $it.compositeRule = true; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } it.compositeRule = $it.compositeRule = $wasComposite; out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + '<errors; ' + ($i) + '++) { vErrors[' + ($i) + '].propertyName = ' + ($key) + '; } var err = '; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('propertyNames') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { propertyName: \'' + ($invalidName) + '\' } '; if (it.opts.messages !== false) { out += ' , message: \'property name \\\'' + ($invalidName) + '\\\' is invalid\' '; } if (it.opts.verbose) { out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError(vErrors); '; } else { out += ' validate.errors = vErrors; return false; '; } } if ($breakOnError) { out += ' break; '; } out += ' } }'; } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/propertyNames.js
propertyNames.js
'use strict'; module.exports = function generate_items(it, $keyword, $ruleType) { var out = ' '; var $lvl = it.level; var $dataLvl = it.dataLevel; var $schema = it.schema[$keyword]; var $schemaPath = it.schemaPath + it.util.getProperty($keyword); var $errSchemaPath = it.errSchemaPath + '/' + $keyword; var $breakOnError = !it.opts.allErrors; var $data = 'data' + ($dataLvl || ''); var $valid = 'valid' + $lvl; var $errs = 'errs__' + $lvl; var $it = it.util.copy(it); var $closingBraces = ''; $it.level++; var $nextValid = 'valid' + $it.level; var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId; out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';'; if (Array.isArray($schema)) { var $additionalItems = it.schema.additionalItems; if ($additionalItems === false) { out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; '; var $currErrSchemaPath = $errSchemaPath; $errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' if (!' + ($valid) + ') { '; var $$outStack = $$outStack || []; $$outStack.push(out); out = ''; /* istanbul ignore else */ if (it.createErrors !== false) { out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } '; if (it.opts.messages !== false) { out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' '; } if (it.opts.verbose) { out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' '; } out += ' } '; } else { out += ' {} '; } var __err = out; out = $$outStack.pop(); if (!it.compositeRule && $breakOnError) { /* istanbul ignore if */ if (it.async) { out += ' throw new ValidationError([' + (__err) + ']); '; } else { out += ' validate.errors = [' + (__err) + ']; return false; '; } } else { out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; '; } out += ' } '; $errSchemaPath = $currErrSchemaPath; if ($breakOnError) { $closingBraces += '}'; out += ' else { '; } } var arr1 = $schema; if (arr1) { var $sch, $i = -1, l1 = arr1.length - 1; while ($i < l1) { $sch = arr1[$i += 1]; if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) { out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { '; var $passData = $data + '[' + $i + ']'; $it.schema = $sch; $it.schemaPath = $schemaPath + '[' + $i + ']'; $it.errSchemaPath = $errSchemaPath + '/' + $i; $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true); $it.dataPathArr[$dataNxt] = $i; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } out += ' } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } } if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0 : it.util.schemaHasRules($additionalItems, it.RULES.all))) { $it.schema = $additionalItems; $it.schemaPath = it.schemaPath + '.additionalItems'; $it.errSchemaPath = it.errSchemaPath + '/additionalItems'; out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' } } '; if ($breakOnError) { out += ' if (' + ($nextValid) + ') { '; $closingBraces += '}'; } } } else if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) { $it.schema = $schema; $it.schemaPath = $schemaPath; $it.errSchemaPath = $errSchemaPath; out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { '; $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true); var $passData = $data + '[' + $idx + ']'; $it.dataPathArr[$dataNxt] = $idx; var $code = it.validate($it); $it.baseId = $currentBaseId; if (it.util.varOccurences($code, $nextData) < 2) { out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' '; } else { out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' '; } if ($breakOnError) { out += ' if (!' + ($nextValid) + ') break; '; } out += ' }'; } if ($breakOnError) { out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {'; } return out; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/dotjs/items.js
items.js
'use strict'; module.exports = { copy: copy, checkDataType: checkDataType, checkDataTypes: checkDataTypes, coerceToTypes: coerceToTypes, toHash: toHash, getProperty: getProperty, escapeQuotes: escapeQuotes, equal: require('fast-deep-equal'), ucs2length: require('ajv/lib/compile/ucs2length'), varOccurences: varOccurences, varReplace: varReplace, schemaHasRules: schemaHasRules, schemaHasRulesExcept: schemaHasRulesExcept, schemaUnknownRules: schemaUnknownRules, toQuotedString: toQuotedString, getPathExpr: getPathExpr, getPath: getPath, getData: getData, unescapeFragment: unescapeFragment, unescapeJsonPointer: unescapeJsonPointer, escapeFragment: escapeFragment, escapeJsonPointer: escapeJsonPointer }; function copy(o, to) { to = to || {}; for (var key in o) to[key] = o[key]; return to; } function checkDataType(dataType, data, strictNumbers, negate) { var EQUAL = negate ? ' !== ' : ' === ' , AND = negate ? ' || ' : ' && ' , OK = negate ? '!' : '' , NOT = negate ? '' : '!'; switch (dataType) { case 'null': return data + EQUAL + 'null'; case 'array': return OK + 'Array.isArray(' + data + ')'; case 'object': return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))'; case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; case 'number': return '(typeof ' + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? (AND + OK + 'isFinite(' + data + ')') : '') + ')'; default: return 'typeof ' + data + EQUAL + '"' + dataType + '"'; } } function checkDataTypes(dataTypes, data, strictNumbers) { switch (dataTypes.length) { case 1: return checkDataType(dataTypes[0], data, strictNumbers, true); default: var code = ''; var types = toHash(dataTypes); if (types.array && types.object) { code = types.null ? '(': '(!' + data + ' || '; code += 'typeof ' + data + ' !== "object")'; delete types.null; delete types.array; delete types.object; } if (types.number) delete types.integer; for (var t in types) code += (code ? ' && ' : '' ) + checkDataType(t, data, strictNumbers, true); return code; } } var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]); function coerceToTypes(optionCoerceTypes, dataTypes) { if (Array.isArray(dataTypes)) { var types = []; for (var i=0; i<dataTypes.length; i++) { var t = dataTypes[i]; if (COERCE_TO_TYPES[t]) types[types.length] = t; else if (optionCoerceTypes === 'array' && t === 'array') types[types.length] = t; } if (types.length) return types; } else if (COERCE_TO_TYPES[dataTypes]) { return [dataTypes]; } else if (optionCoerceTypes === 'array' && dataTypes === 'array') { return ['array']; } } function toHash(arr) { var hash = {}; for (var i=0; i<arr.length; i++) hash[arr[i]] = true; return hash; } var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; var SINGLE_QUOTE = /'|\\/g; function getProperty(key) { return typeof key == 'number' ? '[' + key + ']' : IDENTIFIER.test(key) ? '.' + key : "['" + escapeQuotes(key) + "']"; } function escapeQuotes(str) { return str.replace(SINGLE_QUOTE, '\\$&') .replace(/\n/g, '\\n') .replace(/\r/g, '\\r') .replace(/\f/g, '\\f') .replace(/\t/g, '\\t'); } function varOccurences(str, dataVar) { dataVar += '[^0-9]'; var matches = str.match(new RegExp(dataVar, 'g')); return matches ? matches.length : 0; } function varReplace(str, dataVar, expr) { dataVar += '([^0-9])'; expr = expr.replace(/\$/g, '$$$$'); return str.replace(new RegExp(dataVar, 'g'), expr + '$1'); } function schemaHasRules(schema, rules) { if (typeof schema == 'boolean') return !schema; for (var key in schema) if (rules[key]) return true; } function schemaHasRulesExcept(schema, rules, exceptKeyword) { if (typeof schema == 'boolean') return !schema && exceptKeyword != 'not'; for (var key in schema) if (key != exceptKeyword && rules[key]) return true; } function schemaUnknownRules(schema, rules) { if (typeof schema == 'boolean') return; for (var key in schema) if (!rules[key]) return key; } function toQuotedString(str) { return '\'' + escapeQuotes(str) + '\''; } function getPathExpr(currentPath, expr, jsonPointers, isNumber) { var path = jsonPointers // false by default ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') : (isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\''); return joinPaths(currentPath, path); } function getPath(currentPath, prop, jsonPointers) { var path = jsonPointers // false by default ? toQuotedString('/' + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop)); return joinPaths(currentPath, path); } var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; function getData($data, lvl, paths) { var up, jsonPointer, data, matches; if ($data === '') return 'rootData'; if ($data[0] == '/') { if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data); jsonPointer = $data; data = 'rootData'; } else { matches = $data.match(RELATIVE_JSON_POINTER); if (!matches) throw new Error('Invalid JSON-pointer: ' + $data); up = +matches[1]; jsonPointer = matches[2]; if (jsonPointer == '#') { if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl); return paths[lvl - up]; } if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl); data = 'data' + ((lvl - up) || ''); if (!jsonPointer) return data; } var expr = data; var segments = jsonPointer.split('/'); for (var i=0; i<segments.length; i++) { var segment = segments[i]; if (segment) { data += getProperty(unescapeJsonPointer(segment)); expr += ' && ' + data; } } return expr; } function joinPaths (a, b) { if (a == '""') return b; return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1'); } function unescapeFragment(str) { return unescapeJsonPointer(decodeURIComponent(str)); } function escapeFragment(str) { return encodeURIComponent(escapeJsonPointer(str)); } function escapeJsonPointer(str) { return str.replace(/~/g, '~0').replace(/\//g, '~1'); } function unescapeJsonPointer(str) { return str.replace(/~1/g, '/').replace(/~0/g, '~'); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/util.js
util.js
'use strict'; var util = require('ajv/lib/compile/util'); var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; var DAYS = [0,31,28,31,30,31,30,31,31,30,31,30,31]; var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; // uri-template: https://tools.ietf.org/html/rfc6570 var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; // For the source: https://gist.github.com/dperini/729294 // For test cases: https://mathiasbynens.be/demo/url-regex // @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983. // var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i; var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; module.exports = formats; function formats(mode) { mode = mode == 'full' ? 'full' : 'fast'; return util.copy(formats[mode]); } formats.fast = { // date: http://tools.ietf.org/html/rfc3339#section-5.6 date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/, // date-time: http://tools.ietf.org/html/rfc3339#section-5.6 time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i, 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, 'uri-template': URITEMPLATE, url: URL, // email (sources from jsen validator): // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363 // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation') email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i, hostname: HOSTNAME, // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, // uuid: http://tools.ietf.org/html/rfc4122 uuid: UUID, // JSON-pointer: https://tools.ietf.org/html/rfc6901 // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00 'relative-json-pointer': RELATIVE_JSON_POINTER }; formats.full = { date: date, time: time, 'date-time': date_time, uri: uri, 'uri-reference': URIREF, 'uri-template': URITEMPLATE, url: URL, email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, hostname: HOSTNAME, ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/, ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i, regex: regex, uuid: UUID, 'json-pointer': JSON_POINTER, 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT, 'relative-json-pointer': RELATIVE_JSON_POINTER }; function isLeapYear(year) { // https://tools.ietf.org/html/rfc3339#appendix-C return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); } function date(str) { // full-date from http://tools.ietf.org/html/rfc3339#section-5.6 var matches = str.match(DATE); if (!matches) return false; var year = +matches[1]; var month = +matches[2]; var day = +matches[3]; return month >= 1 && month <= 12 && day >= 1 && day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]); } function time(str, full) { var matches = str.match(TIME); if (!matches) return false; var hour = matches[1]; var minute = matches[2]; var second = matches[3]; var timeZone = matches[5]; return ((hour <= 23 && minute <= 59 && second <= 59) || (hour == 23 && minute == 59 && second == 60)) && (!full || timeZone); } var DATE_TIME_SEPARATOR = /t|\s/i; function date_time(str) { // http://tools.ietf.org/html/rfc3339#section-5.6 var dateTime = str.split(DATE_TIME_SEPARATOR); return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true); } var NOT_URI_FRAGMENT = /\/|:/; function uri(str) { // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "." return NOT_URI_FRAGMENT.test(str) && URI.test(str); } var Z_ANCHOR = /[^\\]\\Z/; function regex(str) { if (Z_ANCHOR.test(str)) return false; try { new RegExp(str); return true; } catch(e) { return false; } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/formats.js
formats.js
'use strict'; var MissingRefError = require('ajv/lib/compile/error_classes').MissingRef; module.exports = compileAsync; /** * Creates validating function for passed schema with asynchronous loading of missing schemas. * `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. * @this Ajv * @param {Object} schema schema object * @param {Boolean} meta optional true to compile meta-schema; this parameter can be skipped * @param {Function} callback an optional node-style callback, it is called with 2 parameters: error (or null) and validating function. * @return {Promise} promise that resolves with a validating function. */ function compileAsync(schema, meta, callback) { /* eslint no-shadow: 0 */ /* global Promise */ /* jshint validthis: true */ var self = this; if (typeof this._opts.loadSchema != 'function') throw new Error('options.loadSchema should be a function'); if (typeof meta == 'function') { callback = meta; meta = undefined; } var p = loadMetaSchemaOf(schema).then(function () { var schemaObj = self._addSchema(schema, undefined, meta); return schemaObj.validate || _compileAsync(schemaObj); }); if (callback) { p.then( function(v) { callback(null, v); }, callback ); } return p; function loadMetaSchemaOf(sch) { var $schema = sch.$schema; return $schema && !self.getSchema($schema) ? compileAsync.call(self, { $ref: $schema }, true) : Promise.resolve(); } function _compileAsync(schemaObj) { try { return self._compile(schemaObj); } catch(e) { if (e instanceof MissingRefError) return loadMissingSchema(e); throw e; } function loadMissingSchema(e) { var ref = e.missingSchema; if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved'); var schemaPromise = self._loadingSchemas[ref]; if (!schemaPromise) { schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref); schemaPromise.then(removePromise, removePromise); } return schemaPromise.then(function (sch) { if (!added(ref)) { return loadMetaSchemaOf(sch).then(function () { if (!added(ref)) self.addSchema(sch, ref, undefined, meta); }); } }).then(function() { return _compileAsync(schemaObj); }); function removePromise() { delete self._loadingSchemas[ref]; } function added(ref) { return self._refs[ref] || self._schemas[ref]; } } } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/async.js
async.js
'use strict'; var resolve = require('ajv/lib/compile/resolve') , util = require('ajv/lib/compile/util') , errorClasses = require('ajv/lib/compile/error_classes') , stableStringify = require('fast-json-stable-stringify'); var validateGenerator = require('ajv/lib/dotjs/validate'); /** * Functions below are used inside compiled validations function */ var ucs2length = util.ucs2length; var equal = require('fast-deep-equal'); // this error is thrown by async schemas to return validation errors via exception var ValidationError = errorClasses.Validation; module.exports = compile; /** * Compiles schema to validation function * @this Ajv * @param {Object} schema schema object * @param {Object} root object with information about the root schema for this schema * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution * @param {String} baseId base ID for IDs in the schema * @return {Function} validation function */ function compile(schema, root, localRefs, baseId) { /* jshint validthis: true, evil: true */ /* eslint no-shadow: 0 */ var self = this , opts = this._opts , refVal = [ undefined ] , refs = {} , patterns = [] , patternsHash = {} , defaults = [] , defaultsHash = {} , customRules = []; root = root || { schema: schema, refVal: refVal, refs: refs }; var c = checkCompiling.call(this, schema, root, baseId); var compilation = this._compilations[c.index]; if (c.compiling) return (compilation.callValidate = callValidate); var formats = this._formats; var RULES = this.RULES; try { var v = localCompile(schema, root, localRefs, baseId); compilation.validate = v; var cv = compilation.callValidate; if (cv) { cv.schema = v.schema; cv.errors = null; cv.refs = v.refs; cv.refVal = v.refVal; cv.root = v.root; cv.$async = v.$async; if (opts.sourceCode) cv.source = v.source; } return v; } finally { endCompiling.call(this, schema, root, baseId); } /* @this {*} - custom context, see passContext option */ function callValidate() { /* jshint validthis: true */ var validate = compilation.validate; var result = validate.apply(this, arguments); callValidate.errors = validate.errors; return result; } function localCompile(_schema, _root, localRefs, baseId) { var isRoot = !_root || (_root && _root.schema == _schema); if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId); var $async = _schema.$async === true; var sourceCode = validateGenerator({ isTop: true, schema: _schema, isRoot: isRoot, baseId: baseId, root: _root, schemaPath: '', errSchemaPath: '#', errorPath: '""', MissingRefError: errorClasses.MissingRef, RULES: RULES, validate: validateGenerator, util: util, resolve: resolve, resolveRef: resolveRef, usePattern: usePattern, useDefault: useDefault, useCustomRule: useCustomRule, opts: opts, formats: formats, logger: self.logger, self: self }); sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode; if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema); // console.log('\n\n\n *** \n', JSON.stringify(sourceCode)); var validate; try { var makeValidate = new Function( 'self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode ); validate = makeValidate( self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError ); refVal[0] = validate; } catch(e) { self.logger.error('Error compiling schema, function code:', sourceCode); throw e; } validate.schema = _schema; validate.errors = null; validate.refs = refs; validate.refVal = refVal; validate.root = isRoot ? validate : _root; if ($async) validate.$async = true; if (opts.sourceCode === true) { validate.source = { code: sourceCode, patterns: patterns, defaults: defaults }; } return validate; } function resolveRef(baseId, ref, isRoot) { ref = resolve.url(baseId, ref); var refIndex = refs[ref]; var _refVal, refCode; if (refIndex !== undefined) { _refVal = refVal[refIndex]; refCode = 'refVal[' + refIndex + ']'; return resolvedRef(_refVal, refCode); } if (!isRoot && root.refs) { var rootRefId = root.refs[ref]; if (rootRefId !== undefined) { _refVal = root.refVal[rootRefId]; refCode = addLocalRef(ref, _refVal); return resolvedRef(_refVal, refCode); } } refCode = addLocalRef(ref); var v = resolve.call(self, localCompile, root, ref); if (v === undefined) { var localSchema = localRefs && localRefs[ref]; if (localSchema) { v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId); } } if (v === undefined) { removeLocalRef(ref); } else { replaceLocalRef(ref, v); return resolvedRef(v, refCode); } } function addLocalRef(ref, v) { var refId = refVal.length; refVal[refId] = v; refs[ref] = refId; return 'refVal' + refId; } function removeLocalRef(ref) { delete refs[ref]; } function replaceLocalRef(ref, v) { var refId = refs[ref]; refVal[refId] = v; } function resolvedRef(refVal, code) { return typeof refVal == 'object' || typeof refVal == 'boolean' ? { code: code, schema: refVal, inline: true } : { code: code, $async: refVal && !!refVal.$async }; } function usePattern(regexStr) { var index = patternsHash[regexStr]; if (index === undefined) { index = patternsHash[regexStr] = patterns.length; patterns[index] = regexStr; } return 'pattern' + index; } function useDefault(value) { switch (typeof value) { case 'boolean': case 'number': return '' + value; case 'string': return util.toQuotedString(value); case 'object': if (value === null) return 'null'; var valueStr = stableStringify(value); var index = defaultsHash[valueStr]; if (index === undefined) { index = defaultsHash[valueStr] = defaults.length; defaults[index] = value; } return 'default' + index; } } function useCustomRule(rule, schema, parentSchema, it) { if (self._opts.validateSchema !== false) { var deps = rule.definition.dependencies; if (deps && !deps.every(function(keyword) { return Object.prototype.hasOwnProperty.call(parentSchema, keyword); })) throw new Error('parent schema must have all required keywords: ' + deps.join(',')); var validateSchema = rule.definition.validateSchema; if (validateSchema) { var valid = validateSchema(schema); if (!valid) { var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors); if (self._opts.validateSchema == 'log') self.logger.error(message); else throw new Error(message); } } } var compile = rule.definition.compile , inline = rule.definition.inline , macro = rule.definition.macro; var validate; if (compile) { validate = compile.call(self, schema, parentSchema, it); } else if (macro) { validate = macro.call(self, schema, parentSchema, it); if (opts.validateSchema !== false) self.validateSchema(validate, true); } else if (inline) { validate = inline.call(self, it, rule.keyword, schema, parentSchema); } else { validate = rule.definition.validate; if (!validate) return; } if (validate === undefined) throw new Error('custom keyword "' + rule.keyword + '"failed to compile'); var index = customRules.length; customRules[index] = validate; return { code: 'customRule' + index, validate: validate }; } } /** * Checks if the schema is currently compiled * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean) */ function checkCompiling(schema, root, baseId) { /* jshint validthis: true */ var index = compIndex.call(this, schema, root, baseId); if (index >= 0) return { index: index, compiling: true }; index = this._compilations.length; this._compilations[index] = { schema: schema, root: root, baseId: baseId }; return { index: index, compiling: false }; } /** * Removes the schema from the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID */ function endCompiling(schema, root, baseId) { /* jshint validthis: true */ var i = compIndex.call(this, schema, root, baseId); if (i >= 0) this._compilations.splice(i, 1); } /** * Index of schema compilation in the currently compiled list * @this Ajv * @param {Object} schema schema to compile * @param {Object} root root object * @param {String} baseId base schema ID * @return {Integer} compilation index */ function compIndex(schema, root, baseId) { /* jshint validthis: true */ for (var i=0; i<this._compilations.length; i++) { var c = this._compilations[i]; if (c.schema == schema && c.root == root && c.baseId == baseId) return i; } return -1; } function patternCode(i, patterns) { return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');'; } function defaultCode(i) { return 'var default' + i + ' = defaults[' + i + '];'; } function refValCode(i, refVal) { return refVal[i] === undefined ? '' : 'var refVal' + i + ' = refVal[' + i + '];'; } function customRuleCode(i) { return 'var customRule' + i + ' = customRules[' + i + '];'; } function vars(arr, statement) { if (!arr.length) return ''; var code = ''; for (var i=0; i<arr.length; i++) code += statement(i, arr); return code; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/index.js
index.js
'use strict'; var ruleModules = require('ajv/lib/dotjs') , toHash = require('ajv/lib/compile/util').toHash; module.exports = function rules() { var RULES = [ { type: 'number', rules: [ { 'maximum': ['exclusiveMaximum'] }, { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] }, { type: 'string', rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] }, { type: 'array', rules: [ 'maxItems', 'minItems', 'items', 'contains', 'uniqueItems' ] }, { type: 'object', rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames', { 'properties': ['additionalProperties', 'patternProperties'] } ] }, { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf', 'if' ] } ]; var ALL = [ 'type', '$comment' ]; var KEYWORDS = [ '$schema', '$id', 'id', '$data', '$async', 'title', 'description', 'default', 'definitions', 'examples', 'readOnly', 'writeOnly', 'contentMediaType', 'contentEncoding', 'additionalItems', 'then', 'else' ]; var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ]; RULES.all = toHash(ALL); RULES.types = toHash(TYPES); RULES.forEach(function (group) { group.rules = group.rules.map(function (keyword) { var implKeywords; if (typeof keyword == 'object') { var key = Object.keys(keyword)[0]; implKeywords = keyword[key]; keyword = key; implKeywords.forEach(function (k) { ALL.push(k); RULES.all[k] = true; }); } ALL.push(keyword); var rule = RULES.all[keyword] = { keyword: keyword, code: ruleModules[keyword], implements: implKeywords }; return rule; }); RULES.all.$comment = { keyword: '$comment', code: ruleModules.$comment }; if (group.type) RULES.types[group.type] = group; }); RULES.keywords = toHash(ALL.concat(KEYWORDS)); RULES.custom = {}; return RULES; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/rules.js
rules.js
'use strict'; var URI = require('uri-js') , equal = require('fast-deep-equal') , util = require('ajv/lib/compile/util') , SchemaObject = require('ajv/lib/compile/schema_obj') , traverse = require('json-schema-traverse'); module.exports = resolve; resolve.normalizeId = normalizeId; resolve.fullPath = getFullPath; resolve.url = resolveUrl; resolve.ids = resolveIds; resolve.inlineRef = inlineRef; resolve.schema = resolveSchema; /** * [resolve and compile the references ($ref)] * @this Ajv * @param {Function} compile reference to schema compilation funciton (localCompile) * @param {Object} root object with information about the root schema for the current schema * @param {String} ref reference to resolve * @return {Object|Function} schema object (if the schema can be inlined) or validation function */ function resolve(compile, root, ref) { /* jshint validthis: true */ var refVal = this._refs[ref]; if (typeof refVal == 'string') { if (this._refs[refVal]) refVal = this._refs[refVal]; else return resolve.call(this, compile, root, refVal); } refVal = refVal || this._schemas[ref]; if (refVal instanceof SchemaObject) { return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal); } var res = resolveSchema.call(this, root, ref); var schema, v, baseId; if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } if (schema instanceof SchemaObject) { v = schema.validate || compile.call(this, schema.schema, root, undefined, baseId); } else if (schema !== undefined) { v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, undefined, baseId); } return v; } /** * Resolve schema, its root and baseId * @this Ajv * @param {Object} root root object with properties schema, refVal, refs * @param {String} ref reference to resolve * @return {Object} object with properties schema, root, baseId */ function resolveSchema(root, ref) { /* jshint validthis: true */ var p = URI.parse(ref) , refPath = _getFullPath(p) , baseId = getFullPath(this._getId(root.schema)); if (Object.keys(root.schema).length === 0 || refPath !== baseId) { var id = normalizeId(refPath); var refVal = this._refs[id]; if (typeof refVal == 'string') { return resolveRecursive.call(this, root, refVal, p); } else if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); root = refVal; } else { refVal = this._schemas[id]; if (refVal instanceof SchemaObject) { if (!refVal.validate) this._compile(refVal); if (id == normalizeId(ref)) return { schema: refVal, root: root, baseId: baseId }; root = refVal; } else { return; } } if (!root.schema) return; baseId = getFullPath(this._getId(root.schema)); } return getJsonPointer.call(this, p, baseId, root.schema, root); } /* @this Ajv */ function resolveRecursive(root, ref, parsedRef) { /* jshint validthis: true */ var res = resolveSchema.call(this, root, ref); if (res) { var schema = res.schema; var baseId = res.baseId; root = res.root; var id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); return getJsonPointer.call(this, parsedRef, baseId, schema, root); } } var PREVENT_SCOPE_CHANGE = util.toHash(['properties', 'patternProperties', 'enum', 'dependencies', 'definitions']); /* @this Ajv */ function getJsonPointer(parsedRef, baseId, schema, root) { /* jshint validthis: true */ parsedRef.fragment = parsedRef.fragment || ''; if (parsedRef.fragment.slice(0,1) != '/') return; var parts = parsedRef.fragment.split('/'); for (var i = 1; i < parts.length; i++) { var part = parts[i]; if (part) { part = util.unescapeFragment(part); schema = schema[part]; if (schema === undefined) break; var id; if (!PREVENT_SCOPE_CHANGE[part]) { id = this._getId(schema); if (id) baseId = resolveUrl(baseId, id); if (schema.$ref) { var $ref = resolveUrl(baseId, schema.$ref); var res = resolveSchema.call(this, root, $ref); if (res) { schema = res.schema; root = res.root; baseId = res.baseId; } } } } } if (schema !== undefined && schema !== root.schema) return { schema: schema, root: root, baseId: baseId }; } var SIMPLE_INLINED = util.toHash([ 'type', 'format', 'pattern', 'maxLength', 'minLength', 'maxProperties', 'minProperties', 'maxItems', 'minItems', 'maximum', 'minimum', 'uniqueItems', 'multipleOf', 'required', 'enum' ]); function inlineRef(schema, limit) { if (limit === false) return false; if (limit === undefined || limit === true) return checkNoRef(schema); else if (limit) return countKeys(schema) <= limit; } function checkNoRef(schema) { var item; if (Array.isArray(schema)) { for (var i=0; i<schema.length; i++) { item = schema[i]; if (typeof item == 'object' && !checkNoRef(item)) return false; } } else { for (var key in schema) { if (key == '$ref') return false; item = schema[key]; if (typeof item == 'object' && !checkNoRef(item)) return false; } } return true; } function countKeys(schema) { var count = 0, item; if (Array.isArray(schema)) { for (var i=0; i<schema.length; i++) { item = schema[i]; if (typeof item == 'object') count += countKeys(item); if (count == Infinity) return Infinity; } } else { for (var key in schema) { if (key == '$ref') return Infinity; if (SIMPLE_INLINED[key]) { count++; } else { item = schema[key]; if (typeof item == 'object') count += countKeys(item) + 1; if (count == Infinity) return Infinity; } } } return count; } function getFullPath(id, normalize) { if (normalize !== false) id = normalizeId(id); var p = URI.parse(id); return _getFullPath(p); } function _getFullPath(p) { return URI.serialize(p).split('#')[0] + '#'; } var TRAILING_SLASH_HASH = /#\/?$/; function normalizeId(id) { return id ? id.replace(TRAILING_SLASH_HASH, '') : ''; } function resolveUrl(baseId, id) { id = normalizeId(id); return URI.resolve(baseId, id); } /* @this Ajv */ function resolveIds(schema) { var schemaId = normalizeId(this._getId(schema)); var baseIds = {'': schemaId}; var fullPaths = {'': getFullPath(schemaId, false)}; var localRefs = {}; var self = this; traverse(schema, {allKeys: true}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { if (jsonPtr === '') return; var id = self._getId(sch); var baseId = baseIds[parentJsonPtr]; var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword; if (keyIndex !== undefined) fullPath += '/' + (typeof keyIndex == 'number' ? keyIndex : util.escapeFragment(keyIndex)); if (typeof id == 'string') { id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id); var refVal = self._refs[id]; if (typeof refVal == 'string') refVal = self._refs[refVal]; if (refVal && refVal.schema) { if (!equal(sch, refVal.schema)) throw new Error('id "' + id + '" resolves to more than one schema'); } else if (id != normalizeId(fullPath)) { if (id[0] == '#') { if (localRefs[id] && !equal(sch, localRefs[id])) throw new Error('id "' + id + '" resolves to more than one schema'); localRefs[id] = sch; } else { self._refs[id] = fullPath; } } } baseIds[jsonPtr] = baseId; fullPaths[jsonPtr] = fullPath; }); return localRefs; }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/ajv/lib/compile/resolve.js
resolve.js
# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] [travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg [travis-url]: https://travis-ci.org/feross/safe-buffer [npm-image]: https://img.shields.io/npm/v/safe-buffer.svg [npm-url]: https://npmjs.org/package/safe-buffer [downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg [downloads-url]: https://npmjs.org/package/safe-buffer [standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg [standard-url]: https://standardjs.com #### Safer Node.js Buffer API **Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, `Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** **Uses the built-in implementation when available.** ## install ``` npm install safe-buffer ``` ## usage The goal of this package is to provide a safe replacement for the node.js `Buffer`. It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to the top of your node.js modules: ```js var Buffer = require('safe-buffer').Buffer // Existing buffer code will continue to work without issues: new Buffer('hey', 'utf8') new Buffer([1, 2, 3], 'utf8') new Buffer(obj) new Buffer(16) // create an uninitialized buffer (potentially unsafe) // But you can use these new explicit APIs to make clear what you want: Buffer.from('hey', 'utf8') // convert from many types to a Buffer Buffer.alloc(16) // create a zero-filled buffer (safe) Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) ``` ## api ### Class Method: Buffer.from(array) <!-- YAML added: v3.0.0 --> * `array` {Array} Allocates a new `Buffer` using an `array` of octets. ```js const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); // creates a new Buffer containing ASCII bytes // ['b','u','f','f','e','r'] ``` A `TypeError` will be thrown if `array` is not an `Array`. ### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) <!-- YAML added: v5.10.0 --> * `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or a `new ArrayBuffer()` * `byteOffset` {Number} Default: `0` * `length` {Number} Default: `arrayBuffer.length - byteOffset` When passed a reference to the `.buffer` property of a `TypedArray` instance, the newly created `Buffer` will share the same allocated memory as the TypedArray. ```js const arr = new Uint16Array(2); arr[0] = 5000; arr[1] = 4000; const buf = Buffer.from(arr.buffer); // shares the memory with arr; console.log(buf); // Prints: <Buffer 88 13 a0 0f> // changing the TypedArray changes the Buffer also arr[1] = 6000; console.log(buf); // Prints: <Buffer 88 13 70 17> ``` The optional `byteOffset` and `length` arguments specify a memory range within the `arrayBuffer` that will be shared by the `Buffer`. ```js const ab = new ArrayBuffer(10); const buf = Buffer.from(ab, 0, 2); console.log(buf.length); // Prints: 2 ``` A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. ### Class Method: Buffer.from(buffer) <!-- YAML added: v3.0.0 --> * `buffer` {Buffer} Copies the passed `buffer` data onto a new `Buffer` instance. ```js const buf1 = Buffer.from('buffer'); const buf2 = Buffer.from(buf1); buf1[0] = 0x61; console.log(buf1.toString()); // 'auffer' console.log(buf2.toString()); // 'buffer' (copy is not changed) ``` A `TypeError` will be thrown if `buffer` is not a `Buffer`. ### Class Method: Buffer.from(str[, encoding]) <!-- YAML added: v5.10.0 --> * `str` {String} String to encode. * `encoding` {String} Encoding to use, Default: `'utf8'` Creates a new `Buffer` containing the given JavaScript string `str`. If provided, the `encoding` parameter identifies the character encoding. If not provided, `encoding` defaults to `'utf8'`. ```js const buf1 = Buffer.from('this is a tést'); console.log(buf1.toString()); // prints: this is a tést console.log(buf1.toString('ascii')); // prints: this is a tC)st const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); console.log(buf2.toString()); // prints: this is a tést ``` A `TypeError` will be thrown if `str` is not a string. ### Class Method: Buffer.alloc(size[, fill[, encoding]]) <!-- YAML added: v5.10.0 --> * `size` {Number} * `fill` {Value} Default: `undefined` * `encoding` {String} Default: `utf8` Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the `Buffer` will be *zero-filled*. ```js const buf = Buffer.alloc(5); console.log(buf); // <Buffer 00 00 00 00 00> ``` The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. See [`buf.fill()`][] for more information. ```js const buf = Buffer.alloc(5, 'a'); console.log(buf); // <Buffer 61 61 61 61 61> ``` If both `fill` and `encoding` are specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill, encoding)`. For example: ```js const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); console.log(buf); // <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64> ``` Calling `Buffer.alloc(size)` can be significantly slower than the alternative `Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance contents will *never contain sensitive data*. A `TypeError` will be thrown if `size` is not a number. ### Class Method: Buffer.allocUnsafe(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. ```js const buf = Buffer.allocUnsafe(5); console.log(buf); // <Buffer 78 e0 82 02 01> // (octets will be different, every time) buf.fill(0); console.log(buf); // <Buffer 00 00 00 00 00> ``` A `TypeError` will be thrown if `size` is not a number. Note that the `Buffer` module pre-allocates an internal `Buffer` instance of size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated `new Buffer(size)` constructor) only when `size` is less than or equal to `Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default value of `Buffer.poolSize` is `8192` but can be modified. Use of this pre-allocated internal memory pool is a key difference between calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The difference is subtle but can be important when an application requires the additional performance that `Buffer.allocUnsafe(size)` provides. ### Class Method: Buffer.allocUnsafeSlow(size) <!-- YAML added: v5.10.0 --> * `size` {Number} Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The `size` must be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will be created if a `size` less than or equal to 0 is specified. The underlying memory for `Buffer` instances created in this way is *not initialized*. The contents of the newly created `Buffer` are unknown and *may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such `Buffer` instances to zeroes. When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, allocations under 4KB are, by default, sliced from a single pre-allocated `Buffer`. This allows applications to avoid the garbage collection overhead of creating many individually allocated Buffers. This approach improves both performance and memory usage by eliminating the need to track and cleanup as many `Persistent` objects. However, in the case where a developer may need to retain a small chunk of memory from a pool for an indeterminate amount of time, it may be appropriate to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then copy out the relevant bits. ```js // need to keep around a few small chunks of memory const store = []; socket.on('readable', () => { const data = socket.read(); // allocate for retained data const sb = Buffer.allocUnsafeSlow(10); // copy the data into the new allocation data.copy(sb, 0, 0, 10); store.push(sb); }); ``` Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* a developer has observed undue memory retention in their applications. A `TypeError` will be thrown if `size` is not a number. ### All the Rest The rest of the `Buffer` API is exactly the same as in node.js. [See the docs](https://nodejs.org/api/buffer.html). ## Related links - [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) - [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) ## Why is `Buffer` unsafe? Today, the node.js `Buffer` constructor is overloaded to handle many different argument types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), `ArrayBuffer`, and also `Number`. The API is optimized for convenience: you can throw any type at it, and it will try to do what you want. Because the Buffer constructor is so powerful, you often see code like this: ```js // Convert UTF-8 strings to hex function toHex (str) { return new Buffer(str).toString('hex') } ``` ***But what happens if `toHex` is called with a `Number` argument?*** ### Remote Memory Disclosure If an attacker can make your program call the `Buffer` constructor with a `Number` argument, then they can make it allocate uninitialized memory from the node.js process. This could potentially disclose TLS private keys, user data, or database passwords. When the `Buffer` constructor is passed a `Number` argument, it returns an **UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like this, you **MUST** overwrite the contents before returning it to the user. From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): > `new Buffer(size)` > > - `size` Number > > The underlying memory for `Buffer` instances created in this way is not initialized. > **The contents of a newly created `Buffer` are unknown and could contain sensitive > data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. (Emphasis our own.) Whenever the programmer intended to create an uninitialized `Buffer` you often see code like this: ```js var buf = new Buffer(16) // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### Would this ever be a problem in real code? Yes. It's surprisingly common to forget to check the type of your variables in a dynamically-typed language like JavaScript. Usually the consequences of assuming the wrong type is that your program crashes with an uncaught exception. But the failure mode for forgetting to check the type of arguments to the `Buffer` constructor is more catastrophic. Here's an example of a vulnerable service that takes a JSON payload and converts it to hex: ```js // Take a JSON payload {str: "some string"} and convert it to hex var server = http.createServer(function (req, res) { var data = '' req.setEncoding('utf8') req.on('data', function (chunk) { data += chunk }) req.on('end', function () { var body = JSON.parse(data) res.end(new Buffer(body.str).toString('hex')) }) }) server.listen(8080) ``` In this example, an http client just has to send: ```json { "str": 1000 } ``` and it will get back 1,000 bytes of uninitialized memory from the server. This is a very serious bug. It's similar in severity to the [the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process memory by remote attackers. ### Which real-world packages were vulnerable? #### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) [Mathias Buus](https://github.com/mafintosh) and I ([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get them to reveal 20 bytes at a time of uninitialized memory from the node.js process. Here's [the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) that fixed it. We released a new fixed version, created a [Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all vulnerable versions on npm so users will get a warning to upgrade to a newer version. #### [`ws`](https://www.npmjs.com/package/ws) That got us wondering if there were other vulnerable packages. Sure enough, within a short period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the most popular WebSocket implementation in node.js. If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as expected, then uninitialized server memory would be disclosed to the remote peer. These were the vulnerable methods: ```js socket.send(number) socket.ping(number) socket.pong(number) ``` Here's a vulnerable socket server with some echo functionality: ```js server.on('connection', function (socket) { socket.on('message', function (message) { message = JSON.parse(message) if (message.type === 'echo') { socket.send(message.data) // send back the user's message } }) }) ``` `socket.send(number)` called on the server, will disclose server memory. Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue was fixed, with a more detailed explanation. Props to [Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the [Node Security Project disclosure](https://nodesecurity.io/advisories/67). ### What's the solution? It's important that node.js offers a fast way to get memory otherwise performance-critical applications would needlessly get a lot slower. But we need a better way to *signal our intent* as programmers. **When we want uninitialized memory, we should request it explicitly.** Sensitive functionality should not be packed into a developer-friendly API that loosely accepts many different types. This type of API encourages the lazy practice of passing variables in without checking the type very carefully. #### A new API: `Buffer.allocUnsafe(number)` The functionality of creating buffers with uninitialized memory should be part of another API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that frequently gets user input of all sorts of different types passed into it. ```js var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! // Immediately overwrite the uninitialized buffer with data from another buffer for (var i = 0; i < buf.length; i++) { buf[i] = otherBuf[i] } ``` ### How do we fix node.js core? We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as `semver-major`) which defends against one case: ```js var str = 16 new Buffer(str, 'utf8') ``` In this situation, it's implied that the programmer intended the first argument to be a string, since they passed an encoding as a second argument. Today, node.js will allocate uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not what the programmer intended. But this is only a partial solution, since if the programmer does `new Buffer(variable)` (without an `encoding` parameter) there's no way to know what they intended. If `variable` is sometimes a number, then uninitialized memory will sometimes be returned. ### What's the real long-term fix? We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when we need uninitialized memory. But that would break 1000s of packages. ~~We believe the best solution is to:~~ ~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ ~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ #### Update We now support adding three new APIs: - `Buffer.from(value)` - convert from any type to a buffer - `Buffer.alloc(size)` - create a zero-filled buffer - `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size This solves the core problem that affected `ws` and `bittorrent-dht` which is `Buffer(variable)` getting tricked into taking a number argument. This way, existing code continues working and the impact on the npm ecosystem will be minimal. Over time, npm maintainers can migrate performance-critical code to use `Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. ### Conclusion We think there's a serious design issue with the `Buffer` API as it exists today. It promotes insecure software by putting high-risk functionality into a convenient API with friendly "developer ergonomics". This wasn't merely a theoretical exercise because we found the issue in some of the most popular npm packages. Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of `buffer`. ```js var Buffer = require('safe-buffer').Buffer ``` Eventually, we hope that node.js core can switch to this new, safer behavior. We believe the impact on the ecosystem would be minimal since it's not a breaking change. Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while older, insecure packages would magically become safe from this attack vector. ## links - [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) - [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) - [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) ## credit The original issues in `bittorrent-dht` ([disclosure](https://nodesecurity.io/advisories/68)) and `ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by [Mathias Buus](https://github.com/mafintosh) and [Feross Aboukhadijeh](http://feross.org/). Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues and for his work running the [Node Security Project](https://nodesecurity.io/). Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and auditing the code. ## license MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org)
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/safe-buffer/README.md
README.md
declare module "safe-buffer" { export class Buffer { length: number write(string: string, offset?: number, length?: number, encoding?: string): number; toString(encoding?: string, start?: number, end?: number): string; toJSON(): { type: 'Buffer', data: any[] }; equals(otherBuffer: Buffer): boolean; compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; slice(start?: number, end?: number): Buffer; writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; readUInt8(offset: number, noAssert?: boolean): number; readUInt16LE(offset: number, noAssert?: boolean): number; readUInt16BE(offset: number, noAssert?: boolean): number; readUInt32LE(offset: number, noAssert?: boolean): number; readUInt32BE(offset: number, noAssert?: boolean): number; readInt8(offset: number, noAssert?: boolean): number; readInt16LE(offset: number, noAssert?: boolean): number; readInt16BE(offset: number, noAssert?: boolean): number; readInt32LE(offset: number, noAssert?: boolean): number; readInt32BE(offset: number, noAssert?: boolean): number; readFloatLE(offset: number, noAssert?: boolean): number; readFloatBE(offset: number, noAssert?: boolean): number; readDoubleLE(offset: number, noAssert?: boolean): number; readDoubleBE(offset: number, noAssert?: boolean): number; swap16(): Buffer; swap32(): Buffer; swap64(): Buffer; writeUInt8(value: number, offset: number, noAssert?: boolean): number; writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; writeInt8(value: number, offset: number, noAssert?: boolean): number; writeInt16LE(value: number, offset: number, noAssert?: boolean): number; writeInt16BE(value: number, offset: number, noAssert?: boolean): number; writeInt32LE(value: number, offset: number, noAssert?: boolean): number; writeInt32BE(value: number, offset: number, noAssert?: boolean): number; writeFloatLE(value: number, offset: number, noAssert?: boolean): number; writeFloatBE(value: number, offset: number, noAssert?: boolean): number; writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; fill(value: any, offset?: number, end?: number): this; indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; /** * Allocates a new buffer containing the given {str}. * * @param str String to store in buffer. * @param encoding encoding to use, optional. Default is 'utf8' */ constructor (str: string, encoding?: string); /** * Allocates a new buffer of {size} octets. * * @param size count of octets to allocate. */ constructor (size: number); /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ constructor (array: Uint8Array); /** * Produces a Buffer backed by the same allocated memory as * the given {ArrayBuffer}. * * * @param arrayBuffer The ArrayBuffer with which to share memory. */ constructor (arrayBuffer: ArrayBuffer); /** * Allocates a new buffer containing the given {array} of octets. * * @param array The octets to store. */ constructor (array: any[]); /** * Copies the passed {buffer} data onto a new {Buffer} instance. * * @param buffer The buffer to copy. */ constructor (buffer: Buffer); prototype: Buffer; /** * Allocates a new Buffer using an {array} of octets. * * @param array */ static from(array: any[]): Buffer; /** * When passed a reference to the .buffer property of a TypedArray instance, * the newly created Buffer will share the same allocated memory as the TypedArray. * The optional {byteOffset} and {length} arguments specify a memory range * within the {arrayBuffer} that will be shared by the Buffer. * * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() * @param byteOffset * @param length */ static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; /** * Copies the passed {buffer} data onto a new Buffer instance. * * @param buffer */ static from(buffer: Buffer): Buffer; /** * Creates a new Buffer containing the given JavaScript string {str}. * If provided, the {encoding} parameter identifies the character encoding. * If not provided, {encoding} defaults to 'utf8'. * * @param str */ static from(str: string, encoding?: string): Buffer; /** * Returns true if {obj} is a Buffer * * @param obj object to test. */ static isBuffer(obj: any): obj is Buffer; /** * Returns true if {encoding} is a valid encoding argument. * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' * * @param encoding string to test. */ static isEncoding(encoding: string): boolean; /** * Gives the actual byte length of a string. encoding defaults to 'utf8'. * This is not the same as String.prototype.length since that returns the number of characters in a string. * * @param string string to test. * @param encoding encoding used to evaluate (defaults to 'utf8') */ static byteLength(string: string, encoding?: string): number; /** * Returns a buffer which is the result of concatenating all the buffers in the list together. * * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. * If the list has exactly one item, then the first item of the list is returned. * If the list has more than one item, then a new Buffer is created. * * @param list An array of Buffer objects to concatenate * @param totalLength Total length of the buffers when concatenated. * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. */ static concat(list: Buffer[], totalLength?: number): Buffer; /** * The same as buf1.compare(buf2). */ static compare(buf1: Buffer, buf2: Buffer): number; /** * Allocates a new buffer of {size} octets. * * @param size count of octets to allocate. * @param fill if specified, buffer will be initialized by calling buf.fill(fill). * If parameter is omitted, buffer will be filled with zeros. * @param encoding encoding used for call to buf.fill while initalizing */ static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; /** * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents * of the newly created Buffer are unknown and may contain sensitive data. * * @param size count of octets to allocate */ static allocUnsafe(size: number): Buffer; /** * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents * of the newly created Buffer are unknown and may contain sensitive data. * * @param size count of octets to allocate */ static allocUnsafeSlow(size: number): Buffer; } }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/safe-buffer/index.d.ts
index.d.ts
var assert = require('assert'); var Stream = require('stream').Stream; var util = require('util'); ///--- Globals /* JSSTYLED */ var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/; ///--- Internal function _capitalize(str) { return (str.charAt(0).toUpperCase() + str.slice(1)); } function _toss(name, expected, oper, arg, actual) { throw new assert.AssertionError({ message: util.format('%s (%s) is required', name, expected), actual: (actual === undefined) ? typeof (arg) : actual(arg), expected: expected, operator: oper || '===', stackStartFunction: _toss.caller }); } function _getClass(arg) { return (Object.prototype.toString.call(arg).slice(8, -1)); } function noop() { // Why even bother with asserts? } ///--- Exports var types = { bool: { check: function (arg) { return typeof (arg) === 'boolean'; } }, func: { check: function (arg) { return typeof (arg) === 'function'; } }, string: { check: function (arg) { return typeof (arg) === 'string'; } }, object: { check: function (arg) { return typeof (arg) === 'object' && arg !== null; } }, number: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg); } }, finite: { check: function (arg) { return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg); } }, buffer: { check: function (arg) { return Buffer.isBuffer(arg); }, operator: 'Buffer.isBuffer' }, array: { check: function (arg) { return Array.isArray(arg); }, operator: 'Array.isArray' }, stream: { check: function (arg) { return arg instanceof Stream; }, operator: 'instanceof', actual: _getClass }, date: { check: function (arg) { return arg instanceof Date; }, operator: 'instanceof', actual: _getClass }, regexp: { check: function (arg) { return arg instanceof RegExp; }, operator: 'instanceof', actual: _getClass }, uuid: { check: function (arg) { return typeof (arg) === 'string' && UUID_REGEXP.test(arg); }, operator: 'isUUID' } }; function _setExports(ndebug) { var keys = Object.keys(types); var out; /* re-export standard assert */ if (process.env.NODE_NDEBUG) { out = noop; } else { out = function (arg, msg) { if (!arg) { _toss(msg, 'true', arg); } }; } /* standard checks */ keys.forEach(function (k) { if (ndebug) { out[k] = noop; return; } var type = types[k]; out[k] = function (arg, msg) { if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* optional checks */ keys.forEach(function (k) { var name = 'optional' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!type.check(arg)) { _toss(msg, k, type.operator, arg, type.actual); } }; }); /* arrayOf checks */ keys.forEach(function (k) { var name = 'arrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* optionalArrayOf checks */ keys.forEach(function (k) { var name = 'optionalArrayOf' + _capitalize(k); if (ndebug) { out[name] = noop; return; } var type = types[k]; var expected = '[' + k + ']'; out[name] = function (arg, msg) { if (arg === undefined || arg === null) { return; } if (!Array.isArray(arg)) { _toss(msg, expected, type.operator, arg, type.actual); } var i; for (i = 0; i < arg.length; i++) { if (!type.check(arg[i])) { _toss(msg, expected, type.operator, arg, type.actual); } } }; }); /* re-export built-in assertions */ Object.keys(assert).forEach(function (k) { if (k === 'AssertionError') { out[k] = assert[k]; return; } if (ndebug) { out[k] = noop; return; } out[k] = assert[k]; }); /* export ourselves (for unit tests _only_) */ out._setExports = _setExports; return out; } module.exports = _setExports(process.env.NODE_NDEBUG);
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/assert-plus/assert.js
assert.js
# assert-plus This library is a super small wrapper over node's assert module that has two things: (1) the ability to disable assertions with the environment variable NODE\_NDEBUG, and (2) some API wrappers for argument testing. Like `assert.string(myArg, 'myArg')`. As a simple example, most of my code looks like this: ```javascript var assert = require('assert-plus'); function fooAccount(options, callback) { assert.object(options, 'options'); assert.number(options.id, 'options.id'); assert.bool(options.isManager, 'options.isManager'); assert.string(options.name, 'options.name'); assert.arrayOfString(options.email, 'options.email'); assert.func(callback, 'callback'); // Do stuff callback(null, {}); } ``` # API All methods that *aren't* part of node's core assert API are simply assumed to take an argument, and then a string 'name' that's not a message; `AssertionError` will be thrown if the assertion fails with a message like: AssertionError: foo (string) is required at test (/home/mark/work/foo/foo.js:3:9) at Object.<anonymous> (/home/mark/work/foo/foo.js:15:1) at Module._compile (module.js:446:26) at Object..js (module.js:464:10) at Module.load (module.js:353:31) at Function._load (module.js:311:12) at Array.0 (module.js:484:10) at EventEmitter._tickCallback (node.js:190:38) from: ```javascript function test(foo) { assert.string(foo, 'foo'); } ``` There you go. You can check that arrays are of a homogeneous type with `Arrayof$Type`: ```javascript function test(foo) { assert.arrayOfString(foo, 'foo'); } ``` You can assert IFF an argument is not `undefined` (i.e., an optional arg): ```javascript assert.optionalString(foo, 'foo'); ``` Lastly, you can opt-out of assertion checking altogether by setting the environment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have lots of assertions, and don't want to pay `typeof ()` taxes to v8 in production. Be advised: The standard functions re-exported from `assert` are also disabled in assert-plus if NDEBUG is specified. Using them directly from the `assert` module avoids this behavior. The complete list of APIs is: * assert.array * assert.bool * assert.buffer * assert.func * assert.number * assert.finite * assert.object * assert.string * assert.stream * assert.date * assert.regexp * assert.uuid * assert.arrayOfArray * assert.arrayOfBool * assert.arrayOfBuffer * assert.arrayOfFunc * assert.arrayOfNumber * assert.arrayOfFinite * assert.arrayOfObject * assert.arrayOfString * assert.arrayOfStream * assert.arrayOfDate * assert.arrayOfRegexp * assert.arrayOfUuid * assert.optionalArray * assert.optionalBool * assert.optionalBuffer * assert.optionalFunc * assert.optionalNumber * assert.optionalFinite * assert.optionalObject * assert.optionalString * assert.optionalStream * assert.optionalDate * assert.optionalRegexp * assert.optionalUuid * assert.optionalArrayOfArray * assert.optionalArrayOfBool * assert.optionalArrayOfBuffer * assert.optionalArrayOfFunc * assert.optionalArrayOfNumber * assert.optionalArrayOfFinite * assert.optionalArrayOfObject * assert.optionalArrayOfString * assert.optionalArrayOfStream * assert.optionalArrayOfDate * assert.optionalArrayOfRegexp * assert.optionalArrayOfUuid * assert.AssertionError * assert.fail * assert.ok * assert.equal * assert.notEqual * assert.deepEqual * assert.notDeepEqual * assert.strictEqual * assert.notStrictEqual * assert.throws * assert.doesNotThrow * assert.ifError # Installation npm install assert-plus ## License The MIT License (MIT) Copyright (c) 2012 Mark Cavage 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. ## Bugs See <https://github.com/mcavage/node-assert-plus/issues>.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/assert-plus/README.md
README.md
[![NPM version](https://img.shields.io/npm/v/esprima.svg)](https://www.npmjs.com/package/esprima) [![npm download](https://img.shields.io/npm/dm/esprima.svg)](https://www.npmjs.com/package/esprima) [![Build Status](https://img.shields.io/travis/jquery/esprima/master.svg)](https://travis-ci.org/jquery/esprima) [![Coverage Status](https://img.shields.io/codecov/c/github/jquery/esprima/master.svg)](https://codecov.io/github/jquery/esprima) **Esprima** ([esprima.org](http://esprima.org), BSD license) is a high performance, standard-compliant [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) parser written in ECMAScript (also popularly known as [JavaScript](https://en.wikipedia.org/wiki/JavaScript)). Esprima is created and maintained by [Ariya Hidayat](https://twitter.com/ariyahidayat), with the help of [many contributors](https://github.com/jquery/esprima/contributors). ### Features - Full support for ECMAScript 2017 ([ECMA-262 8th Edition](http://www.ecma-international.org/publications/standards/Ecma-262.htm)) - Sensible [syntax tree format](https://github.com/estree/estree/blob/master/es5.md) as standardized by [ESTree project](https://github.com/estree/estree) - Experimental support for [JSX](https://facebook.github.io/jsx/), a syntax extension for [React](https://facebook.github.io/react/) - Optional tracking of syntax node location (index-based and line-column) - [Heavily tested](http://esprima.org/test/ci.html) (~1500 [unit tests](https://github.com/jquery/esprima/tree/master/test/fixtures) with [full code coverage](https://codecov.io/github/jquery/esprima)) ### API Esprima can be used to perform [lexical analysis](https://en.wikipedia.org/wiki/Lexical_analysis) (tokenization) or [syntactic analysis](https://en.wikipedia.org/wiki/Parsing) (parsing) of a JavaScript program. A simple example on Node.js REPL: ```javascript > var esprima = require('esprima'); > var program = 'const answer = 42'; > esprima.tokenize(program); [ { type: 'Keyword', value: 'const' }, { type: 'Identifier', value: 'answer' }, { type: 'Punctuator', value: '=' }, { type: 'Numeric', value: '42' } ] > esprima.parseScript(program); { type: 'Program', body: [ { type: 'VariableDeclaration', declarations: [Object], kind: 'const' } ], sourceType: 'script' } ``` For more information, please read the [complete documentation](http://esprima.org/doc).
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esprima/README.md
README.md
/*jslint sloppy:true node:true rhino:true */ var fs, esprima, fname, forceFile, content, options, syntax; if (typeof require === 'function') { fs = require('fs'); try { esprima = require('esprima'); } catch (e) { esprima = require('esprima'); } } else if (typeof load === 'function') { try { load('esprima.js'); } catch (e) { load('../esprima.js'); } } // Shims to Node.js objects when running under Rhino. if (typeof console === 'undefined' && typeof process === 'undefined') { console = { log: print }; fs = { readFileSync: readFile }; process = { argv: arguments, exit: quit }; process.argv.unshift('esparse.js'); process.argv.unshift('rhino'); } function showUsage() { console.log('Usage:'); console.log(' esparse [options] [file.js]'); console.log(); console.log('Available options:'); console.log(); console.log(' --comment Gather all line and block comments in an array'); console.log(' --loc Include line-column location info for each syntax node'); console.log(' --range Include index-based range for each syntax node'); console.log(' --raw Display the raw value of literals'); console.log(' --tokens List all tokens in an array'); console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)'); console.log(' -v, --version Shows program version'); console.log(); process.exit(1); } options = {}; process.argv.splice(2).forEach(function (entry) { if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { if (typeof fname === 'string') { console.log('Error: more than one input file.'); process.exit(1); } else { fname = entry; } } else if (entry === '-h' || entry === '--help') { showUsage(); } else if (entry === '-v' || entry === '--version') { console.log('ECMAScript Parser (using Esprima version', esprima.version, ')'); console.log(); process.exit(0); } else if (entry === '--comment') { options.comment = true; } else if (entry === '--loc') { options.loc = true; } else if (entry === '--range') { options.range = true; } else if (entry === '--raw') { options.raw = true; } else if (entry === '--tokens') { options.tokens = true; } else if (entry === '--tolerant') { options.tolerant = true; } else if (entry === '--') { forceFile = true; } else { console.log('Error: unknown option ' + entry + '.'); process.exit(1); } }); // Special handling for regular expression literal since we need to // convert it to a string literal, otherwise it will be decoded // as object "{}" and the regular expression would be lost. function adjustRegexLiteral(key, value) { if (key === 'value' && value instanceof RegExp) { value = value.toString(); } return value; } function run(content) { syntax = esprima.parse(content, options); console.log(JSON.stringify(syntax, adjustRegexLiteral, 4)); } try { if (fname && (fname !== '-' || forceFile)) { run(fs.readFileSync(fname, 'utf-8')); } else { var content = ''; process.stdin.resume(); process.stdin.on('data', function(chunk) { content += chunk; }); process.stdin.on('end', function() { run(content); }); } } catch (e) { console.log('Error: ' + e.message); process.exit(1); }
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esprima/bin/esparse.js
esparse.js
/*jslint sloppy:true plusplus:true node:true rhino:true */ /*global phantom:true */ var fs, system, esprima, options, fnames, forceFile, count; if (typeof esprima === 'undefined') { // PhantomJS can only require() relative files if (typeof phantom === 'object') { fs = require('fs'); system = require('system'); esprima = require('./esprima'); } else if (typeof require === 'function') { fs = require('fs'); try { esprima = require('esprima'); } catch (e) { esprima = require('esprima'); } } else if (typeof load === 'function') { try { load('esprima.js'); } catch (e) { load('../esprima.js'); } } } // Shims to Node.js objects when running under PhantomJS 1.7+. if (typeof phantom === 'object') { fs.readFileSync = fs.read; process = { argv: [].slice.call(system.args), exit: phantom.exit, on: function (evt, callback) { callback(); } }; process.argv.unshift('phantomjs'); } // Shims to Node.js objects when running under Rhino. if (typeof console === 'undefined' && typeof process === 'undefined') { console = { log: print }; fs = { readFileSync: readFile }; process = { argv: arguments, exit: quit, on: function (evt, callback) { callback(); } }; process.argv.unshift('esvalidate.js'); process.argv.unshift('rhino'); } function showUsage() { console.log('Usage:'); console.log(' esvalidate [options] [file.js...]'); console.log(); console.log('Available options:'); console.log(); console.log(' --format=type Set the report format, plain (default) or junit'); console.log(' -v, --version Print program version'); console.log(); process.exit(1); } options = { format: 'plain' }; fnames = []; process.argv.splice(2).forEach(function (entry) { if (forceFile || entry === '-' || entry.slice(0, 1) !== '-') { fnames.push(entry); } else if (entry === '-h' || entry === '--help') { showUsage(); } else if (entry === '-v' || entry === '--version') { console.log('ECMAScript Validator (using Esprima version', esprima.version, ')'); console.log(); process.exit(0); } else if (entry.slice(0, 9) === '--format=') { options.format = entry.slice(9); if (options.format !== 'plain' && options.format !== 'junit') { console.log('Error: unknown report format ' + options.format + '.'); process.exit(1); } } else if (entry === '--') { forceFile = true; } else { console.log('Error: unknown option ' + entry + '.'); process.exit(1); } }); if (fnames.length === 0) { fnames.push(''); } if (options.format === 'junit') { console.log('<?xml version="1.0" encoding="UTF-8"?>'); console.log('<testsuites>'); } count = 0; function run(fname, content) { var timestamp, syntax, name; try { if (typeof content !== 'string') { throw content; } if (content[0] === '#' && content[1] === '!') { content = '//' + content.substr(2, content.length); } timestamp = Date.now(); syntax = esprima.parse(content, { tolerant: true }); if (options.format === 'junit') { name = fname; if (name.lastIndexOf('/') >= 0) { name = name.slice(name.lastIndexOf('/') + 1); } console.log('<testsuite name="' + fname + '" errors="0" ' + ' failures="' + syntax.errors.length + '" ' + ' tests="' + syntax.errors.length + '" ' + ' time="' + Math.round((Date.now() - timestamp) / 1000) + '">'); syntax.errors.forEach(function (error) { var msg = error.message; msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' + ' time="0">'); console.log(' <error type="SyntaxError" message="' + error.message + '">' + error.message + '(' + name + ':' + error.lineNumber + ')' + '</error>'); console.log(' </testcase>'); }); console.log('</testsuite>'); } else if (options.format === 'plain') { syntax.errors.forEach(function (error) { var msg = error.message; msg = msg.replace(/^Line\ [0-9]*\:\ /, ''); msg = fname + ':' + error.lineNumber + ': ' + msg; console.log(msg); ++count; }); } } catch (e) { ++count; if (options.format === 'junit') { console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' + ' time="' + Math.round((Date.now() - timestamp) / 1000) + '">'); console.log(' <testcase name="' + e.message + '" ' + ' time="0">'); console.log(' <error type="ParseError" message="' + e.message + '">' + e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') + ')</error>'); console.log(' </testcase>'); console.log('</testsuite>'); } else { console.log(fname + ':' + e.lineNumber + ': ' + e.message.replace(/^Line\ [0-9]*\:\ /, '')); } } } fnames.forEach(function (fname) { var content = ''; try { if (fname && (fname !== '-' || forceFile)) { content = fs.readFileSync(fname, 'utf-8'); } else { fname = ''; process.stdin.resume(); process.stdin.on('data', function(chunk) { content += chunk; }); process.stdin.on('end', function() { run(fname, content); }); return; } } catch (e) { content = e; } run(fname, content); }); process.on('exit', function () { if (options.format === 'junit') { console.log('</testsuites>'); } if (count > 0) { process.exit(1); } if (count === 0 && typeof phantom === 'object') { process.exit(0); } });
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/esprima/bin/esvalidate.js
esvalidate.js
# node-dashdash changelog ## not yet released (nothing yet) ## 1.14.1 - [issue #30] Change the output used by dashdash's Bash completion support to indicate "there are no completions for this argument" to cope with different sorting rules on different Bash/platforms. For example: $ triton -v -p test2 package get <TAB> # before ##-no -tritonpackage- completions-## $ triton -v -p test2 package get <TAB> # after ##-no-completion- -results-## ## 1.14.0 - New `synopsisFromOpt(<option spec>)` function. This will be used by [node-cmdln](https://github.com/trentm/node-cmdln) to put together a synopsis of options for a command. Some examples: > synopsisFromOpt({names: ['help', 'h'], type: 'bool'}); '[ --help | -h ]' > synopsisFromOpt({name: 'file', type: 'string', helpArg: 'FILE'}); '[ --file=FILE ]' ## 1.13.1 - [issue #20] `bashCompletionSpecFromOptions` breaks on an options array with an empty-string group. ## 1.13.0 - Update assert-plus dep to 1.x to get recent fixes (particularly for `assert.optional*`). - Drop testing (and official support in packages.json#engines) for node 0.8.x. Add testing against node 5.x and 4.x with `make testall`. - [pull #16] Change the `positiveInteger` type to NOT accept zero (0). For those who might need the old behaviour, see "examples/custom-option-intGteZero.js". (By Dave Pacheco.) ## 1.12.2 - Bash completion: Add `argtypes` to specify the types of positional args. E.g. this would allow you to have an `ssh` command with `argtypes = ['host', 'cmd']` for bash completion. You then have to provide Bash functions to handle completing those types via the `specExtra` arg. See "[examples/ddcompletion.js](examples/ddcompletion.js)" for an example. - Bash completion: Tweak so that options or only offered as completions when there is a leading '-'. E.g. `mytool <TAB>` does NOT offer options, `mytool -<TAB>` *does*. Without this, a tool with options would never be able to fallback to Bash's "default" completion. For example `ls <TAB>` wouldn't result in filename completion. Now it will. - Bash completion: A workaround for not being able to explicitly have *no* completion results. Because dashdash's completion uses `complete -o default`, we fallback to Bash's "default" completion (typically for filename completion). Before this change, an attempt to explicitly say "there are no completions that match" would unintentionally trigger filename completion. Instead as a workaround we return: $ ddcompletion --none <TAB> # the 'none' argtype ##-no completions-## $ ddcompletion # a custom 'fruit' argtype apple banana orange $ ddcompletion z ##-no -fruit- completions-## This is a bit of a hack, but IMO a better experience than the surprise of matching a local filename beginning with 'z', which isn't, in this case, a "fruit". ## 1.12.1 - Bash completion: Document `<option spec>.completionType`. Add `includeHidden` option to `bashCompletionSpecFromOptions()`. Add support for dealing with hidden subcmds. ## 1.12.0 - Support for generating Bash completion files. See the "Bash completion" section of the README.md and "examples/ddcompletion.js" for an example. ## 1.11.0 - Add the `arrayFlatten` boolean option to `dashdash.addOptionType` used for custom option types. This allows one to create an `arrayOf...` option type where each usage of the option can return multiple results. For example: node mytool.js --foo a,b --foo c We could define an option type for `--foo` such that `opts.foo = ['a', 'b', 'c']`. See "[examples/custom-option-arrayOfCommaSepString.js](examples/custom-option-arrayOfCommaSepString.js)" for an example. ## 1.10.1 - Trim the published package to the minimal bits. Before: 24K tarball, 144K unpacked. After: 12K tarball, 48K unpacked. `npm` won't let me drop the README.md. :) ## 1.10.0 - [issue #9] Support `includeDefault` in help config (similar to `includeEnv`) to have a note of an option's default value, if any, in help output. - [issue #11] Fix option group breakage introduced in v1.9.0. ## 1.9.0 - [issue #10] Custom option types added with `addOptionType` can specify a "default" value. See "examples/custom-option-fruit.js". ## 1.8.0 - Support `hidden: true` in an option spec to have help output exclude this option. ## 1.7.3 - [issue #8] Fix parsing of a short option group when one of the option takes an argument. For example, consider `tail` with a `-f` boolean option and a `-n` option that takes a number argument. This should parse: tail -fn5 Before this change, that would not parse correctly. It is suspected that this was introduced in version 1.4.0 (with commit 656fa8bc71c372ebddad0a7026bd71611e2ec99a). ## 1.7.2 - Known issues: #8 - Exclude 'tools/' dir in packages published to npm. ## 1.7.1 - Known issues: #8 - Support an option group *empty string* value: ... { group: '' }, ... to render as a blank line in option help. This can help separate loosely related sets of options without resorting to a title for option groups. ## 1.7.0 - Known issues: #8 - [pull #7] Support for `<parser>.help({helpWrap: false, ...})` option to be able to fully control the formatting for option help (by Patrick Mooney) `helpWrap: false` can also be set on individual options in the option objects, e.g.: var options = [ { names: ['foo'], type: 'string', helpWrap: false, help: 'long help with\n newlines' + '\n spaces\n and such\nwill render correctly' }, ... ]; ## 1.6.0 - Known issues: #8 - [pull #6] Support headings between groups of options (by Joshua M. Clulow) so that this code: var options = [ { group: 'Armament Options' }, { names: [ 'weapon', 'w' ], type: 'string' }, { group: 'General Options' }, { names: [ 'help', 'h' ], type: 'bool' } ]; ... will give you this help output: ... Armament Options: -w, --weapon General Options: -h, --help ... ## 1.5.0 - Known issues: #8 - Add support for adding custom option types. "examples/custom-option-duration.js" shows an example adding a "duration" option type. $ node custom-option-duration.js -t 1h duration: 3600000 ms $ node custom-option-duration.js -t 1s duration: 1000 ms $ node custom-option-duration.js -t 5d duration: 432000000 ms $ node custom-option-duration.js -t bogus custom-option-duration.js: error: arg for "-t" is not a valid duration: "bogus" A custom option type is added via: var dashdash = require('dashdash'); dashdash.addOptionType({ name: '...', takesArg: true, helpArg: '...', parseArg: function (option, optstr, arg) { ... } }); - [issue #4] Add `date` and `arrayOfDate` option types. They accept these date formats: epoch second times (e.g. 1396031701) and ISO 8601 format: `YYYY-MM-DD[THH:MM:SS[.sss][Z]]` (e.g. "2014-03-28", "2014-03-28T18:35:01.489Z"). See "examples/date.js" for an example usage. $ node examples/date.js -s 2014-01-01 -e $(date +%s) start at 2014-01-01T00:00:00.000Z end at 2014-03-29T04:26:18.000Z ## 1.4.0 - Known issues: #8 - [pull #2, pull #3] Add a `allowUnknown: true` option on `createParser` to allow unknown options to be passed through as `opts._args` instead of parsing throwing an exception (by https://github.com/isaacs). See 'allowUnknown' in the README for a subtle caveat. ## 1.3.2 - Fix a subtlety where a *bool* option using both `env` and `default` didn't work exactly correctly. If `default: false` then all was fine (by luck). However, if you had an option like this: options: [ { names: ['verbose', 'v'], env: 'FOO_VERBOSE', 'default': true, // <--- this type: 'bool' } ], wanted `FOO_VERBOSE=0` to make the option false, then you need the fix in this version of dashdash. ## 1.3.1 - [issue #1] Fix an envvar not winning over an option 'default'. Previously an option with both `default` and `env` would never take a value from the environment variable. E.g. `FOO_FILE` would never work here: options: [ { names: ['file', 'f'], env: 'FOO_FILE', 'default': 'default.file', type: 'string' } ], ## 1.3.0 - [Backward incompatible change for boolean envvars] Change the interpretation of environment variables for boolean options to consider '0' to be false. Previous to this *any* value to the envvar was considered true -- which was quite misleading. Example: $ FOO_VERBOSE=0 node examples/foo.js # opts: { verbose: [ false ], _order: [ { key: 'verbose', value: false, from: 'env' } ], _args: [] } # args: [] ## 1.2.1 - Fix for `parse.help({includeEnv: true, ...})` handling to ensure that an option with an `env` **but no `help`** still has the "Environment: ..." output. E.g.: { names: ['foo'], type: 'string', env: 'FOO' } ... --foo=ARG Environment: FOO=ARG ## 1.2.0 - Transform the option key on the `opts` object returned from `<parser>.parse()` for convenience. Currently this is just `s/-/_/g`, e.g. '--dry-run' -> `opts.dry_run`. This allow one to use hyphen in option names (common) but not have to do silly things like `opt["dry-run"]` to access the parsed results. ## 1.1.0 - Environment variable integration. Envvars can be associated with an option, then option processing will fallback to using that envvar if defined and if the option isn't specified in argv. See the "Environment variable integration" section in the README. - Change the `<parser>.parse()` signature to take a single object with keys for arguments. The old signature is still supported. - `dashdash.createParser(CONFIG)` alternative to `new dashdash.Parser(CONFIG)` a la many node-land APIs. ## 1.0.2 - Add "positiveInteger" and "arrayOfPositiveInteger" option types that only accept positive integers. - Add "integer" and "arrayOfInteger" option types that accepts only integers. Note that, for better or worse, these do NOT accept: "0x42" (hex), "1e2" (with exponent) or "1.", "3.0" (floats). ## 1.0.1 - Fix not modifying the given option spec objects (which breaks creating a Parser with them more than once). ## 1.0.0 First release.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/dashdash/CHANGES.md
CHANGES.md
A light, featureful and explicit option parsing library for node.js. [Why another one? See below](#why). tl;dr: The others I've tried are one of too loosey goosey (not explicit), too big/too many deps, or ill specified. YMMV. Follow <a href="https://twitter.com/intent/user?screen_name=trentmick" target="_blank">@trentmick</a> for updates to node-dashdash. # Install npm install dashdash # Usage ```javascript var dashdash = require('dashdash'); // Specify the options. Minimally `name` (or `names`) and `type` // must be given for each. var options = [ { // `names` or a single `name`. First element is the `opts.KEY`. names: ['help', 'h'], // See "Option specs" below for types. type: 'bool', help: 'Print this help and exit.' } ]; // Shortcut form. As called it infers `process.argv`. See below for // the longer form to use methods like `.help()` on the Parser object. var opts = dashdash.parse({options: options}); console.log("opts:", opts); console.log("args:", opts._args); ``` # Longer Example A more realistic [starter script "foo.js"](./examples/foo.js) is as follows. This also shows using `parser.help()` for formatted option help. ```javascript var dashdash = require('dashdash'); var options = [ { name: 'version', type: 'bool', help: 'Print tool version and exit.' }, { names: ['help', 'h'], type: 'bool', help: 'Print this help and exit.' }, { names: ['verbose', 'v'], type: 'arrayOfBool', help: 'Verbose output. Use multiple times for more verbose.' }, { names: ['file', 'f'], type: 'string', help: 'File to process', helpArg: 'FILE' } ]; var parser = dashdash.createParser({options: options}); try { var opts = parser.parse(process.argv); } catch (e) { console.error('foo: error: %s', e.message); process.exit(1); } console.log("# opts:", opts); console.log("# args:", opts._args); // Use `parser.help()` for formatted options help. if (opts.help) { var help = parser.help({includeEnv: true}).trimRight(); console.log('usage: node foo.js [OPTIONS]\n' + 'options:\n' + help); process.exit(0); } // ... ``` Some example output from this script (foo.js): ``` $ node foo.js -h # opts: { help: true, _order: [ { name: 'help', value: true, from: 'argv' } ], _args: [] } # args: [] usage: node foo.js [OPTIONS] options: --version Print tool version and exit. -h, --help Print this help and exit. -v, --verbose Verbose output. Use multiple times for more verbose. -f FILE, --file=FILE File to process $ node foo.js -v # opts: { verbose: [ true ], _order: [ { name: 'verbose', value: true, from: 'argv' } ], _args: [] } # args: [] $ node foo.js --version arg1 # opts: { version: true, _order: [ { name: 'version', value: true, from: 'argv' } ], _args: [ 'arg1' ] } # args: [ 'arg1' ] $ node foo.js -f bar.txt # opts: { file: 'bar.txt', _order: [ { name: 'file', value: 'bar.txt', from: 'argv' } ], _args: [] } # args: [] $ node foo.js -vvv --file=blah # opts: { verbose: [ true, true, true ], file: 'blah', _order: [ { name: 'verbose', value: true, from: 'argv' }, { name: 'verbose', value: true, from: 'argv' }, { name: 'verbose', value: true, from: 'argv' }, { name: 'file', value: 'blah', from: 'argv' } ], _args: [] } # args: [] ``` See the ["examples"](examples/) dir for a number of starter examples using some of dashdash's features. # Environment variable integration If you want to allow environment variables to specify options to your tool, dashdash makes this easy. We can change the 'verbose' option in the example above to include an 'env' field: ```javascript { names: ['verbose', 'v'], type: 'arrayOfBool', env: 'FOO_VERBOSE', // <--- add this line help: 'Verbose output. Use multiple times for more verbose.' }, ``` then the **"FOO_VERBOSE" environment variable** can be used to set this option: ```shell $ FOO_VERBOSE=1 node foo.js # opts: { verbose: [ true ], _order: [ { name: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] ``` Boolean options will interpret the empty string as unset, '0' as false and anything else as true. ```shell $ FOO_VERBOSE= node examples/foo.js # not set # opts: { _order: [], _args: [] } # args: [] $ FOO_VERBOSE=0 node examples/foo.js # '0' is false # opts: { verbose: [ false ], _order: [ { key: 'verbose', value: false, from: 'env' } ], _args: [] } # args: [] $ FOO_VERBOSE=1 node examples/foo.js # true # opts: { verbose: [ true ], _order: [ { key: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] $ FOO_VERBOSE=boogabooga node examples/foo.js # true # opts: { verbose: [ true ], _order: [ { key: 'verbose', value: true, from: 'env' } ], _args: [] } # args: [] ``` Non-booleans can be used as well. Strings: ```shell $ FOO_FILE=data.txt node examples/foo.js # opts: { file: 'data.txt', _order: [ { key: 'file', value: 'data.txt', from: 'env' } ], _args: [] } # args: [] ``` Numbers: ```shell $ FOO_TIMEOUT=5000 node examples/foo.js # opts: { timeout: 5000, _order: [ { key: 'timeout', value: 5000, from: 'env' } ], _args: [] } # args: [] $ FOO_TIMEOUT=blarg node examples/foo.js foo: error: arg for "FOO_TIMEOUT" is not a positive integer: "blarg" ``` With the `includeEnv: true` config to `parser.help()` the environment variable can also be included in **help output**: usage: node foo.js [OPTIONS] options: --version Print tool version and exit. -h, --help Print this help and exit. -v, --verbose Verbose output. Use multiple times for more verbose. Environment: FOO_VERBOSE=1 -f FILE, --file=FILE File to process # Bash completion Dashdash provides a simple way to create a Bash completion file that you can place in your "bash_completion.d" directory -- sometimes that is "/usr/local/etc/bash_completion.d/"). Features: - Support for short and long opts - Support for knowing which options take arguments - Support for subcommands (e.g. 'git log <TAB>' to show just options for the log subcommand). See [node-cmdln](https://github.com/trentm/node-cmdln#bash-completion) for how to integrate that. - Does the right thing with "--" to stop options. - Custom optarg and arg types for custom completions. Dashdash will return bash completion file content given a parser instance: var parser = dashdash.createParser({options: options}); console.log( parser.bashCompletion({name: 'mycli'}) ); or directly from a `options` array of options specs: var code = dashdash.bashCompletionFromOptions({ name: 'mycli', options: OPTIONS }); Write that content to "/usr/local/etc/bash_completion.d/mycli" and you will have Bash completions for `mycli`. Alternatively you can write it to any file (e.g. "~/.bashrc") and source it. You could add a `--completion` hidden option to your tool that emits the completion content and document for your users to call that to install Bash completions. See [examples/ddcompletion.js](examples/ddcompletion.js) for a complete example, including how one can define bash functions for completion of custom option types. Also see [node-cmdln](https://github.com/trentm/node-cmdln) for how it uses this for Bash completion for full multi-subcommand tools. - TODO: document specExtra - TODO: document includeHidden - TODO: document custom types, `function complete\_FOO` guide, completionType - TODO: document argtypes # Parser config Parser construction (i.e. `dashdash.createParser(CONFIG)`) takes the following fields: - `options` (Array of option specs). Required. See the [Option specs](#option-specs) section below. - `interspersed` (Boolean). Optional. Default is true. If true this allows interspersed arguments and options. I.e.: node ./tool.js -v arg1 arg2 -h # '-h' is after interspersed args Set it to false to have '-h' **not** get parsed as an option in the above example. - `allowUnknown` (Boolean). Optional. Default is false. If false, this causes unknown arguments to throw an error. I.e.: node ./tool.js -v arg1 --afe8asefksjefhas Set it to true to treat the unknown option as a positional argument. **Caveat**: When a shortopt group, such as `-xaz` contains a mix of known and unknown options, the *entire* group is passed through unmolested as a positional argument. Consider if you have a known short option `-a`, and parse the following command line: node ./tool.js -xaz where `-x` and `-z` are unknown. There are multiple ways to interpret this: 1. `-x` takes a value: `{x: 'az'}` 2. `-x` and `-z` are both booleans: `{x:true,a:true,z:true}` Since dashdash does not know what `-x` and `-z` are, it can't know if you'd prefer to receive `{a:true,_args:['-x','-z']}` or `{x:'az'}`, or `{_args:['-xaz']}`. Leaving the positional arg unprocessed is the easiest mistake for the user to recover from. # Option specs Example using all fields (required fields are noted): ```javascript { names: ['file', 'f'], // Required (one of `names` or `name`). type: 'string', // Required. completionType: 'filename', env: 'MYTOOL_FILE', help: 'Config file to load before running "mytool"', helpArg: 'PATH', helpWrap: false, default: path.resolve(process.env.HOME, '.mytoolrc') } ``` Each option spec in the `options` array must/can have the following fields: - `name` (String) or `names` (Array). Required. These give the option name and aliases. The first name (if more than one given) is the key for the parsed `opts` object. - `type` (String). Required. One of: - bool - string - number - integer - positiveInteger - date (epoch seconds, e.g. 1396031701, or ISO 8601 format `YYYY-MM-DD[THH:MM:SS[.sss][Z]]`, e.g. "2014-03-28T18:35:01.489Z") - arrayOfBool - arrayOfString - arrayOfNumber - arrayOfInteger - arrayOfPositiveInteger - arrayOfDate FWIW, these names attempt to match with asserts on [assert-plus](https://github.com/mcavage/node-assert-plus). You can add your own custom option types with `dashdash.addOptionType`. See below. - `completionType` (String). Optional. This is used for [Bash completion](#bash-completion) for an option argument. If not specified, then the value of `type` is used. Any string may be specified, but only the following values have meaning: - `none`: Provide no completions. - `file`: Bash's default completion (i.e. `complete -o default`), which includes filenames. - *Any string FOO for which a `function complete_FOO` Bash function is defined.* This is for custom completions for a given tool. Typically these custom functions are provided in the `specExtra` argument to `dashdash.bashCompletionFromOptions()`. See ["examples/ddcompletion.js"](examples/ddcompletion.js) for an example. - `env` (String or Array of String). Optional. An environment variable name (or names) that can be used as a fallback for this option. For example, given a "foo.js" like this: var options = [{names: ['dry-run', 'n'], env: 'FOO_DRY_RUN'}]; var opts = dashdash.parse({options: options}); Both `node foo.js --dry-run` and `FOO_DRY_RUN=1 node foo.js` would result in `opts.dry_run = true`. An environment variable is only used as a fallback, i.e. it is ignored if the associated option is given in `argv`. - `help` (String). Optional. Used for `parser.help()` output. - `helpArg` (String). Optional. Used in help output as the placeholder for the option argument, e.g. the "PATH" in: ... -f PATH, --file=PATH File to process ... - `helpWrap` (Boolean). Optional, default true. Set this to `false` to have that option's `help` *not* be text wrapped in `<parser>.help()` output. - `default`. Optional. A default value used for this option, if the option isn't specified in argv. - `hidden` (Boolean). Optional, default false. If true, help output will not include this option. See also the `includeHidden` option to `bashCompletionFromOptions()` for [Bash completion](#bash-completion). # Option group headings You can add headings between option specs in the `options` array. To do so, simply add an object with only a `group` property -- the string to print as the heading for the subsequent options in the array. For example: ```javascript var options = [ { group: 'Armament Options' }, { names: [ 'weapon', 'w' ], type: 'string' }, { group: 'General Options' }, { names: [ 'help', 'h' ], type: 'bool' } ]; ... ``` Note: You can use an empty string, `{group: ''}`, to get a blank line in help output between groups of options. # Help config The `parser.help(...)` function is configurable as follows: Options: Armament Options: ^^ -w WEAPON, --weapon=WEAPON Weapon with which to crush. One of: | / sword, spear, maul | / General Options: | / -h, --help Print this help and exit. | / ^^^^ ^ | \ `-- indent `-- helpCol maxCol ---' `-- headingIndent - `indent` (Number or String). Default 4. Set to a number (for that many spaces) or a string for the literal indent. - `headingIndent` (Number or String). Default half length of `indent`. Set to a number (for that many spaces) or a string for the literal indent. This indent applies to group heading lines, between normal option lines. - `nameSort` (String). Default is 'length'. By default the names are sorted to put the short opts first (i.e. '-h, --help' preferred to '--help, -h'). Set to 'none' to not do this sorting. - `maxCol` (Number). Default 80. Note that reflow is just done on whitespace so a long token in the option help can overflow maxCol. - `helpCol` (Number). If not set a reasonable value will be determined between `minHelpCol` and `maxHelpCol`. - `minHelpCol` (Number). Default 20. - `maxHelpCol` (Number). Default 40. - `helpWrap` (Boolean). Default true. Set to `false` to have option `help` strings *not* be textwrapped to the helpCol..maxCol range. - `includeEnv` (Boolean). Default false. If the option has associated environment variables (via the `env` option spec attribute), then append mentioned of those envvars to the help string. - `includeDefault` (Boolean). Default false. If the option has a default value (via the `default` option spec attribute, or a default on the option's type), then a "Default: VALUE" string will be appended to the help string. # Custom option types Dashdash includes a good starter set of option types that it will parse for you. However, you can add your own via: var dashdash = require('dashdash'); dashdash.addOptionType({ name: '...', takesArg: true, helpArg: '...', parseArg: function (option, optstr, arg) { ... }, array: false, // optional arrayFlatten: false, // optional default: ..., // optional completionType: ... // optional }); For example, a simple option type that accepts 'yes', 'y', 'no' or 'n' as a boolean argument would look like: var dashdash = require('dashdash'); function parseYesNo(option, optstr, arg) { var argLower = arg.toLowerCase() if (~['yes', 'y'].indexOf(argLower)) { return true; } else if (~['no', 'n'].indexOf(argLower)) { return false; } else { throw new Error(format( 'arg for "%s" is not "yes" or "no": "%s"', optstr, arg)); } } dashdash.addOptionType({ name: 'yesno' takesArg: true, helpArg: '<yes|no>', parseArg: parseYesNo }); var options = { {names: ['answer', 'a'], type: 'yesno'} }; var opts = dashdash.parse({options: options}); See "examples/custom-option-\*.js" for other examples. See the `addOptionType` block comment in "lib/dashdash.js" for more details. Please let me know [with an issue](https://github.com/trentm/node-dashdash/issues/new) if you write a generally useful one. # Why Why another node.js option parsing lib? - `nopt` really is just for "tools like npm". Implicit opts (e.g. '--no-foo' works for every '--foo'). Can't disable abbreviated opts. Can't do multiple usages of same opt, e.g. '-vvv' (I think). Can't do grouped short opts. - `optimist` has surprise interpretation of options (at least to me). Implicit opts mean ambiguities and poor error handling for fat-fingering. `process.exit` calls makes it hard to use as a libary. - `optparse` Incomplete docs. Is this an attempted clone of Python's `optparse`. Not clear. Some divergence. `parser.on("name", ...)` API is weird. - `argparse` Dep on underscore. No thanks just for option processing. `find lib | wc -l` -> `26`. Overkill. Argparse is a bit different anyway. Not sure I want that. - `posix-getopt` No type validation. Though that isn't a killer. AFAIK can't have a long opt without a short alias. I.e. no `getopt_long` semantics. Also, no whizbang features like generated help output. - ["commander.js"](https://github.com/visionmedia/commander.js): I wrote [a critique](http://trentm.com/2014/01/a-critique-of-commander-for-nodejs.html) a while back. It seems fine, but last I checked had [an outstanding bug](https://github.com/visionmedia/commander.js/pull/121) that would prevent me from using it. # License MIT. See LICENSE.txt.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/dashdash/README.md
README.md
var assert = require('assert-plus'); var format = require('util').format; var fs = require('fs'); var path = require('path'); var DEBUG = true; if (DEBUG) { var debug = console.warn; } else { var debug = function () {}; } // ---- internal support stuff // Replace {{variable}} in `s` with the template data in `d`. function renderTemplate(s, d) { return s.replace(/{{([a-zA-Z]+)}}/g, function (match, key) { return d.hasOwnProperty(key) ? d[key] : match; }); } /** * Return a shallow copy of the given object; */ function shallowCopy(obj) { if (!obj) { return (obj); } var copy = {}; Object.keys(obj).forEach(function (k) { copy[k] = obj[k]; }); return (copy); } function space(n) { var s = ''; for (var i = 0; i < n; i++) { s += ' '; } return s; } function makeIndent(arg, deflen, name) { if (arg === null || arg === undefined) return space(deflen); else if (typeof (arg) === 'number') return space(arg); else if (typeof (arg) === 'string') return arg; else assert.fail('invalid "' + name + '": not a string or number: ' + arg); } /** * Return an array of lines wrapping the given text to the given width. * This splits on whitespace. Single tokens longer than `width` are not * broken up. */ function textwrap(s, width) { var words = s.trim().split(/\s+/); var lines = []; var line = ''; words.forEach(function (w) { var newLength = line.length + w.length; if (line.length > 0) newLength += 1; if (newLength > width) { lines.push(line); line = ''; } if (line.length > 0) line += ' '; line += w; }); lines.push(line); return lines; } /** * Transform an option name to a "key" that is used as the field * on the `opts` object returned from `<parser>.parse()`. * * Transformations: * - '-' -> '_': This allow one to use hyphen in option names (common) * but not have to do silly things like `opt["dry-run"]` to access the * parsed results. */ function optionKeyFromName(name) { return name.replace(/-/g, '_'); } // ---- Option types function parseBool(option, optstr, arg) { return Boolean(arg); } function parseString(option, optstr, arg) { assert.string(arg, 'arg'); return arg; } function parseNumber(option, optstr, arg) { assert.string(arg, 'arg'); var num = Number(arg); if (isNaN(num)) { throw new Error(format('arg for "%s" is not a number: "%s"', optstr, arg)); } return num; } function parseInteger(option, optstr, arg) { assert.string(arg, 'arg'); var num = Number(arg); if (!/^[0-9-]+$/.test(arg) || isNaN(num)) { throw new Error(format('arg for "%s" is not an integer: "%s"', optstr, arg)); } return num; } function parsePositiveInteger(option, optstr, arg) { assert.string(arg, 'arg'); var num = Number(arg); if (!/^[0-9]+$/.test(arg) || isNaN(num) || num === 0) { throw new Error(format('arg for "%s" is not a positive integer: "%s"', optstr, arg)); } return num; } /** * Supported date args: * - epoch second times (e.g. 1396031701) * - ISO 8601 format: YYYY-MM-DD[THH:MM:SS[.sss][Z]] * 2014-03-28T18:35:01.489Z * 2014-03-28T18:35:01.489 * 2014-03-28T18:35:01Z * 2014-03-28T18:35:01 * 2014-03-28 */ function parseDate(option, optstr, arg) { assert.string(arg, 'arg'); var date; if (/^\d+$/.test(arg)) { // epoch seconds date = new Date(Number(arg) * 1000); /* JSSTYLED */ } else if (/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2}(\.\d+)?Z?)?$/i.test(arg)) { // ISO 8601 format date = new Date(arg); } else { throw new Error(format('arg for "%s" is not a valid date format: "%s"', optstr, arg)); } if (date.toString() === 'Invalid Date') { throw new Error(format('arg for "%s" is an invalid date: "%s"', optstr, arg)); } return date; } var optionTypes = { bool: { takesArg: false, parseArg: parseBool }, string: { takesArg: true, helpArg: 'ARG', parseArg: parseString }, number: { takesArg: true, helpArg: 'NUM', parseArg: parseNumber }, integer: { takesArg: true, helpArg: 'INT', parseArg: parseInteger }, positiveInteger: { takesArg: true, helpArg: 'INT', parseArg: parsePositiveInteger }, date: { takesArg: true, helpArg: 'DATE', parseArg: parseDate }, arrayOfBool: { takesArg: false, array: true, parseArg: parseBool }, arrayOfString: { takesArg: true, helpArg: 'ARG', array: true, parseArg: parseString }, arrayOfNumber: { takesArg: true, helpArg: 'NUM', array: true, parseArg: parseNumber }, arrayOfInteger: { takesArg: true, helpArg: 'INT', array: true, parseArg: parseInteger }, arrayOfPositiveInteger: { takesArg: true, helpArg: 'INT', array: true, parseArg: parsePositiveInteger }, arrayOfDate: { takesArg: true, helpArg: 'INT', array: true, parseArg: parseDate }, }; // ---- Parser /** * Parser constructor. * * @param config {Object} The parser configuration * - options {Array} Array of option specs. See the README for how to * specify each option spec. * - allowUnknown {Boolean} Default false. Whether to throw on unknown * options. If false, then unknown args are included in the _args array. * - interspersed {Boolean} Default true. Whether to allow interspersed * arguments (non-options) and options. E.g.: * node tool.js arg1 arg2 -v * '-v' is after some args here. If `interspersed: false` then '-v' * would not be parsed out. Note that regardless of `interspersed` * the presence of '--' will stop option parsing, as all good * option parsers should. */ function Parser(config) { assert.object(config, 'config'); assert.arrayOfObject(config.options, 'config.options'); assert.optionalBool(config.interspersed, 'config.interspersed'); var self = this; // Allow interspersed arguments (true by default). this.interspersed = (config.interspersed !== undefined ? config.interspersed : true); // Don't allow unknown flags (true by default). this.allowUnknown = (config.allowUnknown !== undefined ? config.allowUnknown : false); this.options = config.options.map(function (o) { return shallowCopy(o); }); this.optionFromName = {}; this.optionFromEnv = {}; for (var i = 0; i < this.options.length; i++) { var o = this.options[i]; if (o.group !== undefined && o.group !== null) { assert.optionalString(o.group, format('config.options.%d.group', i)); continue; } assert.ok(optionTypes[o.type], format('invalid config.options.%d.type: "%s" in %j', i, o.type, o)); assert.optionalString(o.name, format('config.options.%d.name', i)); assert.optionalArrayOfString(o.names, format('config.options.%d.names', i)); assert.ok((o.name || o.names) && !(o.name && o.names), format('exactly one of "name" or "names" required: %j', o)); assert.optionalString(o.help, format('config.options.%d.help', i)); var env = o.env || []; if (typeof (env) === 'string') { env = [env]; } assert.optionalArrayOfString(env, format('config.options.%d.env', i)); assert.optionalString(o.helpGroup, format('config.options.%d.helpGroup', i)); assert.optionalBool(o.helpWrap, format('config.options.%d.helpWrap', i)); assert.optionalBool(o.hidden, format('config.options.%d.hidden', i)); if (o.name) { o.names = [o.name]; } else { assert.string(o.names[0], format('config.options.%d.names is empty', i)); } o.key = optionKeyFromName(o.names[0]); o.names.forEach(function (n) { if (self.optionFromName[n]) { throw new Error(format( 'option name collision: "%s" used in %j and %j', n, self.optionFromName[n], o)); } self.optionFromName[n] = o; }); env.forEach(function (n) { if (self.optionFromEnv[n]) { throw new Error(format( 'option env collision: "%s" used in %j and %j', n, self.optionFromEnv[n], o)); } self.optionFromEnv[n] = o; }); } } Parser.prototype.optionTakesArg = function optionTakesArg(option) { return optionTypes[option.type].takesArg; }; /** * Parse options from the given argv. * * @param inputs {Object} Optional. * - argv {Array} Optional. The argv to parse. Defaults to * `process.argv`. * - slice {Number} The index into argv at which options/args begin. * Default is 2, as appropriate for `process.argv`. * - env {Object} Optional. The env to use for 'env' entries in the * option specs. Defaults to `process.env`. * @returns {Object} Parsed `opts`. It has special keys `_args` (the * remaining args from `argv`) and `_order` (gives the order that * options were specified). */ Parser.prototype.parse = function parse(inputs) { var self = this; // Old API was `parse([argv, [slice]])` if (Array.isArray(arguments[0])) { inputs = {argv: arguments[0], slice: arguments[1]}; } assert.optionalObject(inputs, 'inputs'); if (!inputs) { inputs = {}; } assert.optionalArrayOfString(inputs.argv, 'inputs.argv'); //assert.optionalNumber(slice, 'slice'); var argv = inputs.argv || process.argv; var slice = inputs.slice !== undefined ? inputs.slice : 2; var args = argv.slice(slice); var env = inputs.env || process.env; var opts = {}; var _order = []; function addOpt(option, optstr, key, val, from) { var type = optionTypes[option.type]; var parsedVal = type.parseArg(option, optstr, val); if (type.array) { if (!opts[key]) { opts[key] = []; } if (type.arrayFlatten && Array.isArray(parsedVal)) { for (var i = 0; i < parsedVal.length; i++) { opts[key].push(parsedVal[i]); } } else { opts[key].push(parsedVal); } } else { opts[key] = parsedVal; } var item = { key: key, value: parsedVal, from: from }; _order.push(item); } // Parse args. var _args = []; var i = 0; outer: while (i < args.length) { var arg = args[i]; // End of options marker. if (arg === '--') { i++; break; // Long option } else if (arg.slice(0, 2) === '--') { var name = arg.slice(2); var val = null; var idx = name.indexOf('='); if (idx !== -1) { val = name.slice(idx + 1); name = name.slice(0, idx); } var option = this.optionFromName[name]; if (!option) { if (!this.allowUnknown) throw new Error(format('unknown option: "--%s"', name)); else if (this.interspersed) _args.push(arg); else break outer; } else { var takesArg = this.optionTakesArg(option); if (val !== null && !takesArg) { throw new Error(format('argument given to "--%s" option ' + 'that does not take one: "%s"', name, arg)); } if (!takesArg) { addOpt(option, '--'+name, option.key, true, 'argv'); } else if (val !== null) { addOpt(option, '--'+name, option.key, val, 'argv'); } else if (i + 1 >= args.length) { throw new Error(format('do not have enough args for "--%s" ' + 'option', name)); } else { addOpt(option, '--'+name, option.key, args[i + 1], 'argv'); i++; } } // Short option } else if (arg[0] === '-' && arg.length > 1) { var j = 1; var allFound = true; while (j < arg.length) { var name = arg[j]; var option = this.optionFromName[name]; if (!option) { allFound = false; if (this.allowUnknown) { if (this.interspersed) { _args.push(arg); break; } else break outer; } else if (arg.length > 2) { throw new Error(format( 'unknown option: "-%s" in "%s" group', name, arg)); } else { throw new Error(format('unknown option: "-%s"', name)); } } else if (this.optionTakesArg(option)) { break; } j++; } j = 1; while (allFound && j < arg.length) { var name = arg[j]; var val = arg.slice(j + 1); // option val if it takes an arg var option = this.optionFromName[name]; var takesArg = this.optionTakesArg(option); if (!takesArg) { addOpt(option, '-'+name, option.key, true, 'argv'); } else if (val) { addOpt(option, '-'+name, option.key, val, 'argv'); break; } else { if (i + 1 >= args.length) { throw new Error(format('do not have enough args ' + 'for "-%s" option', name)); } addOpt(option, '-'+name, option.key, args[i + 1], 'argv'); i++; break; } j++; } // An interspersed arg } else if (this.interspersed) { _args.push(arg); // An arg and interspersed args are not allowed, so done options. } else { break outer; } i++; } _args = _args.concat(args.slice(i)); // Parse environment. Object.keys(this.optionFromEnv).forEach(function (envname) { var val = env[envname]; if (val === undefined) return; var option = self.optionFromEnv[envname]; if (opts[option.key] !== undefined) return; var takesArg = self.optionTakesArg(option); if (takesArg) { addOpt(option, envname, option.key, val, 'env'); } else if (val !== '') { // Boolean envvar handling: // - VAR=<empty-string> not set (as if the VAR was not set) // - VAR=0 false // - anything else true addOpt(option, envname, option.key, (val !== '0'), 'env'); } }); // Apply default values. this.options.forEach(function (o) { if (opts[o.key] === undefined) { if (o.default !== undefined) { opts[o.key] = o.default; } else if (o.type && optionTypes[o.type].default !== undefined) { opts[o.key] = optionTypes[o.type].default; } } }); opts._order = _order; opts._args = _args; return opts; }; /** * Return help output for the current options. * * E.g.: if the current options are: * [{names: ['help', 'h'], type: 'bool', help: 'Show help and exit.'}] * then this would return: * ' -h, --help Show help and exit.\n' * * @param config {Object} Config for controlling the option help output. * - indent {Number|String} Default 4. An indent/prefix to use for * each option line. * - nameSort {String} Default is 'length'. By default the names are * sorted to put the short opts first (i.e. '-h, --help' preferred * to '--help, -h'). Set to 'none' to not do this sorting. * - maxCol {Number} Default 80. Note that long tokens in a help string * can go past this. * - helpCol {Number} Set to specify a specific column at which * option help will be aligned. By default this is determined * automatically. * - minHelpCol {Number} Default 20. * - maxHelpCol {Number} Default 40. * - includeEnv {Boolean} Default false. If true, a note stating the `env` * envvar (if specified for this option) will be appended to the help * output. * - includeDefault {Boolean} Default false. If true, a note stating * the `default` for this option, if any, will be appended to the help * output. * - helpWrap {Boolean} Default true. Wrap help text in helpCol..maxCol * bounds. * @returns {String} */ Parser.prototype.help = function help(config) { config = config || {}; assert.object(config, 'config'); var indent = makeIndent(config.indent, 4, 'config.indent'); var headingIndent = makeIndent(config.headingIndent, Math.round(indent.length / 2), 'config.headingIndent'); assert.optionalString(config.nameSort, 'config.nameSort'); var nameSort = config.nameSort || 'length'; assert.ok(~['length', 'none'].indexOf(nameSort), 'invalid "config.nameSort"'); assert.optionalNumber(config.maxCol, 'config.maxCol'); assert.optionalNumber(config.maxHelpCol, 'config.maxHelpCol'); assert.optionalNumber(config.minHelpCol, 'config.minHelpCol'); assert.optionalNumber(config.helpCol, 'config.helpCol'); assert.optionalBool(config.includeEnv, 'config.includeEnv'); assert.optionalBool(config.includeDefault, 'config.includeDefault'); assert.optionalBool(config.helpWrap, 'config.helpWrap'); var maxCol = config.maxCol || 80; var minHelpCol = config.minHelpCol || 20; var maxHelpCol = config.maxHelpCol || 40; var lines = []; var maxWidth = 0; this.options.forEach(function (o) { if (o.hidden) { return; } if (o.group !== undefined && o.group !== null) { // We deal with groups in the next pass lines.push(null); return; } var type = optionTypes[o.type]; var arg = o.helpArg || type.helpArg || 'ARG'; var line = ''; var names = o.names.slice(); if (nameSort === 'length') { names.sort(function (a, b) { if (a.length < b.length) return -1; else if (b.length < a.length) return 1; else return 0; }) } names.forEach(function (name, i) { if (i > 0) line += ', '; if (name.length === 1) { line += '-' + name if (type.takesArg) line += ' ' + arg; } else { line += '--' + name if (type.takesArg) line += '=' + arg; } }); maxWidth = Math.max(maxWidth, line.length); lines.push(line); }); // Add help strings. var helpCol = config.helpCol; if (!helpCol) { helpCol = maxWidth + indent.length + 2; helpCol = Math.min(Math.max(helpCol, minHelpCol), maxHelpCol); } var i = -1; this.options.forEach(function (o) { if (o.hidden) { return; } i++; if (o.group !== undefined && o.group !== null) { if (o.group === '') { // Support a empty string "group" to have a blank line between // sets of options. lines[i] = ''; } else { // Render the group heading with the heading-specific indent. lines[i] = (i === 0 ? '' : '\n') + headingIndent + o.group + ':'; } return; } var helpDefault; if (config.includeDefault) { if (o.default !== undefined) { helpDefault = format('Default: %j', o.default); } else if (o.type && optionTypes[o.type].default !== undefined) { helpDefault = format('Default: %j', optionTypes[o.type].default); } } var line = lines[i] = indent + lines[i]; if (!o.help && !(config.includeEnv && o.env) && !helpDefault) { return; } var n = helpCol - line.length; if (n >= 0) { line += space(n); } else { line += '\n' + space(helpCol); } var helpEnv = ''; if (o.env && o.env.length && config.includeEnv) { helpEnv += 'Environment: '; var type = optionTypes[o.type]; var arg = o.helpArg || type.helpArg || 'ARG'; var envs = (Array.isArray(o.env) ? o.env : [o.env]).map( function (e) { if (type.takesArg) { return e + '=' + arg; } else { return e + '=1'; } } ); helpEnv += envs.join(', '); } var help = (o.help || '').trim(); if (o.helpWrap !== false && config.helpWrap !== false) { // Wrap help description normally. if (help.length && !~'.!?"\''.indexOf(help.slice(-1))) { help += '.'; } if (help.length) { help += ' '; } help += helpEnv; if (helpDefault) { if (helpEnv) { help += '. '; } help += helpDefault; } line += textwrap(help, maxCol - helpCol).join( '\n' + space(helpCol)); } else { // Do not wrap help description, but indent newlines appropriately. var helpLines = help.split('\n').filter( function (ln) { return ln.length }); if (helpEnv !== '') { helpLines.push(helpEnv); } if (helpDefault) { helpLines.push(helpDefault); } line += helpLines.join('\n' + space(helpCol)); } lines[i] = line; }); var rv = ''; if (lines.length > 0) { rv = lines.join('\n') + '\n'; } return rv; }; /** * Return a string suitable for a Bash completion file for this tool. * * @param args.name {String} The tool name. * @param args.specExtra {String} Optional. Extra Bash code content to add * to the end of the "spec". Typically this is used to append Bash * "complete_TYPE" functions for custom option types. See * "examples/ddcompletion.js" for an example. * @param args.argtypes {Array} Optional. Array of completion types for * positional args (i.e. non-options). E.g. * argtypes = ['fruit', 'veggie', 'file'] * will result in completion of fruits for the first arg, veggies for the * second, and filenames for the third and subsequent positional args. * If not given, positional args will use Bash's 'default' completion. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g. * `complete_fruit` and `complete_veggie` in this example. */ Parser.prototype.bashCompletion = function bashCompletion(args) { assert.object(args, 'args'); assert.string(args.name, 'args.name'); assert.optionalString(args.specExtra, 'args.specExtra'); assert.optionalArrayOfString(args.argtypes, 'args.argtypes'); return bashCompletionFromOptions({ name: args.name, specExtra: args.specExtra, argtypes: args.argtypes, options: this.options }); }; // ---- Bash completion const BASH_COMPLETION_TEMPLATE_PATH = path.join( __dirname, '../etc/dashdash.bash_completion.in'); /** * Return the Bash completion "spec" (the string value for the "{{spec}}" * var in the "dashdash.bash_completion.in" template) for this tool. * * The "spec" is Bash code that defines the CLI options and subcmds for * the template's completion code. It looks something like this: * * local cmd_shortopts="-J ..." * local cmd_longopts="--help ..." * local cmd_optargs="-p=tritonprofile ..." * * @param args.options {Array} The array of dashdash option specs. * @param args.context {String} Optional. A context string for the "local cmd*" * vars in the spec. By default it is the empty string. When used to * scope for completion on a *sub-command* (e.g. for "git log" on a "git" * tool), then it would have a value (e.g. "__log"). See * <http://github.com/trentm/node-cmdln> Bash completion for details. * @param opts.includeHidden {Boolean} Optional. Default false. By default * hidden options and subcmds are "excluded". Here excluded means they * won't be offered as a completion, but if used, their argument type * will be completed. "Hidden" options and subcmds are ones with the * `hidden: true` attribute to exclude them from default help output. * @param args.argtypes {Array} Optional. Array of completion types for * positional args (i.e. non-options). E.g. * argtypes = ['fruit', 'veggie', 'file'] * will result in completion of fruits for the first arg, veggies for the * second, and filenames for the third and subsequent positional args. * If not given, positional args will use Bash's 'default' completion. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g. * `complete_fruit` and `complete_veggie` in this example. */ function bashCompletionSpecFromOptions(args) { assert.object(args, 'args'); assert.object(args.options, 'args.options'); assert.optionalString(args.context, 'args.context'); assert.optionalBool(args.includeHidden, 'args.includeHidden'); assert.optionalArrayOfString(args.argtypes, 'args.argtypes'); var context = args.context || ''; var includeHidden = (args.includeHidden === undefined ? false : args.includeHidden); var spec = []; var shortopts = []; var longopts = []; var optargs = []; (args.options || []).forEach(function (o) { if (o.group !== undefined && o.group !== null) { // Skip group headers. return; } var optNames = o.names || [o.name]; var optType = getOptionType(o.type); if (optType.takesArg) { var completionType = o.completionType || optType.completionType || o.type; optNames.forEach(function (optName) { if (optName.length === 1) { if (includeHidden || !o.hidden) { shortopts.push('-' + optName); } // Include even hidden options in `optargs` so that bash // completion of its arg still works. optargs.push('-' + optName + '=' + completionType); } else { if (includeHidden || !o.hidden) { longopts.push('--' + optName); } optargs.push('--' + optName + '=' + completionType); } }); } else { optNames.forEach(function (optName) { if (includeHidden || !o.hidden) { if (optName.length === 1) { shortopts.push('-' + optName); } else { longopts.push('--' + optName); } } }); } }); spec.push(format('local cmd%s_shortopts="%s"', context, shortopts.sort().join(' '))); spec.push(format('local cmd%s_longopts="%s"', context, longopts.sort().join(' '))); spec.push(format('local cmd%s_optargs="%s"', context, optargs.sort().join(' '))); if (args.argtypes) { spec.push(format('local cmd%s_argtypes="%s"', context, args.argtypes.join(' '))); } return spec.join('\n'); } /** * Return a string suitable for a Bash completion file for this tool. * * @param args.name {String} The tool name. * @param args.options {Array} The array of dashdash option specs. * @param args.specExtra {String} Optional. Extra Bash code content to add * to the end of the "spec". Typically this is used to append Bash * "complete_TYPE" functions for custom option types. See * "examples/ddcompletion.js" for an example. * @param args.argtypes {Array} Optional. Array of completion types for * positional args (i.e. non-options). E.g. * argtypes = ['fruit', 'veggie', 'file'] * will result in completion of fruits for the first arg, veggies for the * second, and filenames for the third and subsequent positional args. * If not given, positional args will use Bash's 'default' completion. * See `specExtra` for providing Bash `complete_TYPE` functions, e.g. * `complete_fruit` and `complete_veggie` in this example. */ function bashCompletionFromOptions(args) { assert.object(args, 'args'); assert.object(args.options, 'args.options'); assert.string(args.name, 'args.name'); assert.optionalString(args.specExtra, 'args.specExtra'); assert.optionalArrayOfString(args.argtypes, 'args.argtypes'); // Gather template data. var data = { name: args.name, date: new Date(), spec: bashCompletionSpecFromOptions({ options: args.options, argtypes: args.argtypes }), }; if (args.specExtra) { data.spec += '\n\n' + args.specExtra; } // Render template. var template = fs.readFileSync(BASH_COMPLETION_TEMPLATE_PATH, 'utf8'); return renderTemplate(template, data); } // ---- exports function createParser(config) { return new Parser(config); } /** * Parse argv with the given options. * * @param config {Object} A merge of all the available fields from * `dashdash.Parser` and `dashdash.Parser.parse`: options, interspersed, * argv, env, slice. */ function parse(config) { assert.object(config, 'config'); assert.optionalArrayOfString(config.argv, 'config.argv'); assert.optionalObject(config.env, 'config.env'); var config = shallowCopy(config); var argv = config.argv; delete config.argv; var env = config.env; delete config.env; var parser = new Parser(config); return parser.parse({argv: argv, env: env}); } /** * Add a new option type. * * @params optionType {Object}: * - name {String} Required. * - takesArg {Boolean} Required. Whether this type of option takes an * argument on process.argv. Typically this is true for all but the * "bool" type. * - helpArg {String} Required iff `takesArg === true`. The string to * show in generated help for options of this type. * - parseArg {Function} Require. `function (option, optstr, arg)` parser * that takes a string argument and returns an instance of the * appropriate type, or throws an error if the arg is invalid. * - array {Boolean} Optional. Set to true if this is an 'arrayOf' type * that collects multiple usages of the option in process.argv and * puts results in an array. * - arrayFlatten {Boolean} Optional. XXX * - default Optional. Default value for options of this type, if no * default is specified in the option type usage. */ function addOptionType(optionType) { assert.object(optionType, 'optionType'); assert.string(optionType.name, 'optionType.name'); assert.bool(optionType.takesArg, 'optionType.takesArg'); if (optionType.takesArg) { assert.string(optionType.helpArg, 'optionType.helpArg'); } assert.func(optionType.parseArg, 'optionType.parseArg'); assert.optionalBool(optionType.array, 'optionType.array'); assert.optionalBool(optionType.arrayFlatten, 'optionType.arrayFlatten'); optionTypes[optionType.name] = { takesArg: optionType.takesArg, helpArg: optionType.helpArg, parseArg: optionType.parseArg, array: optionType.array, arrayFlatten: optionType.arrayFlatten, default: optionType.default } } function getOptionType(name) { assert.string(name, 'name'); return optionTypes[name]; } /** * Return a synopsis string for the given option spec. * * Examples: * > synopsisFromOpt({names: ['help', 'h'], type: 'bool'}); * '[ --help | -h ]' * > synopsisFromOpt({name: 'file', type: 'string', helpArg: 'FILE'}); * '[ --file=FILE ]' */ function synopsisFromOpt(o) { assert.object(o, 'o'); if (o.hasOwnProperty('group')) { return null; } var names = o.names || [o.name]; // `type` here could be undefined if, for example, the command has a // dashdash option spec with a bogus 'type'. var type = getOptionType(o.type); var helpArg = o.helpArg || (type && type.helpArg) || 'ARG'; var parts = []; names.forEach(function (name) { var part = (name.length === 1 ? '-' : '--') + name; if (type && type.takesArg) { part += (name.length === 1 ? ' ' + helpArg : '=' + helpArg); } parts.push(part); }); return ('[ ' + parts.join(' | ') + ' ]'); }; module.exports = { createParser: createParser, Parser: Parser, parse: parse, addOptionType: addOptionType, getOptionType: getOptionType, synopsisFromOpt: synopsisFromOpt, // Bash completion-related exports BASH_COMPLETION_TEMPLATE_PATH: BASH_COMPLETION_TEMPLATE_PATH, bashCompletionFromOptions: bashCompletionFromOptions, bashCompletionSpecFromOptions: bashCompletionSpecFromOptions, // Export the parseFoo parsers because they might be useful as primitives // for custom option types. parseBool: parseBool, parseString: parseString, parseNumber: parseNumber, parseInteger: parseInteger, parsePositiveInteger: parsePositiveInteger, parseDate: parseDate };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/dashdash/lib/dashdash.js
dashdash.js
### Estraverse [![Build Status](https://secure.travis-ci.org/estools/estraverse.svg)](http://travis-ci.org/estools/estraverse) Estraverse ([estraverse](http://github.com/estools/estraverse)) is [ECMAScript](http://www.ecma-international.org/publications/standards/Ecma-262.htm) traversal functions from [esmangle project](http://github.com/estools/esmangle). ### Documentation You can find usage docs at [wiki page](https://github.com/estools/estraverse/wiki/Usage). ### Example Usage The following code will output all variables declared at the root of a file. ```javascript estraverse.traverse(ast, { enter: function (node, parent) { if (node.type == 'FunctionExpression' || node.type == 'FunctionDeclaration') return estraverse.VisitorOption.Skip; }, leave: function (node, parent) { if (node.type == 'VariableDeclarator') console.log(node.id.name); } }); ``` We can use `this.skip`, `this.remove` and `this.break` functions instead of using Skip, Remove and Break. ```javascript estraverse.traverse(ast, { enter: function (node) { this.break(); } }); ``` And estraverse provides `estraverse.replace` function. When returning node from `enter`/`leave`, current node is replaced with it. ```javascript result = estraverse.replace(tree, { enter: function (node) { // Replace it with replaced. if (node.type === 'Literal') return replaced; } }); ``` By passing `visitor.keys` mapping, we can extend estraverse traversing functionality. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Extending the existing traversing rules. keys: { // TargetNodeName: [ 'keys', 'containing', 'the', 'other', '**node**' ] TestExpression: ['argument'] } }); ``` By passing `visitor.fallback` option, we can control the behavior when encountering unknown nodes. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Iterating the child **nodes** of unknown nodes. fallback: 'iteration' }); ``` When `visitor.fallback` is a function, we can determine which keys to visit on each node. ```javascript // This tree contains a user-defined `TestExpression` node. var tree = { type: 'TestExpression', // This 'argument' is the property containing the other **node**. argument: { type: 'Literal', value: 20 }, // This 'extended' is the property not containing the other **node**. extended: true }; estraverse.traverse(tree, { enter: function (node) { }, // Skip the `argument` property of each node fallback: function(node) { return Object.keys(node).filter(function(key) { return key !== 'argument'; }); } }); ``` ### License Copyright (C) 2012-2016 [Yusuke Suzuki](http://github.com/Constellation) (twitter: [@Constellation](http://twitter.com/Constellation)) and other contributors. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * 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. 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 <COPYRIGHT HOLDER> 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.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/estraverse/README.md
README.md
(function clone(exports) { 'use strict'; var Syntax, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE; function deepCopy(obj) { var ret = {}, key, val; for (key in obj) { if (obj.hasOwnProperty(key)) { val = obj[key]; if (typeof val === 'object' && val !== null) { ret[key] = deepCopy(val); } else { ret[key] = val; } } } return ret; } // based on LLVM libc++ upper_bound / lower_bound // MIT License function upperBound(array, func) { var diff, len, i, current; len = array.length; i = 0; while (len) { diff = len >>> 1; current = i + diff; if (func(array[current])) { len = diff; } else { i = current + 1; len -= diff + 1; } } return i; } Syntax = { AssignmentExpression: 'AssignmentExpression', AssignmentPattern: 'AssignmentPattern', ArrayExpression: 'ArrayExpression', ArrayPattern: 'ArrayPattern', ArrowFunctionExpression: 'ArrowFunctionExpression', AwaitExpression: 'AwaitExpression', // CAUTION: It's deferred to ES7. BlockStatement: 'BlockStatement', BinaryExpression: 'BinaryExpression', BreakStatement: 'BreakStatement', CallExpression: 'CallExpression', CatchClause: 'CatchClause', ClassBody: 'ClassBody', ClassDeclaration: 'ClassDeclaration', ClassExpression: 'ClassExpression', ComprehensionBlock: 'ComprehensionBlock', // CAUTION: It's deferred to ES7. ComprehensionExpression: 'ComprehensionExpression', // CAUTION: It's deferred to ES7. ConditionalExpression: 'ConditionalExpression', ContinueStatement: 'ContinueStatement', DebuggerStatement: 'DebuggerStatement', DirectiveStatement: 'DirectiveStatement', DoWhileStatement: 'DoWhileStatement', EmptyStatement: 'EmptyStatement', ExportAllDeclaration: 'ExportAllDeclaration', ExportDefaultDeclaration: 'ExportDefaultDeclaration', ExportNamedDeclaration: 'ExportNamedDeclaration', ExportSpecifier: 'ExportSpecifier', ExpressionStatement: 'ExpressionStatement', ForStatement: 'ForStatement', ForInStatement: 'ForInStatement', ForOfStatement: 'ForOfStatement', FunctionDeclaration: 'FunctionDeclaration', FunctionExpression: 'FunctionExpression', GeneratorExpression: 'GeneratorExpression', // CAUTION: It's deferred to ES7. Identifier: 'Identifier', IfStatement: 'IfStatement', ImportExpression: 'ImportExpression', ImportDeclaration: 'ImportDeclaration', ImportDefaultSpecifier: 'ImportDefaultSpecifier', ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', ImportSpecifier: 'ImportSpecifier', Literal: 'Literal', LabeledStatement: 'LabeledStatement', LogicalExpression: 'LogicalExpression', MemberExpression: 'MemberExpression', MetaProperty: 'MetaProperty', MethodDefinition: 'MethodDefinition', ModuleSpecifier: 'ModuleSpecifier', NewExpression: 'NewExpression', ObjectExpression: 'ObjectExpression', ObjectPattern: 'ObjectPattern', Program: 'Program', Property: 'Property', RestElement: 'RestElement', ReturnStatement: 'ReturnStatement', SequenceExpression: 'SequenceExpression', SpreadElement: 'SpreadElement', Super: 'Super', SwitchStatement: 'SwitchStatement', SwitchCase: 'SwitchCase', TaggedTemplateExpression: 'TaggedTemplateExpression', TemplateElement: 'TemplateElement', TemplateLiteral: 'TemplateLiteral', ThisExpression: 'ThisExpression', ThrowStatement: 'ThrowStatement', TryStatement: 'TryStatement', UnaryExpression: 'UnaryExpression', UpdateExpression: 'UpdateExpression', VariableDeclaration: 'VariableDeclaration', VariableDeclarator: 'VariableDeclarator', WhileStatement: 'WhileStatement', WithStatement: 'WithStatement', YieldExpression: 'YieldExpression' }; VisitorKeys = { AssignmentExpression: ['left', 'right'], AssignmentPattern: ['left', 'right'], ArrayExpression: ['elements'], ArrayPattern: ['elements'], ArrowFunctionExpression: ['params', 'body'], AwaitExpression: ['argument'], // CAUTION: It's deferred to ES7. BlockStatement: ['body'], BinaryExpression: ['left', 'right'], BreakStatement: ['label'], CallExpression: ['callee', 'arguments'], CatchClause: ['param', 'body'], ClassBody: ['body'], ClassDeclaration: ['id', 'superClass', 'body'], ClassExpression: ['id', 'superClass', 'body'], ComprehensionBlock: ['left', 'right'], // CAUTION: It's deferred to ES7. ComprehensionExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. ConditionalExpression: ['test', 'consequent', 'alternate'], ContinueStatement: ['label'], DebuggerStatement: [], DirectiveStatement: [], DoWhileStatement: ['body', 'test'], EmptyStatement: [], ExportAllDeclaration: ['source'], ExportDefaultDeclaration: ['declaration'], ExportNamedDeclaration: ['declaration', 'specifiers', 'source'], ExportSpecifier: ['exported', 'local'], ExpressionStatement: ['expression'], ForStatement: ['init', 'test', 'update', 'body'], ForInStatement: ['left', 'right', 'body'], ForOfStatement: ['left', 'right', 'body'], FunctionDeclaration: ['id', 'params', 'body'], FunctionExpression: ['id', 'params', 'body'], GeneratorExpression: ['blocks', 'filter', 'body'], // CAUTION: It's deferred to ES7. Identifier: [], IfStatement: ['test', 'consequent', 'alternate'], ImportExpression: ['source'], ImportDeclaration: ['specifiers', 'source'], ImportDefaultSpecifier: ['local'], ImportNamespaceSpecifier: ['local'], ImportSpecifier: ['imported', 'local'], Literal: [], LabeledStatement: ['label', 'body'], LogicalExpression: ['left', 'right'], MemberExpression: ['object', 'property'], MetaProperty: ['meta', 'property'], MethodDefinition: ['key', 'value'], ModuleSpecifier: [], NewExpression: ['callee', 'arguments'], ObjectExpression: ['properties'], ObjectPattern: ['properties'], Program: ['body'], Property: ['key', 'value'], RestElement: [ 'argument' ], ReturnStatement: ['argument'], SequenceExpression: ['expressions'], SpreadElement: ['argument'], Super: [], SwitchStatement: ['discriminant', 'cases'], SwitchCase: ['test', 'consequent'], TaggedTemplateExpression: ['tag', 'quasi'], TemplateElement: [], TemplateLiteral: ['quasis', 'expressions'], ThisExpression: [], ThrowStatement: ['argument'], TryStatement: ['block', 'handler', 'finalizer'], UnaryExpression: ['argument'], UpdateExpression: ['argument'], VariableDeclaration: ['declarations'], VariableDeclarator: ['id', 'init'], WhileStatement: ['test', 'body'], WithStatement: ['object', 'body'], YieldExpression: ['argument'] }; // unique id BREAK = {}; SKIP = {}; REMOVE = {}; VisitorOption = { Break: BREAK, Skip: SKIP, Remove: REMOVE }; function Reference(parent, key) { this.parent = parent; this.key = key; } Reference.prototype.replace = function replace(node) { this.parent[this.key] = node; }; Reference.prototype.remove = function remove() { if (Array.isArray(this.parent)) { this.parent.splice(this.key, 1); return true; } else { this.replace(null); return false; } }; function Element(node, path, wrap, ref) { this.node = node; this.path = path; this.wrap = wrap; this.ref = ref; } function Controller() { } // API: // return property path array from root to current node Controller.prototype.path = function path() { var i, iz, j, jz, result, element; function addToPath(result, path) { if (Array.isArray(path)) { for (j = 0, jz = path.length; j < jz; ++j) { result.push(path[j]); } } else { result.push(path); } } // root node if (!this.__current.path) { return null; } // first node is sentinel, second node is root element result = []; for (i = 2, iz = this.__leavelist.length; i < iz; ++i) { element = this.__leavelist[i]; addToPath(result, element.path); } addToPath(result, this.__current.path); return result; }; // API: // return type of current node Controller.prototype.type = function () { var node = this.current(); return node.type || this.__current.wrap; }; // API: // return array of parent elements Controller.prototype.parents = function parents() { var i, iz, result; // first node is sentinel result = []; for (i = 1, iz = this.__leavelist.length; i < iz; ++i) { result.push(this.__leavelist[i].node); } return result; }; // API: // return current node Controller.prototype.current = function current() { return this.__current.node; }; Controller.prototype.__execute = function __execute(callback, element) { var previous, result; result = undefined; previous = this.__current; this.__current = element; this.__state = null; if (callback) { result = callback.call(this, element.node, this.__leavelist[this.__leavelist.length - 1].node); } this.__current = previous; return result; }; // API: // notify control skip / break Controller.prototype.notify = function notify(flag) { this.__state = flag; }; // API: // skip child nodes of current node Controller.prototype.skip = function () { this.notify(SKIP); }; // API: // break traversals Controller.prototype['break'] = function () { this.notify(BREAK); }; // API: // remove node Controller.prototype.remove = function () { this.notify(REMOVE); }; Controller.prototype.__initialize = function(root, visitor) { this.visitor = visitor; this.root = root; this.__worklist = []; this.__leavelist = []; this.__current = null; this.__state = null; this.__fallback = null; if (visitor.fallback === 'iteration') { this.__fallback = Object.keys; } else if (typeof visitor.fallback === 'function') { this.__fallback = visitor.fallback; } this.__keys = VisitorKeys; if (visitor.keys) { this.__keys = Object.assign(Object.create(this.__keys), visitor.keys); } }; function isNode(node) { if (node == null) { return false; } return typeof node === 'object' && typeof node.type === 'string'; } function isProperty(nodeType, key) { return (nodeType === Syntax.ObjectExpression || nodeType === Syntax.ObjectPattern) && 'properties' === key; } Controller.prototype.traverse = function traverse(root, visitor) { var worklist, leavelist, element, node, nodeType, ret, key, current, current2, candidates, candidate, sentinel; this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize worklist.push(new Element(root, null, null, null)); leavelist.push(new Element(null, null, null, null)); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); ret = this.__execute(visitor.leave, element); if (this.__state === BREAK || ret === BREAK) { return; } continue; } if (element.node) { ret = this.__execute(visitor.enter, element); if (this.__state === BREAK || ret === BREAK) { return; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || ret === SKIP) { continue; } node = element.node; nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (Array.isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', null); } else if (isNode(candidate[current2])) { element = new Element(candidate[current2], [key, current2], null, null); } else { continue; } worklist.push(element); } } else if (isNode(candidate)) { worklist.push(new Element(candidate, key, null, null)); } } } } }; Controller.prototype.replace = function replace(root, visitor) { var worklist, leavelist, node, nodeType, target, element, current, current2, candidates, candidate, sentinel, outer, key; function removeElem(element) { var i, key, nextElem, parent; if (element.ref.remove()) { // When the reference is an element of an array. key = element.ref.key; parent = element.ref.parent; // If removed from array, then decrease following items' keys. i = worklist.length; while (i--) { nextElem = worklist[i]; if (nextElem.ref && nextElem.ref.parent === parent) { if (nextElem.ref.key < key) { break; } --nextElem.ref.key; } } } } this.__initialize(root, visitor); sentinel = {}; // reference worklist = this.__worklist; leavelist = this.__leavelist; // initialize outer = { root: root }; element = new Element(root, null, null, new Reference(outer, 'root')); worklist.push(element); leavelist.push(element); while (worklist.length) { element = worklist.pop(); if (element === sentinel) { element = leavelist.pop(); target = this.__execute(visitor.leave, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); } if (this.__state === BREAK || target === BREAK) { return outer.root; } continue; } target = this.__execute(visitor.enter, element); // node may be replaced with null, // so distinguish between undefined and null in this place if (target !== undefined && target !== BREAK && target !== SKIP && target !== REMOVE) { // replace element.ref.replace(target); element.node = target; } if (this.__state === REMOVE || target === REMOVE) { removeElem(element); element.node = null; } if (this.__state === BREAK || target === BREAK) { return outer.root; } // node may be null node = element.node; if (!node) { continue; } worklist.push(sentinel); leavelist.push(element); if (this.__state === SKIP || target === SKIP) { continue; } nodeType = node.type || element.wrap; candidates = this.__keys[nodeType]; if (!candidates) { if (this.__fallback) { candidates = this.__fallback(node); } else { throw new Error('Unknown node type ' + nodeType + '.'); } } current = candidates.length; while ((current -= 1) >= 0) { key = candidates[current]; candidate = node[key]; if (!candidate) { continue; } if (Array.isArray(candidate)) { current2 = candidate.length; while ((current2 -= 1) >= 0) { if (!candidate[current2]) { continue; } if (isProperty(nodeType, candidates[current])) { element = new Element(candidate[current2], [key, current2], 'Property', new Reference(candidate, current2)); } else if (isNode(candidate[current2])) { element = new Element(candidate[current2], [key, current2], null, new Reference(candidate, current2)); } else { continue; } worklist.push(element); } } else if (isNode(candidate)) { worklist.push(new Element(candidate, key, null, new Reference(node, key))); } } } return outer.root; }; function traverse(root, visitor) { var controller = new Controller(); return controller.traverse(root, visitor); } function replace(root, visitor) { var controller = new Controller(); return controller.replace(root, visitor); } function extendCommentRange(comment, tokens) { var target; target = upperBound(tokens, function search(token) { return token.range[0] > comment.range[0]; }); comment.extendedRange = [comment.range[0], comment.range[1]]; if (target !== tokens.length) { comment.extendedRange[1] = tokens[target].range[0]; } target -= 1; if (target >= 0) { comment.extendedRange[0] = tokens[target].range[1]; } return comment; } function attachComments(tree, providedComments, tokens) { // At first, we should calculate extended comment ranges. var comments = [], comment, len, i, cursor; if (!tree.range) { throw new Error('attachComments needs range information'); } // tokens array is empty, we attach comments to tree as 'leadingComments' if (!tokens.length) { if (providedComments.length) { for (i = 0, len = providedComments.length; i < len; i += 1) { comment = deepCopy(providedComments[i]); comment.extendedRange = [0, tree.range[0]]; comments.push(comment); } tree.leadingComments = comments; } return tree; } for (i = 0, len = providedComments.length; i < len; i += 1) { comments.push(extendCommentRange(deepCopy(providedComments[i]), tokens)); } // This is based on John Freeman's implementation. cursor = 0; traverse(tree, { enter: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (comment.extendedRange[1] > node.range[0]) { break; } if (comment.extendedRange[1] === node.range[0]) { if (!node.leadingComments) { node.leadingComments = []; } node.leadingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); cursor = 0; traverse(tree, { leave: function (node) { var comment; while (cursor < comments.length) { comment = comments[cursor]; if (node.range[1] < comment.extendedRange[0]) { break; } if (node.range[1] === comment.extendedRange[0]) { if (!node.trailingComments) { node.trailingComments = []; } node.trailingComments.push(comment); comments.splice(cursor, 1); } else { cursor += 1; } } // already out of owned node if (cursor === comments.length) { return VisitorOption.Break; } if (comments[cursor].extendedRange[0] > node.range[1]) { return VisitorOption.Skip; } } }); return tree; } exports.version = require('estraverse/package.json').version; exports.Syntax = Syntax; exports.traverse = traverse; exports.replace = replace; exports.attachComments = attachComments; exports.VisitorKeys = VisitorKeys; exports.VisitorOption = VisitorOption; exports.Controller = Controller; exports.cloneEnvironment = function () { return clone({}); }; return exports; }(exports)); /* vim: set sw=4 ts=4 et tw=80 : */
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/estraverse/estraverse.js
estraverse.js
# qs <sup>[![Version Badge][2]][1]</sup> [![Build Status][3]][4] [![dependency status][5]][6] [![dev dependency status][7]][8] [![License][license-image]][license-url] [![Downloads][downloads-image]][downloads-url] [![npm badge][11]][1] A querystring parsing and stringifying library with some added security. Lead Maintainer: [Jordan Harband](https://github.com/ljharb) The **qs** module was originally created and maintained by [TJ Holowaychuk](https://github.com/visionmedia/node-querystring). ## Usage ```javascript var qs = require('qs'); var assert = require('assert'); var obj = qs.parse('a=c'); assert.deepEqual(obj, { a: 'c' }); var str = qs.stringify(obj); assert.equal(str, 'a=c'); ``` ### Parsing Objects [](#preventEval) ```javascript qs.parse(string, [options]); ``` **qs** allows you to create nested objects within your query strings, by surrounding the name of sub-keys with square brackets `[]`. For example, the string `'foo[bar]=baz'` converts to: ```javascript assert.deepEqual(qs.parse('foo[bar]=baz'), { foo: { bar: 'baz' } }); ``` When using the `plainObjects` option the parsed value is returned as a null object, created via `Object.create(null)` and as such you should be aware that prototype methods will not exist on it and a user may set those names to whatever value they like: ```javascript var nullObject = qs.parse('a[hasOwnProperty]=b', { plainObjects: true }); assert.deepEqual(nullObject, { a: { hasOwnProperty: 'b' } }); ``` By default parameters that would overwrite properties on the object prototype are ignored, if you wish to keep the data from those fields either use `plainObjects` as mentioned above, or set `allowPrototypes` to `true` which will allow user input to overwrite those properties. *WARNING* It is generally a bad idea to enable this option as it can cause problems when attempting to use the properties that have been overwritten. Always be careful with this option. ```javascript var protoObject = qs.parse('a[hasOwnProperty]=b', { allowPrototypes: true }); assert.deepEqual(protoObject, { a: { hasOwnProperty: 'b' } }); ``` URI encoded strings work too: ```javascript assert.deepEqual(qs.parse('a%5Bb%5D=c'), { a: { b: 'c' } }); ``` You can also nest your objects, like `'foo[bar][baz]=foobarbaz'`: ```javascript assert.deepEqual(qs.parse('foo[bar][baz]=foobarbaz'), { foo: { bar: { baz: 'foobarbaz' } } }); ``` By default, when nesting objects **qs** will only parse up to 5 children deep. This means if you attempt to parse a string like `'a[b][c][d][e][f][g][h][i]=j'` your resulting object will be: ```javascript var expected = { a: { b: { c: { d: { e: { f: { '[g][h][i]': 'j' } } } } } } }; var string = 'a[b][c][d][e][f][g][h][i]=j'; assert.deepEqual(qs.parse(string), expected); ``` This depth can be overridden by passing a `depth` option to `qs.parse(string, [options])`: ```javascript var deep = qs.parse('a[b][c][d][e][f][g][h][i]=j', { depth: 1 }); assert.deepEqual(deep, { a: { b: { '[c][d][e][f][g][h][i]': 'j' } } }); ``` The depth limit helps mitigate abuse when **qs** is used to parse user input, and it is recommended to keep it a reasonably small number. For similar reasons, by default **qs** will only parse up to 1000 parameters. This can be overridden by passing a `parameterLimit` option: ```javascript var limited = qs.parse('a=b&c=d', { parameterLimit: 1 }); assert.deepEqual(limited, { a: 'b' }); ``` To bypass the leading question mark, use `ignoreQueryPrefix`: ```javascript var prefixed = qs.parse('?a=b&c=d', { ignoreQueryPrefix: true }); assert.deepEqual(prefixed, { a: 'b', c: 'd' }); ``` An optional delimiter can also be passed: ```javascript var delimited = qs.parse('a=b;c=d', { delimiter: ';' }); assert.deepEqual(delimited, { a: 'b', c: 'd' }); ``` Delimiters can be a regular expression too: ```javascript var regexed = qs.parse('a=b;c=d,e=f', { delimiter: /[;,]/ }); assert.deepEqual(regexed, { a: 'b', c: 'd', e: 'f' }); ``` Option `allowDots` can be used to enable dot notation: ```javascript var withDots = qs.parse('a.b=c', { allowDots: true }); assert.deepEqual(withDots, { a: { b: 'c' } }); ``` ### Parsing Arrays **qs** can also parse arrays using a similar `[]` notation: ```javascript var withArray = qs.parse('a[]=b&a[]=c'); assert.deepEqual(withArray, { a: ['b', 'c'] }); ``` You may specify an index as well: ```javascript var withIndexes = qs.parse('a[1]=c&a[0]=b'); assert.deepEqual(withIndexes, { a: ['b', 'c'] }); ``` Note that the only difference between an index in an array and a key in an object is that the value between the brackets must be a number to create an array. When creating arrays with specific indices, **qs** will compact a sparse array to only the existing values preserving their order: ```javascript var noSparse = qs.parse('a[1]=b&a[15]=c'); assert.deepEqual(noSparse, { a: ['b', 'c'] }); ``` Note that an empty string is also a value, and will be preserved: ```javascript var withEmptyString = qs.parse('a[]=&a[]=b'); assert.deepEqual(withEmptyString, { a: ['', 'b'] }); var withIndexedEmptyString = qs.parse('a[0]=b&a[1]=&a[2]=c'); assert.deepEqual(withIndexedEmptyString, { a: ['b', '', 'c'] }); ``` **qs** will also limit specifying indices in an array to a maximum index of `20`. Any array members with an index of greater than `20` will instead be converted to an object with the index as the key: ```javascript var withMaxIndex = qs.parse('a[100]=b'); assert.deepEqual(withMaxIndex, { a: { '100': 'b' } }); ``` This limit can be overridden by passing an `arrayLimit` option: ```javascript var withArrayLimit = qs.parse('a[1]=b', { arrayLimit: 0 }); assert.deepEqual(withArrayLimit, { a: { '1': 'b' } }); ``` To disable array parsing entirely, set `parseArrays` to `false`. ```javascript var noParsingArrays = qs.parse('a[]=b', { parseArrays: false }); assert.deepEqual(noParsingArrays, { a: { '0': 'b' } }); ``` If you mix notations, **qs** will merge the two items into an object: ```javascript var mixedNotation = qs.parse('a[0]=b&a[b]=c'); assert.deepEqual(mixedNotation, { a: { '0': 'b', b: 'c' } }); ``` You can also create arrays of objects: ```javascript var arraysOfObjects = qs.parse('a[][b]=c'); assert.deepEqual(arraysOfObjects, { a: [{ b: 'c' }] }); ``` ### Stringifying [](#preventEval) ```javascript qs.stringify(object, [options]); ``` When stringifying, **qs** by default URI encodes output. Objects are stringified as you would expect: ```javascript assert.equal(qs.stringify({ a: 'b' }), 'a=b'); assert.equal(qs.stringify({ a: { b: 'c' } }), 'a%5Bb%5D=c'); ``` This encoding can be disabled by setting the `encode` option to `false`: ```javascript var unencoded = qs.stringify({ a: { b: 'c' } }, { encode: false }); assert.equal(unencoded, 'a[b]=c'); ``` Encoding can be disabled for keys by setting the `encodeValuesOnly` option to `true`: ```javascript var encodedValues = qs.stringify( { a: 'b', c: ['d', 'e=f'], f: [['g'], ['h']] }, { encodeValuesOnly: true } ); assert.equal(encodedValues,'a=b&c[0]=d&c[1]=e%3Df&f[0][0]=g&f[1][0]=h'); ``` This encoding can also be replaced by a custom encoding method set as `encoder` option: ```javascript var encoded = qs.stringify({ a: { b: 'c' } }, { encoder: function (str) { // Passed in values `a`, `b`, `c` return // Return encoded string }}) ``` _(Note: the `encoder` option does not apply if `encode` is `false`)_ Analogue to the `encoder` there is a `decoder` option for `parse` to override decoding of properties and values: ```javascript var decoded = qs.parse('x=z', { decoder: function (str) { // Passed in values `x`, `z` return // Return decoded string }}) ``` Examples beyond this point will be shown as though the output is not URI encoded for clarity. Please note that the return values in these cases *will* be URI encoded during real usage. When arrays are stringified, by default they are given explicit indices: ```javascript qs.stringify({ a: ['b', 'c', 'd'] }); // 'a[0]=b&a[1]=c&a[2]=d' ``` You may override this by setting the `indices` option to `false`: ```javascript qs.stringify({ a: ['b', 'c', 'd'] }, { indices: false }); // 'a=b&a=c&a=d' ``` You may use the `arrayFormat` option to specify the format of the output array: ```javascript qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'indices' }) // 'a[0]=b&a[1]=c' qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'brackets' }) // 'a[]=b&a[]=c' qs.stringify({ a: ['b', 'c'] }, { arrayFormat: 'repeat' }) // 'a=b&a=c' ``` When objects are stringified, by default they use bracket notation: ```javascript qs.stringify({ a: { b: { c: 'd', e: 'f' } } }); // 'a[b][c]=d&a[b][e]=f' ``` You may override this to use dot notation by setting the `allowDots` option to `true`: ```javascript qs.stringify({ a: { b: { c: 'd', e: 'f' } } }, { allowDots: true }); // 'a.b.c=d&a.b.e=f' ``` Empty strings and null values will omit the value, but the equals sign (=) remains in place: ```javascript assert.equal(qs.stringify({ a: '' }), 'a='); ``` Key with no values (such as an empty object or array) will return nothing: ```javascript assert.equal(qs.stringify({ a: [] }), ''); assert.equal(qs.stringify({ a: {} }), ''); assert.equal(qs.stringify({ a: [{}] }), ''); assert.equal(qs.stringify({ a: { b: []} }), ''); assert.equal(qs.stringify({ a: { b: {}} }), ''); ``` Properties that are set to `undefined` will be omitted entirely: ```javascript assert.equal(qs.stringify({ a: null, b: undefined }), 'a='); ``` The query string may optionally be prepended with a question mark: ```javascript assert.equal(qs.stringify({ a: 'b', c: 'd' }, { addQueryPrefix: true }), '?a=b&c=d'); ``` The delimiter may be overridden with stringify as well: ```javascript assert.equal(qs.stringify({ a: 'b', c: 'd' }, { delimiter: ';' }), 'a=b;c=d'); ``` If you only want to override the serialization of `Date` objects, you can provide a `serializeDate` option: ```javascript var date = new Date(7); assert.equal(qs.stringify({ a: date }), 'a=1970-01-01T00:00:00.007Z'.replace(/:/g, '%3A')); assert.equal( qs.stringify({ a: date }, { serializeDate: function (d) { return d.getTime(); } }), 'a=7' ); ``` You may use the `sort` option to affect the order of parameter keys: ```javascript function alphabeticalSort(a, b) { return a.localeCompare(b); } assert.equal(qs.stringify({ a: 'c', z: 'y', b : 'f' }, { sort: alphabeticalSort }), 'a=c&b=f&z=y'); ``` Finally, you can use the `filter` option to restrict which keys will be included in the stringified output. If you pass a function, it will be called for each key to obtain the replacement value. Otherwise, if you pass an array, it will be used to select properties and array indices for stringification: ```javascript function filterFunc(prefix, value) { if (prefix == 'b') { // Return an `undefined` value to omit a property. return; } if (prefix == 'e[f]') { return value.getTime(); } if (prefix == 'e[g][0]') { return value * 2; } return value; } qs.stringify({ a: 'b', c: 'd', e: { f: new Date(123), g: [2] } }, { filter: filterFunc }); // 'a=b&c=d&e[f]=123&e[g][0]=4' qs.stringify({ a: 'b', c: 'd', e: 'f' }, { filter: ['a', 'e'] }); // 'a=b&e=f' qs.stringify({ a: ['b', 'c', 'd'], e: 'f' }, { filter: ['a', 0, 2] }); // 'a[0]=b&a[2]=d' ``` ### Handling of `null` values By default, `null` values are treated like empty strings: ```javascript var withNull = qs.stringify({ a: null, b: '' }); assert.equal(withNull, 'a=&b='); ``` Parsing does not distinguish between parameters with and without equal signs. Both are converted to empty strings. ```javascript var equalsInsensitive = qs.parse('a&b='); assert.deepEqual(equalsInsensitive, { a: '', b: '' }); ``` To distinguish between `null` values and empty strings use the `strictNullHandling` flag. In the result string the `null` values have no `=` sign: ```javascript var strictNull = qs.stringify({ a: null, b: '' }, { strictNullHandling: true }); assert.equal(strictNull, 'a&b='); ``` To parse values without `=` back to `null` use the `strictNullHandling` flag: ```javascript var parsedStrictNull = qs.parse('a&b=', { strictNullHandling: true }); assert.deepEqual(parsedStrictNull, { a: null, b: '' }); ``` To completely skip rendering keys with `null` values, use the `skipNulls` flag: ```javascript var nullsSkipped = qs.stringify({ a: 'b', c: null}, { skipNulls: true }); assert.equal(nullsSkipped, 'a=b'); ``` ### Dealing with special character sets By default the encoding and decoding of characters is done in `utf-8`. If you wish to encode querystrings to a different character set (i.e. [Shift JIS](https://en.wikipedia.org/wiki/Shift_JIS)) you can use the [`qs-iconv`](https://github.com/martinheidegger/qs-iconv) library: ```javascript var encoder = require('qs-iconv/encoder')('shift_jis'); var shiftJISEncoded = qs.stringify({ a: 'こんにちは!' }, { encoder: encoder }); assert.equal(shiftJISEncoded, 'a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I'); ``` This also works for decoding of query strings: ```javascript var decoder = require('qs-iconv/decoder')('shift_jis'); var obj = qs.parse('a=%82%B1%82%F1%82%C9%82%BF%82%CD%81I', { decoder: decoder }); assert.deepEqual(obj, { a: 'こんにちは!' }); ``` ### RFC 3986 and RFC 1738 space encoding RFC3986 used as default option and encodes ' ' to *%20* which is backward compatible. In the same time, output can be stringified as per RFC1738 with ' ' equal to '+'. ``` assert.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC3986' }), 'a=b%20c'); assert.equal(qs.stringify({ a: 'b c' }, { format : 'RFC1738' }), 'a=b+c'); ``` [1]: https://npmjs.org/package/qs [2]: http://versionbadg.es/ljharb/qs.svg [3]: https://api.travis-ci.org/ljharb/qs.svg [4]: https://travis-ci.org/ljharb/qs [5]: https://david-dm.org/ljharb/qs.svg [6]: https://david-dm.org/ljharb/qs [7]: https://david-dm.org/ljharb/qs/dev-status.svg [8]: https://david-dm.org/ljharb/qs?type=dev [9]: https://ci.testling.com/ljharb/qs.png [10]: https://ci.testling.com/ljharb/qs [11]: https://nodei.co/npm/qs.png?downloads=true&stars=true [license-image]: http://img.shields.io/npm/l/qs.svg [license-url]: LICENSE [downloads-image]: http://img.shields.io/npm/dm/qs.svg [downloads-url]: http://npm-stat.com/charts.html?package=qs
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/README.md
README.md
## **6.5.2** - [Fix] use `safer-buffer` instead of `Buffer` constructor - [Refactor] utils: `module.exports` one thing, instead of mutating `exports` (#230) - [Dev Deps] update `browserify`, `eslint`, `iconv-lite`, `safer-buffer`, `tape`, `browserify` ## **6.5.1** - [Fix] Fix parsing & compacting very deep objects (#224) - [Refactor] name utils functions - [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` - [Tests] up to `node` `v8.4`; use `nvm install-latest-npm` so newer npm doesn’t break older node - [Tests] Use precise dist for Node.js 0.6 runtime (#225) - [Tests] make 0.6 required, now that it’s passing - [Tests] on `node` `v8.2`; fix npm on node 0.6 ## **6.5.0** - [New] add `utils.assign` - [New] pass default encoder/decoder to custom encoder/decoder functions (#206) - [New] `parse`/`stringify`: add `ignoreQueryPrefix`/`addQueryPrefix` options, respectively (#213) - [Fix] Handle stringifying empty objects with addQueryPrefix (#217) - [Fix] do not mutate `options` argument (#207) - [Refactor] `parse`: cache index to reuse in else statement (#182) - [Docs] add various badges to readme (#208) - [Dev Deps] update `eslint`, `browserify`, `iconv-lite`, `tape` - [Tests] up to `node` `v8.1`, `v7.10`, `v6.11`; npm v4.6 breaks on node < v1; npm v5+ breaks on node < v4 - [Tests] add `editorconfig-tools` ## **6.4.0** - [New] `qs.stringify`: add `encodeValuesOnly` option - [Fix] follow `allowPrototypes` option during merge (#201, #201) - [Fix] support keys starting with brackets (#202, #200) - [Fix] chmod a-x - [Dev Deps] update `eslint` - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds - [eslint] reduce warnings ## **6.3.2** - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Dev Deps] update `eslint` - [Fix] chmod a-x - [Fix] support keys starting with brackets (#202, #200) - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds ## **6.3.1** - [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties (thanks, @snyk!) - [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `browserify`, `iconv-lite`, `qs-iconv`, `tape` - [Tests] on all node minors; improve test matrix - [Docs] document stringify option `allowDots` (#195) - [Docs] add empty object and array values example (#195) - [Docs] Fix minor inconsistency/typo (#192) - [Docs] document stringify option `sort` (#191) - [Refactor] `stringify`: throw faster with an invalid encoder - [Refactor] remove unnecessary escapes (#184) - Remove contributing.md, since `qs` is no longer part of `hapi` (#183) ## **6.3.0** - [New] Add support for RFC 1738 (#174, #173) - [New] `stringify`: Add `serializeDate` option to customize Date serialization (#159) - [Fix] ensure `utils.merge` handles merging two arrays - [Refactor] only constructors should be capitalized - [Refactor] capitalized var names are for constructors only - [Refactor] avoid using a sparse array - [Robustness] `formats`: cache `String#replace` - [Dev Deps] update `browserify`, `eslint`, `@ljharb/eslint-config`; add `safe-publish-latest` - [Tests] up to `node` `v6.8`, `v4.6`; improve test matrix - [Tests] flesh out arrayLimit/arrayFormat tests (#107) - [Tests] skip Object.create tests when null objects are not available - [Tests] Turn on eslint for test files (#175) ## **6.2.3** - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Fix] chmod a-x - [Fix] support keys starting with brackets (#202, #200) - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds ## **6.2.2** - [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties ## **6.2.1** - [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values - [Refactor] Be explicit and use `Object.prototype.hasOwnProperty.call` - [Tests] remove `parallelshell` since it does not reliably report failures - [Tests] up to `node` `v6.3`, `v5.12` - [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config`, `qs-iconv` ## [**6.2.0**](https://github.com/ljharb/qs/issues?milestone=36&state=closed) - [New] pass Buffers to the encoder/decoder directly (#161) - [New] add "encoder" and "decoder" options, for custom param encoding/decoding (#160) - [Fix] fix compacting of nested sparse arrays (#150) ## **6.1.2 - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Fix] chmod a-x - [Fix] support keys starting with brackets (#202, #200) - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds ## **6.1.1** - [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties ## [**6.1.0**](https://github.com/ljharb/qs/issues?milestone=35&state=closed) - [New] allowDots option for `stringify` (#151) - [Fix] "sort" option should work at a depth of 3 or more (#151) - [Fix] Restore `dist` directory; will be removed in v7 (#148) ## **6.0.4** - [Fix] follow `allowPrototypes` option during merge (#201, #200) - [Fix] chmod a-x - [Fix] support keys starting with brackets (#202, #200) - [Tests] up to `node` `v7.7`, `v6.10`,` v4.8`; disable osx builds since they block linux builds ## **6.0.3** - [Fix] ensure that `allowPrototypes: false` does not ever shadow Object.prototype properties - [Fix] Restore `dist` directory; will be removed in v7 (#148) ## [**6.0.2**](https://github.com/ljharb/qs/issues?milestone=33&state=closed) - Revert ES6 requirement and restore support for node down to v0.8. ## [**6.0.1**](https://github.com/ljharb/qs/issues?milestone=32&state=closed) - [**#127**](https://github.com/ljharb/qs/pull/127) Fix engines definition in package.json ## [**6.0.0**](https://github.com/ljharb/qs/issues?milestone=31&state=closed) - [**#124**](https://github.com/ljharb/qs/issues/124) Use ES6 and drop support for node < v4 ## **5.2.1** - [Fix] ensure `key[]=x&key[]&key[]=y` results in 3, not 2, values ## [**5.2.0**](https://github.com/ljharb/qs/issues?milestone=30&state=closed) - [**#64**](https://github.com/ljharb/qs/issues/64) Add option to sort object keys in the query string ## [**5.1.0**](https://github.com/ljharb/qs/issues?milestone=29&state=closed) - [**#117**](https://github.com/ljharb/qs/issues/117) make URI encoding stringified results optional - [**#106**](https://github.com/ljharb/qs/issues/106) Add flag `skipNulls` to optionally skip null values in stringify ## [**5.0.0**](https://github.com/ljharb/qs/issues?milestone=28&state=closed) - [**#114**](https://github.com/ljharb/qs/issues/114) default allowDots to false - [**#100**](https://github.com/ljharb/qs/issues/100) include dist to npm ## [**4.0.0**](https://github.com/ljharb/qs/issues?milestone=26&state=closed) - [**#98**](https://github.com/ljharb/qs/issues/98) make returning plain objects and allowing prototype overwriting properties optional ## [**3.1.0**](https://github.com/ljharb/qs/issues?milestone=24&state=closed) - [**#89**](https://github.com/ljharb/qs/issues/89) Add option to disable "Transform dot notation to bracket notation" ## [**3.0.0**](https://github.com/ljharb/qs/issues?milestone=23&state=closed) - [**#80**](https://github.com/ljharb/qs/issues/80) qs.parse silently drops properties - [**#77**](https://github.com/ljharb/qs/issues/77) Perf boost - [**#60**](https://github.com/ljharb/qs/issues/60) Add explicit option to disable array parsing - [**#74**](https://github.com/ljharb/qs/issues/74) Bad parse when turning array into object - [**#81**](https://github.com/ljharb/qs/issues/81) Add a `filter` option - [**#68**](https://github.com/ljharb/qs/issues/68) Fixed issue with recursion and passing strings into objects. - [**#66**](https://github.com/ljharb/qs/issues/66) Add mixed array and object dot notation support Closes: #47 - [**#76**](https://github.com/ljharb/qs/issues/76) RFC 3986 - [**#85**](https://github.com/ljharb/qs/issues/85) No equal sign - [**#84**](https://github.com/ljharb/qs/issues/84) update license attribute ## [**2.4.1**](https://github.com/ljharb/qs/issues?milestone=20&state=closed) - [**#73**](https://github.com/ljharb/qs/issues/73) Property 'hasOwnProperty' of object #<Object> is not a function ## [**2.4.0**](https://github.com/ljharb/qs/issues?milestone=19&state=closed) - [**#70**](https://github.com/ljharb/qs/issues/70) Add arrayFormat option ## [**2.3.3**](https://github.com/ljharb/qs/issues?milestone=18&state=closed) - [**#59**](https://github.com/ljharb/qs/issues/59) make sure array indexes are >= 0, closes #57 - [**#58**](https://github.com/ljharb/qs/issues/58) make qs usable for browser loader ## [**2.3.2**](https://github.com/ljharb/qs/issues?milestone=17&state=closed) - [**#55**](https://github.com/ljharb/qs/issues/55) allow merging a string into an object ## [**2.3.1**](https://github.com/ljharb/qs/issues?milestone=16&state=closed) - [**#52**](https://github.com/ljharb/qs/issues/52) Return "undefined" and "false" instead of throwing "TypeError". ## [**2.3.0**](https://github.com/ljharb/qs/issues?milestone=15&state=closed) - [**#50**](https://github.com/ljharb/qs/issues/50) add option to omit array indices, closes #46 ## [**2.2.5**](https://github.com/ljharb/qs/issues?milestone=14&state=closed) - [**#39**](https://github.com/ljharb/qs/issues/39) Is there an alternative to Buffer.isBuffer? - [**#49**](https://github.com/ljharb/qs/issues/49) refactor utils.merge, fixes #45 - [**#41**](https://github.com/ljharb/qs/issues/41) avoid browserifying Buffer, for #39 ## [**2.2.4**](https://github.com/ljharb/qs/issues?milestone=13&state=closed) - [**#38**](https://github.com/ljharb/qs/issues/38) how to handle object keys beginning with a number ## [**2.2.3**](https://github.com/ljharb/qs/issues?milestone=12&state=closed) - [**#37**](https://github.com/ljharb/qs/issues/37) parser discards first empty value in array - [**#36**](https://github.com/ljharb/qs/issues/36) Update to lab 4.x ## [**2.2.2**](https://github.com/ljharb/qs/issues?milestone=11&state=closed) - [**#33**](https://github.com/ljharb/qs/issues/33) Error when plain object in a value - [**#34**](https://github.com/ljharb/qs/issues/34) use Object.prototype.hasOwnProperty.call instead of obj.hasOwnProperty - [**#24**](https://github.com/ljharb/qs/issues/24) Changelog? Semver? ## [**2.2.1**](https://github.com/ljharb/qs/issues?milestone=10&state=closed) - [**#32**](https://github.com/ljharb/qs/issues/32) account for circular references properly, closes #31 - [**#31**](https://github.com/ljharb/qs/issues/31) qs.parse stackoverflow on circular objects ## [**2.2.0**](https://github.com/ljharb/qs/issues?milestone=9&state=closed) - [**#26**](https://github.com/ljharb/qs/issues/26) Don't use Buffer global if it's not present - [**#30**](https://github.com/ljharb/qs/issues/30) Bug when merging non-object values into arrays - [**#29**](https://github.com/ljharb/qs/issues/29) Don't call Utils.clone at the top of Utils.merge - [**#23**](https://github.com/ljharb/qs/issues/23) Ability to not limit parameters? ## [**2.1.0**](https://github.com/ljharb/qs/issues?milestone=8&state=closed) - [**#22**](https://github.com/ljharb/qs/issues/22) Enable using a RegExp as delimiter ## [**2.0.0**](https://github.com/ljharb/qs/issues?milestone=7&state=closed) - [**#18**](https://github.com/ljharb/qs/issues/18) Why is there arrayLimit? - [**#20**](https://github.com/ljharb/qs/issues/20) Configurable parametersLimit - [**#21**](https://github.com/ljharb/qs/issues/21) make all limits optional, for #18, for #20 ## [**1.2.2**](https://github.com/ljharb/qs/issues?milestone=6&state=closed) - [**#19**](https://github.com/ljharb/qs/issues/19) Don't overwrite null values ## [**1.2.1**](https://github.com/ljharb/qs/issues?milestone=5&state=closed) - [**#16**](https://github.com/ljharb/qs/issues/16) ignore non-string delimiters - [**#15**](https://github.com/ljharb/qs/issues/15) Close code block ## [**1.2.0**](https://github.com/ljharb/qs/issues?milestone=4&state=closed) - [**#12**](https://github.com/ljharb/qs/issues/12) Add optional delim argument - [**#13**](https://github.com/ljharb/qs/issues/13) fix #11: flattened keys in array are now correctly parsed ## [**1.1.0**](https://github.com/ljharb/qs/issues?milestone=3&state=closed) - [**#7**](https://github.com/ljharb/qs/issues/7) Empty values of a POST array disappear after being submitted - [**#9**](https://github.com/ljharb/qs/issues/9) Should not omit equals signs (=) when value is null - [**#6**](https://github.com/ljharb/qs/issues/6) Minor grammar fix in README ## [**1.0.2**](https://github.com/ljharb/qs/issues?milestone=2&state=closed) - [**#5**](https://github.com/ljharb/qs/issues/5) array holes incorrectly copied into object on large index
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/CHANGELOG.md
CHANGELOG.md
'use strict'; var test = require('tape'); var qs = require('qs'); var utils = require('qs/lib/utils'); var iconv = require('iconv-lite'); var SaferBuffer = require('safer-buffer').Buffer; 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('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 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'] }), '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 a nested array value', function (st) { st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'indices' }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }, { arrayFormat: 'brackets' }), 'a%5Bb%5D%5B%5D=c&a%5Bb%5D%5B%5D=d'); st.equal(qs.stringify({ a: { b: ['c', 'd'] } }), 'a%5Bb%5D%5B0%5D=c&a%5Bb%5D%5B1%5D=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, encode: false, 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, encode: false, arrayFormat: 'brackets' } ), 'a.b[]=c&a.b[]=d', 'brackets: stringifies with dots + brackets' ); st.equal( qs.stringify( { a: { b: ['c', 'd'] } }, { allowDots: true, encode: false } ), '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', 'indices => brackets' ); st.equal( qs.stringify({ a: [{ b: 'c' }] }, { arrayFormat: 'brackets' }), 'a%5B%5D%5Bb%5D=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] }, { encode: false, arrayFormat: 'indices' }), 'a[0][b]=1&a[1]=2&a[2]=3', 'indices => indices' ); st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false, arrayFormat: 'brackets' }), 'a[][b]=1&a[]=2&a[]=3', 'brackets => brackets' ); st.equal( qs.stringify({ a: [{ b: 1 }, 2, 3] }, { encode: false }), '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 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('doesn\'t 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('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.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.end(); }); t.test('RFC 1738 spaces 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.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.end(); }); t.test('Backward compatibility to RFC 3986', function (st) { st.equal(qs.stringify({ a: 'b c' }), 'a=b%20c'); 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('does not mutate the options argument', function (st) { var options = {}; qs.stringify({}, options); st.deepEqual(options, {}); st.end(); }); t.end(); });
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/test/stringify.js
stringify.js
'use strict'; var test = require('tape'); var qs = require('qs'); var utils = require('qs/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('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.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.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 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('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', { parallel: false }, 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) { st.deepEqual(qs.parse('a[0]=b&a[1]=c', { parseArrays: false }), { a: { 0: 'b', 1: 'c' } }); 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 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 }), { a: { b: 'c', toString: true } }, 'can overwrite prototype with plainObjects true' ); 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 iconv.decode(SaferBuffer.from(result), 'shift_jis').toString(); } }), { 県: '大阪府' }); 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.end(); });
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/test/parse.js
parse.js
(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; module.exports = { 'default': 'RFC3986', formatters: { RFC1738: function (value) { return replace.call(value, percentTwenties, '+'); }, RFC3986: function (value) { return value; } }, RFC1738: 'RFC1738', RFC3986: '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 defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; 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); for (var i = 0; i < parts.length; ++i) { 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); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder); val = options.decoder(part.slice(pos + 1), defaults.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = 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 ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { 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 = 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 ((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); }; module.exports = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; 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); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); }; },{"./utils":5}],4:[function(require,module,exports){ 'use strict'; var utils = require('./utils'); var formats = require('./formats'); var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.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]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; }; },{"./formats":1,"./utils":5}],5:[function(require,module,exports){ 'use strict'; var has = Object.prototype.hasOwnProperty; 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) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.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; } } return obj; }; 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) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = merge(target[i], 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) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; var encode = function encode(str) { // 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 = typeof str === 'string' ? str : String(str); 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); } } } return compactQueue(queue); }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; module.exports = { arrayToObject: arrayToObject, assign: assign, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, merge: merge }; },{}]},{},[2])(2) });
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/dist/qs.js
qs.js
'use strict'; var utils = require('qs/lib/utils'); var formats = require('qs/lib/formats'); var arrayPrefixGenerators = { brackets: function brackets(prefix) { // eslint-disable-line func-name-matching return prefix + '[]'; }, indices: function indices(prefix, key) { // eslint-disable-line func-name-matching return prefix + '[' + key + ']'; }, repeat: function repeat(prefix) { // eslint-disable-line func-name-matching return prefix; } }; var toISO = Date.prototype.toISOString; var defaults = { delimiter: '&', encode: true, encoder: utils.encode, encodeValuesOnly: false, serializeDate: function serializeDate(date) { // eslint-disable-line func-name-matching return toISO.call(date); }, skipNulls: false, strictNullHandling: false }; var stringify = function stringify( // eslint-disable-line func-name-matching object, prefix, generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly ) { var obj = object; if (typeof filter === 'function') { obj = filter(prefix, obj); } else if (obj instanceof Date) { obj = serializeDate(obj); } else if (obj === null) { if (strictNullHandling) { return encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder) : prefix; } obj = ''; } if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean' || utils.isBuffer(obj)) { if (encoder) { var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder); return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder))]; } return [formatter(prefix) + '=' + formatter(String(obj))]; } var values = []; if (typeof obj === 'undefined') { return values; } var objKeys; if (Array.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]; if (skipNulls && obj[key] === null) { continue; } if (Array.isArray(obj)) { values = values.concat(stringify( obj[key], generateArrayPrefix(prefix, key), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } else { values = values.concat(stringify( obj[key], prefix + (allowDots ? '.' + key : '[' + key + ']'), generateArrayPrefix, strictNullHandling, skipNulls, encoder, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } } return values; }; module.exports = function (object, opts) { var obj = object; var options = opts ? utils.assign({}, opts) : {}; if (options.encoder !== null && options.encoder !== undefined && typeof options.encoder !== 'function') { throw new TypeError('Encoder has to be a function.'); } var delimiter = typeof options.delimiter === 'undefined' ? defaults.delimiter : options.delimiter; var strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; var skipNulls = typeof options.skipNulls === 'boolean' ? options.skipNulls : defaults.skipNulls; var encode = typeof options.encode === 'boolean' ? options.encode : defaults.encode; var encoder = typeof options.encoder === 'function' ? options.encoder : defaults.encoder; var sort = typeof options.sort === 'function' ? options.sort : null; var allowDots = typeof options.allowDots === 'undefined' ? false : options.allowDots; var serializeDate = typeof options.serializeDate === 'function' ? options.serializeDate : defaults.serializeDate; var encodeValuesOnly = typeof options.encodeValuesOnly === 'boolean' ? options.encodeValuesOnly : defaults.encodeValuesOnly; if (typeof options.format === 'undefined') { options.format = formats['default']; } else if (!Object.prototype.hasOwnProperty.call(formats.formatters, options.format)) { throw new TypeError('Unknown format option provided.'); } var formatter = formats.formatters[options.format]; var objKeys; var filter; if (typeof options.filter === 'function') { filter = options.filter; obj = filter('', obj); } else if (Array.isArray(options.filter)) { filter = options.filter; objKeys = filter; } var keys = []; if (typeof obj !== 'object' || obj === null) { return ''; } var arrayFormat; if (options.arrayFormat in arrayPrefixGenerators) { arrayFormat = options.arrayFormat; } else if ('indices' in options) { arrayFormat = options.indices ? 'indices' : 'repeat'; } else { arrayFormat = 'indices'; } var generateArrayPrefix = arrayPrefixGenerators[arrayFormat]; if (!objKeys) { objKeys = Object.keys(obj); } if (sort) { objKeys.sort(sort); } for (var i = 0; i < objKeys.length; ++i) { var key = objKeys[i]; if (skipNulls && obj[key] === null) { continue; } keys = keys.concat(stringify( obj[key], key, generateArrayPrefix, strictNullHandling, skipNulls, encode ? encoder : null, filter, sort, allowDots, serializeDate, formatter, encodeValuesOnly )); } var joined = keys.join(delimiter); var prefix = options.addQueryPrefix === true ? '?' : ''; return joined.length > 0 ? prefix + joined : ''; };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/lib/stringify.js
stringify.js
'use strict'; var utils = require('qs/lib/utils'); var has = Object.prototype.hasOwnProperty; var defaults = { allowDots: false, allowPrototypes: false, arrayLimit: 20, decoder: utils.decode, delimiter: '&', depth: 5, parameterLimit: 1000, plainObjects: false, strictNullHandling: false }; 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); for (var i = 0; i < parts.length; ++i) { 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); val = options.strictNullHandling ? null : ''; } else { key = options.decoder(part.slice(0, pos), defaults.decoder); val = options.decoder(part.slice(pos + 1), defaults.decoder); } if (has.call(obj, key)) { obj[key] = [].concat(obj[key]).concat(val); } else { obj[key] = val; } } return obj; }; var parseObject = function (chain, val, options) { var leaf = val; for (var i = chain.length - 1; i >= 0; --i) { var obj; var root = chain[i]; if (root === '[]') { obj = []; obj = 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 ( !isNaN(index) && root !== cleanRoot && String(index) === cleanRoot && index >= 0 && (options.parseArrays && index <= options.arrayLimit) ) { obj = []; obj[index] = leaf; } else { obj[cleanRoot] = leaf; } } leaf = obj; } return leaf; }; var parseKeys = function parseQueryStringKeys(givenKey, val, options) { 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 = 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 ((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); }; module.exports = function (str, opts) { var options = opts ? utils.assign({}, opts) : {}; if (options.decoder !== null && options.decoder !== undefined && typeof options.decoder !== 'function') { throw new TypeError('Decoder has to be a function.'); } options.ignoreQueryPrefix = options.ignoreQueryPrefix === true; options.delimiter = typeof options.delimiter === 'string' || utils.isRegExp(options.delimiter) ? options.delimiter : defaults.delimiter; options.depth = typeof options.depth === 'number' ? options.depth : defaults.depth; options.arrayLimit = typeof options.arrayLimit === 'number' ? options.arrayLimit : defaults.arrayLimit; options.parseArrays = options.parseArrays !== false; options.decoder = typeof options.decoder === 'function' ? options.decoder : defaults.decoder; options.allowDots = typeof options.allowDots === 'boolean' ? options.allowDots : defaults.allowDots; options.plainObjects = typeof options.plainObjects === 'boolean' ? options.plainObjects : defaults.plainObjects; options.allowPrototypes = typeof options.allowPrototypes === 'boolean' ? options.allowPrototypes : defaults.allowPrototypes; options.parameterLimit = typeof options.parameterLimit === 'number' ? options.parameterLimit : defaults.parameterLimit; options.strictNullHandling = typeof options.strictNullHandling === 'boolean' ? options.strictNullHandling : defaults.strictNullHandling; 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); obj = utils.merge(obj, newObj, options); } return utils.compact(obj); };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/lib/parse.js
parse.js
'use strict'; var has = Object.prototype.hasOwnProperty; 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) { var obj; while (queue.length) { var item = queue.pop(); obj = item.obj[item.prop]; if (Array.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; } } return obj; }; 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) { if (!source) { return target; } if (typeof source !== 'object') { if (Array.isArray(target)) { target.push(source); } else if (typeof target === 'object') { if (options.plainObjects || options.allowPrototypes || !has.call(Object.prototype, source)) { target[source] = true; } } else { return [target, source]; } return target; } if (typeof target !== 'object') { return [target].concat(source); } var mergeTarget = target; if (Array.isArray(target) && !Array.isArray(source)) { mergeTarget = arrayToObject(target, options); } if (Array.isArray(target) && Array.isArray(source)) { source.forEach(function (item, i) { if (has.call(target, i)) { if (target[i] && typeof target[i] === 'object') { target[i] = merge(target[i], 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) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (e) { return str; } }; var encode = function encode(str) { // 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 = typeof str === 'string' ? str : String(str); 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); } } } return compactQueue(queue); }; var isRegExp = function isRegExp(obj) { return Object.prototype.toString.call(obj) === '[object RegExp]'; }; var isBuffer = function isBuffer(obj) { if (obj === null || typeof obj === 'undefined') { return false; } return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); }; module.exports = { arrayToObject: arrayToObject, assign: assign, compact: compact, decode: decode, encode: encode, isBuffer: isBuffer, isRegExp: isRegExp, merge: merge };
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/qs/lib/utils.js
utils.js
* Module dependencies. */ var crypto = require('crypto') , parse = require('url').parse ; /** * Valid keys. */ var keys = [ 'acl' , 'location' , 'logging' , 'notification' , 'partNumber' , 'policy' , 'requestPayment' , 'torrent' , 'uploadId' , 'uploads' , 'versionId' , 'versioning' , 'versions' , 'website' ] /** * Return an "Authorization" header value with the given `options` * in the form of "AWS <key>:<signature>" * * @param {Object} options * @return {String} * @api private */ function authorization (options) { return 'AWS ' + options.key + ':' + sign(options) } module.exports = authorization module.exports.authorization = authorization /** * Simple HMAC-SHA1 Wrapper * * @param {Object} options * @return {String} * @api private */ function hmacSha1 (options) { return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64') } module.exports.hmacSha1 = hmacSha1 /** * Create a base64 sha1 HMAC for `options`. * * @param {Object} options * @return {String} * @api private */ function sign (options) { options.message = stringToSign(options) return hmacSha1(options) } module.exports.sign = sign /** * Create a base64 sha1 HMAC for `options`. * * Specifically to be used with S3 presigned URLs * * @param {Object} options * @return {String} * @api private */ function signQuery (options) { options.message = queryStringToSign(options) return hmacSha1(options) } module.exports.signQuery= signQuery /** * Return a string for sign() with the given `options`. * * Spec: * * <verb>\n * <md5>\n * <content-type>\n * <date>\n * [headers\n] * <resource> * * @param {Object} options * @return {String} * @api private */ function stringToSign (options) { var headers = options.amazonHeaders || '' if (headers) headers += '\n' var r = [ options.verb , options.md5 , options.contentType , options.date ? options.date.toUTCString() : '' , headers + options.resource ] return r.join('\n') } module.exports.stringToSign = stringToSign /** * Return a string for sign() with the given `options`, but is meant exclusively * for S3 presigned URLs * * Spec: * * <date>\n * <resource> * * @param {Object} options * @return {String} * @api private */ function queryStringToSign (options){ return 'GET\n\n\n' + options.date + '\n' + options.resource } module.exports.queryStringToSign = queryStringToSign /** * Perform the following: * * - ignore non-amazon headers * - lowercase fields * - sort lexicographically * - trim whitespace between ":" * - join with newline * * @param {Object} headers * @return {String} * @api private */ function canonicalizeHeaders (headers) { var buf = [] , fields = Object.keys(headers) ; for (var i = 0, len = fields.length; i < len; ++i) { var field = fields[i] , val = headers[field] , field = field.toLowerCase() ; if (0 !== field.indexOf('x-amz')) continue buf.push(field + ':' + val) } return buf.sort().join('\n') } module.exports.canonicalizeHeaders = canonicalizeHeaders /** * Perform the following: * * - ignore non sub-resources * - sort lexicographically * * @param {String} resource * @return {String} * @api private */ function canonicalizeResource (resource) { var url = parse(resource, true) , path = url.pathname , buf = [] ; Object.keys(url.query).forEach(function(key){ if (!~keys.indexOf(key)) return var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key]) buf.push(key + val) }) return path + (buf.length ? '?' + buf.sort().join('&') : '') } module.exports.canonicalizeResource = canonicalizeResource
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/aws-sign2/index.js
index.js
'use strict'; /** Highest positive signed 32-bit float value */ const maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ const base = 36; const tMin = 1; const tMax = 26; const skew = 38; const damp = 700; const initialBias = 72; const initialN = 128; // 0x80 const delimiter = '-'; // '\x2D' /** Regular expressions */ const regexPunycode = /^xn--/; const regexNonASCII = /[^\0-\x7E]/; // non-ASCII chars const regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators /** Error messages */ const errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }; /** Convenience shortcuts */ const baseMinusTMin = base - tMin; const floor = Math.floor; const stringFromCharCode = String.fromCharCode; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { const result = []; let length = array.length; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { const parts = string.split('@'); let result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); const labels = string.split('.'); const encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { const output = []; let counter = 0; const length = string.length; while (counter < length) { const value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // It's a high surrogate, and there is a next character. const extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // Low surrogate. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // It's an unmatched surrogate; only append this code unit, in case the // next code unit is the high surrogate of a surrogate pair. output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ const ucs2encode = array => String.fromCodePoint(...array); /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ const basicToDigit = function(codePoint) { if (codePoint - 0x30 < 0x0A) { return codePoint - 0x16; } if (codePoint - 0x41 < 0x1A) { return codePoint - 0x41; } if (codePoint - 0x61 < 0x1A) { return codePoint - 0x61; } return base; }; /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ const digitToBasic = function(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); }; /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ const adapt = function(delta, numPoints, firstTime) { let k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); }; /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ const decode = function(input) { // Don't use UCS-2. const output = []; const inputLength = input.length; let i = 0; let n = initialN; let bias = initialBias; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. let basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (let j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. let oldi = i; for (let w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } const digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } const baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } const out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output. output.splice(i++, 0, n); } return String.fromCodePoint(...output); }; /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ const encode = function(input) { const output = []; // Convert the input in UCS-2 to an array of Unicode code points. input = ucs2decode(input); // Cache the length. let inputLength = input.length; // Initialize the state. let n = initialN; let delta = 0; let bias = initialBias; // Handle the basic code points. for (const currentValue of input) { if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } let basicLength = output.length; let handledCPCount = basicLength; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string with a delimiter unless it's empty. if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: let m = maxInt; for (const currentValue of input) { if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>, // but guard against overflow. const handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (const currentValue of input) { if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer. let q = delta; for (let k = base; /* no condition */; k += base) { const t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } const qMinusT = q - t; const baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); }; /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ const toUnicode = function(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); }; /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ const toASCII = function(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); }; /*--------------------------------------------------------------------------*/ /** Define the public API */ const punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '2.1.0', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see <https://mathiasbynens.be/notes/javascript-encoding> * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; export { ucs2decode, ucs2encode, decode, encode, toASCII, toUnicode }; export default punycode;
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/punycode/punycode.es6.js
punycode.es6.js
# Punycode.js [![Build status](https://travis-ci.org/bestiejs/punycode.js.svg?branch=master)](https://travis-ci.org/bestiejs/punycode.js) [![Code coverage status](http://img.shields.io/codecov/c/github/bestiejs/punycode.js.svg)](https://codecov.io/gh/bestiejs/punycode.js) [![Dependency status](https://gemnasium.com/bestiejs/punycode.js.svg)](https://gemnasium.com/bestiejs/punycode.js) Punycode.js is a robust Punycode converter that fully complies to [RFC 3492](https://tools.ietf.org/html/rfc3492) and [RFC 5891](https://tools.ietf.org/html/rfc5891). This JavaScript library is the result of comparing, optimizing and documenting different open-source implementations of the Punycode algorithm: * [The C example code from RFC 3492](https://tools.ietf.org/html/rfc3492#appendix-C) * [`punycode.c` by _Markus W. Scherer_ (IBM)](http://opensource.apple.com/source/ICU/ICU-400.42/icuSources/common/punycode.c) * [`punycode.c` by _Ben Noordhuis_](https://github.com/bnoordhuis/punycode/blob/master/punycode.c) * [JavaScript implementation by _some_](http://stackoverflow.com/questions/183485/can-anyone-recommend-a-good-free-javascript-for-punycode-to-unicode-conversion/301287#301287) * [`punycode.js` by _Ben Noordhuis_](https://github.com/joyent/node/blob/426298c8c1c0d5b5224ac3658c41e7c2a3fe9377/lib/punycode.js) (note: [not fully compliant](https://github.com/joyent/node/issues/2072)) This project was [bundled](https://github.com/joyent/node/blob/master/lib/punycode.js) with Node.js from [v0.6.2+](https://github.com/joyent/node/compare/975f1930b1...61e796decc) until [v7](https://github.com/nodejs/node/pull/7941) (soft-deprecated). The current version supports recent versions of Node.js only. It provides a CommonJS module and an ES6 module. For the old version that offers the same functionality with broader support, including Rhino, Ringo, Narwhal, and web browsers, see [v1.4.1](https://github.com/bestiejs/punycode.js/releases/tag/v1.4.1). ## Installation Via [npm](https://www.npmjs.com/): ```bash npm install punycode --save ``` In [Node.js](https://nodejs.org/): ```js const punycode = require('punycode'); ``` ## API ### `punycode.decode(string)` Converts a Punycode string of ASCII symbols to a string of Unicode symbols. ```js // decode domain name parts punycode.decode('maana-pta'); // 'mañana' punycode.decode('--dqo34k'); // '☃-⌘' ``` ### `punycode.encode(string)` Converts a string of Unicode symbols to a Punycode string of ASCII symbols. ```js // encode domain name parts punycode.encode('mañana'); // 'maana-pta' punycode.encode('☃-⌘'); // '--dqo34k' ``` ### `punycode.toUnicode(input)` Converts a Punycode string representing a domain name or an email address to Unicode. Only the Punycoded parts of the input will be converted, i.e. it doesn’t matter if you call it on a string that has already been converted to Unicode. ```js // decode domain names punycode.toUnicode('xn--maana-pta.com'); // → 'mañana.com' punycode.toUnicode('xn----dqo34k.com'); // → '☃-⌘.com' // decode email addresses punycode.toUnicode('джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq'); // → 'джумла@джpумлатест.bрфa' ``` ### `punycode.toASCII(input)` Converts a lowercased Unicode string representing a domain name or an email address to Punycode. Only the non-ASCII parts of the input will be converted, i.e. it doesn’t matter if you call it with a domain that’s already in ASCII. ```js // encode domain names punycode.toASCII('mañana.com'); // → 'xn--maana-pta.com' punycode.toASCII('☃-⌘.com'); // → 'xn----dqo34k.com' // encode email addresses punycode.toASCII('джумла@джpумлатест.bрфa'); // → 'джумла@xn--p-8sbkgc5ag7bhce.xn--ba-lmcq' ``` ### `punycode.ucs2` #### `punycode.ucs2.decode(string)` Creates an array containing the numeric code point values of each Unicode symbol in the string. While [JavaScript uses UCS-2 internally](https://mathiasbynens.be/notes/javascript-encoding), this function will convert a pair of surrogate halves (each of which UCS-2 exposes as separate characters) into a single code point, matching UTF-16. ```js punycode.ucs2.decode('abc'); // → [0x61, 0x62, 0x63] // surrogate pair for U+1D306 TETRAGRAM FOR CENTRE: punycode.ucs2.decode('\uD834\uDF06'); // → [0x1D306] ``` #### `punycode.ucs2.encode(codePoints)` Creates a string based on an array of numeric code point values. ```js punycode.ucs2.encode([0x61, 0x62, 0x63]); // → 'abc' punycode.ucs2.encode([0x1D306]); // → '\uD834\uDF06' ``` ### `punycode.version` A string representing the current Punycode.js version number. ## Author | [![twitter/mathias](https://gravatar.com/avatar/24e08a9ea84deb17ae121074d0f17125?s=70)](https://twitter.com/mathias "Follow @mathias on Twitter") | |---| | [Mathias Bynens](https://mathiasbynens.be/) | ## License Punycode.js is available under the [MIT](https://mths.be/mit) license.
zhihu-crawler
/zhihu_crawler-0.0.2.tar.gz/zhihu_crawler-0.0.2/zhihu_crawler/common/node_modules/punycode/README.md
README.md