response.js
This file
Path
lib/response.js
1,054 lines · 24.3 KiB · JavaScript
Last changed by
Ignore `expires` and `maxAge` in `res.clearCookie()` (#5792)Jon Churchbefore adoption82fc12a
History of this fileTake it
1/*!2 * express3 * Copyright(c) 2009-2013 TJ Holowaychuk4 * Copyright(c) 2014-2015 Douglas Christopher Wilson5 * MIT Licensed6 */78'use strict';910/**11 * Module dependencies.12 * @private13 */1415var Buffer = require('safe-buffer').Buffer16var contentDisposition = require('content-disposition');17var createError = require('http-errors')18var encodeUrl = require('encodeurl');19var escapeHtml = require('escape-html');20var http = require('http');21var onFinished = require('on-finished');22var mime = require('mime-types')23var path = require('path');24var pathIsAbsolute = require('path-is-absolute');25var statuses = require('statuses')26var merge = require('utils-merge');27var sign = require('cookie-signature').sign;28var normalizeType = require('./utils').normalizeType;29var normalizeTypes = require('./utils').normalizeTypes;30var setCharset = require('./utils').setCharset;31var cookie = require('cookie');32var send = require('send');33var extname = path.extname;34var resolve = path.resolve;35var vary = require('vary');3637/**38 * Response prototype.39 * @public40 */4142var res = Object.create(http.ServerResponse.prototype)4344/**45 * Module exports.46 * @public47 */4849module.exports = res5051/**52 * Module variables.53 * @private54 */5556var schemaAndHostRegExp = /^(?:[a-zA-Z][a-zA-Z0-9+.-]*:)?\/\/[^\\\/\?]+/;5758/**59 * Set the HTTP status code for the response.60 *61 * Expects an integer value between 100 and 999 inclusive.62 * Throws an error if the provided status code is not an integer or if it's outside the allowable range.63 *64 * @param {number} code - The HTTP status code to set.65 * @return {ServerResponse} - Returns itself for chaining methods.66 * @throws {TypeError} If `code` is not an integer.67 * @throws {RangeError} If `code` is outside the range 100 to 999.68 * @public69 */7071res.status = function status(code) {72 // Check if the status code is not an integer73 if (!Number.isInteger(code)) {74 throw new TypeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be an integer.`);75 }76 // Check if the status code is outside of Node's valid range77 if (code < 100 || code > 999) {78 throw new RangeError(`Invalid status code: ${JSON.stringify(code)}. Status code must be greater than 99 and less than 1000.`);79 }8081 this.statusCode = code;82 return this;83};8485/**86 * Set Link header field with the given `links`.87 *88 * Examples:89 *90 * res.links({91 * next: 'http://api.example.com/users?page=2',92 * last: 'http://api.example.com/users?page=5'93 * });94 *95 * @param {Object} links96 * @return {ServerResponse}97 * @public98 */99100res.links = function(links){101 var link = this.get('Link') || '';102 if (link) link += ', ';103 return this.set('Link', link + Object.keys(links).map(function(rel){104 return '<' + links[rel] + '>; rel="' + rel + '"';105 }).join(', '));106};107108/**109 * Send a response.110 *111 * Examples:112 *113 * res.send(Buffer.from('wahoo'));114 * res.send({ some: 'json' });115 * res.send('<p>some html</p>');116 *117 * @param {string|number|boolean|object|Buffer} body118 * @public119 */120121res.send = function send(body) {122 var chunk = body;123 var encoding;124 var req = this.req;125 var type;126127 // settings128 var app = this.app;129130 switch (typeof chunk) {131 // string defaulting to html132 case 'string':133 if (!this.get('Content-Type')) {134 this.type('html');135 }136 break;137 case 'boolean':138 case 'number':139 case 'object':140 if (chunk === null) {141 chunk = '';142 } else if (Buffer.isBuffer(chunk)) {143 if (!this.get('Content-Type')) {144 this.type('bin');145 }146 } else {147 return this.json(chunk);148 }149 break;150 }151152 // write strings in utf-8153 if (typeof chunk === 'string') {154 encoding = 'utf8';155 type = this.get('Content-Type');156157 // reflect this in content-type158 if (typeof type === 'string') {159 this.set('Content-Type', setCharset(type, 'utf-8'));160 }161 }162163 // determine if ETag should be generated164 var etagFn = app.get('etag fn')165 var generateETag = !this.get('ETag') && typeof etagFn === 'function'166167 // populate Content-Length168 var len169 if (chunk !== undefined) {170 if (Buffer.isBuffer(chunk)) {171 // get length of Buffer172 len = chunk.length173 } else if (!generateETag && chunk.length < 1000) {174 // just calculate length when no ETag + small chunk175 len = Buffer.byteLength(chunk, encoding)176 } else {177 // convert chunk to Buffer and calculate178 chunk = Buffer.from(chunk, encoding)179 encoding = undefined;180 len = chunk.length181 }182183 this.set('Content-Length', len);184 }185186 // populate ETag187 var etag;188 if (generateETag && len !== undefined) {189 if ((etag = etagFn(chunk, encoding))) {190 this.set('ETag', etag);191 }192 }193194 // freshness195 if (req.fresh) this.status(304);196197 // strip irrelevant headers198 if (204 === this.statusCode || 304 === this.statusCode) {199 this.removeHeader('Content-Type');200 this.removeHeader('Content-Length');201 this.removeHeader('Transfer-Encoding');202 chunk = '';203 }204205 // alter headers for 205206 if (this.statusCode === 205) {207 this.set('Content-Length', '0')208 this.removeHeader('Transfer-Encoding')209 chunk = ''210 }211212 if (req.method === 'HEAD') {213 // skip body for HEAD214 this.end();215 } else {216 // respond217 this.end(chunk, encoding);218 }219220 return this;221};222223/**224 * Send JSON response.225 *226 * Examples:227 *228 * res.json(null);229 * res.json({ user: 'tj' });230 *231 * @param {string|number|boolean|object} obj232 * @public233 */234235res.json = function json(obj) {236 // settings237 var app = this.app;238 var escape = app.get('json escape')239 var replacer = app.get('json replacer');240 var spaces = app.get('json spaces');241 var body = stringify(obj, replacer, spaces, escape)242243 // content-type244 if (!this.get('Content-Type')) {245 this.set('Content-Type', 'application/json');246 }247248 return this.send(body);249};250251/**252 * Send JSON response with JSONP callback support.253 *254 * Examples:255 *256 * res.jsonp(null);257 * res.jsonp({ user: 'tj' });258 *259 * @param {string|number|boolean|object} obj260 * @public261 */262263res.jsonp = function jsonp(obj) {264 // settings265 var app = this.app;266 var escape = app.get('json escape')267 var replacer = app.get('json replacer');268 var spaces = app.get('json spaces');269 var body = stringify(obj, replacer, spaces, escape)270 var callback = this.req.query[app.get('jsonp callback name')];271272 // content-type273 if (!this.get('Content-Type')) {274 this.set('X-Content-Type-Options', 'nosniff');275 this.set('Content-Type', 'application/json');276 }277278 // fixup callback279 if (Array.isArray(callback)) {280 callback = callback[0];281 }282283 // jsonp284 if (typeof callback === 'string' && callback.length !== 0) {285 this.set('X-Content-Type-Options', 'nosniff');286 this.set('Content-Type', 'text/javascript');287288 // restrict callback charset289 callback = callback.replace(/[^\[\]\w$.]/g, '');290291 if (body === undefined) {292 // empty argument293 body = ''294 } else if (typeof body === 'string') {295 // replace chars not allowed in JavaScript that are in JSON296 body = body297 .replace(/\u2028/g, '\\u2028')298 .replace(/\u2029/g, '\\u2029')299 }300301 // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse"302 // the typeof check is just to reduce client error noise303 body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');';304 }305306 return this.send(body);307};308309/**310 * Send given HTTP status code.311 *312 * Sets the response status to `statusCode` and the body of the313 * response to the standard description from node's http.STATUS_CODES314 * or the statusCode number if no description.315 *316 * Examples:317 *318 * res.sendStatus(200);319 *320 * @param {number} statusCode321 * @public322 */323324res.sendStatus = function sendStatus(statusCode) {325 var body = statuses.message[statusCode] || String(statusCode)326327 this.status(statusCode);328 this.type('txt');329330 return this.send(body);331};332333/**334 * Transfer the file at the given `path`.335 *336 * Automatically sets the _Content-Type_ response header field.337 * The callback `callback(err)` is invoked when the transfer is complete338 * or when an error occurs. Be sure to check `res.headersSent`339 * if you wish to attempt responding, as the header and some data340 * may have already been transferred.341 *342 * Options:343 *344 * - `maxAge` defaulting to 0 (can be string converted by `ms`)345 * - `root` root directory for relative filenames346 * - `headers` object of headers to serve with file347 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them348 *349 * Other options are passed along to `send`.350 *351 * Examples:352 *353 * The following example illustrates how `res.sendFile()` may354 * be used as an alternative for the `static()` middleware for355 * dynamic situations. The code backing `res.sendFile()` is actually356 * the same code, so HTTP cache support etc is identical.357 *358 * app.get('/user/:uid/photos/:file', function(req, res){359 * var uid = req.params.uid360 * , file = req.params.file;361 *362 * req.user.mayViewFilesFrom(uid, function(yes){363 * if (yes) {364 * res.sendFile('/uploads/' + uid + '/' + file);365 * } else {366 * res.send(403, 'Sorry! you cant see that.');367 * }368 * });369 * });370 *371 * @public372 */373374res.sendFile = function sendFile(path, options, callback) {375 var done = callback;376 var req = this.req;377 var res = this;378 var next = req.next;379 var opts = options || {};380381 if (!path) {382 throw new TypeError('path argument is required to res.sendFile');383 }384385 if (typeof path !== 'string') {386 throw new TypeError('path must be a string to res.sendFile')387 }388389 // support function as second arg390 if (typeof options === 'function') {391 done = options;392 opts = {};393 }394395 if (!opts.root && !pathIsAbsolute(path)) {396 throw new TypeError('path must be absolute or specify root to res.sendFile');397 }398399 // create file stream400 var pathname = encodeURI(path);401 var file = send(req, pathname, opts);402403 // transfer404 sendfile(res, file, opts, function (err) {405 if (done) return done(err);406 if (err && err.code === 'EISDIR') return next();407408 // next() all but write errors409 if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') {410 next(err);411 }412 });413};414415/**416 * Transfer the file at the given `path` as an attachment.417 *418 * Optionally providing an alternate attachment `filename`,419 * and optional callback `callback(err)`. The callback is invoked420 * when the data transfer is complete, or when an error has421 * occurred. Be sure to check `res.headersSent` if you plan to respond.422 *423 * Optionally providing an `options` object to use with `res.sendFile()`.424 * This function will set the `Content-Disposition` header, overriding425 * any `Content-Disposition` header passed as header options in order426 * to set the attachment and filename.427 *428 * This method uses `res.sendFile()`.429 *430 * @public431 */432433res.download = function download (path, filename, options, callback) {434 var done = callback;435 var name = filename;436 var opts = options || null437438 // support function as second or third arg439 if (typeof filename === 'function') {440 done = filename;441 name = null;442 opts = null443 } else if (typeof options === 'function') {444 done = options445 opts = null446 }447448 // support optional filename, where options may be in it's place449 if (typeof filename === 'object' &&450 (typeof options === 'function' || options === undefined)) {451 name = null452 opts = filename453 }454455 // set Content-Disposition when file is sent456 var headers = {457 'Content-Disposition': contentDisposition(name || path)458 };459460 // merge user-provided headers461 if (opts && opts.headers) {462 var keys = Object.keys(opts.headers)463 for (var i = 0; i < keys.length; i++) {464 var key = keys[i]465 if (key.toLowerCase() !== 'content-disposition') {466 headers[key] = opts.headers[key]467 }468 }469 }470471 // merge user-provided options472 opts = Object.create(opts)473 opts.headers = headers474475 // Resolve the full path for sendFile476 var fullPath = !opts.root477 ? resolve(path)478 : path479480 // send file481 return this.sendFile(fullPath, opts, done)482};483484/**485 * Set _Content-Type_ response header with `type` through `mime.contentType()`486 * when it does not contain "/", or set the Content-Type to `type` otherwise.487 * When no mapping is found though `mime.contentType()`, the type is set to488 * "application/octet-stream".489 *490 * Examples:491 *492 * res.type('.html');493 * res.type('html');494 * res.type('json');495 * res.type('application/json');496 * res.type('png');497 *498 * @param {String} type499 * @return {ServerResponse} for chaining500 * @public501 */502503res.contentType =504res.type = function contentType(type) {505 var ct = type.indexOf('/') === -1506 ? (mime.contentType(type) || 'application/octet-stream')507 : type;508509 return this.set('Content-Type', ct);510};511512/**513 * Respond to the Acceptable formats using an `obj`514 * of mime-type callbacks.515 *516 * This method uses `req.accepted`, an array of517 * acceptable types ordered by their quality values.518 * When "Accept" is not present the _first_ callback519 * is invoked, otherwise the first match is used. When520 * no match is performed the server responds with521 * 406 "Not Acceptable".522 *523 * Content-Type is set for you, however if you choose524 * you may alter this within the callback using `res.type()`525 * or `res.set('Content-Type', ...)`.526 *527 * res.format({528 * 'text/plain': function(){529 * res.send('hey');530 * },531 *532 * 'text/html': function(){533 * res.send('<p>hey</p>');534 * },535 *536 * 'application/json': function () {537 * res.send({ message: 'hey' });538 * }539 * });540 *541 * In addition to canonicalized MIME types you may542 * also use extnames mapped to these types:543 *544 * res.format({545 * text: function(){546 * res.send('hey');547 * },548 *549 * html: function(){550 * res.send('<p>hey</p>');551 * },552 *553 * json: function(){554 * res.send({ message: 'hey' });555 * }556 * });557 *558 * By default Express passes an `Error`559 * with a `.status` of 406 to `next(err)`560 * if a match is not made. If you provide561 * a `.default` callback it will be invoked562 * instead.563 *564 * @param {Object} obj565 * @return {ServerResponse} for chaining566 * @public567 */568569res.format = function(obj){570 var req = this.req;571 var next = req.next;572573 var keys = Object.keys(obj)574 .filter(function (v) { return v !== 'default' })575576 var key = keys.length > 0577 ? req.accepts(keys)578 : false;579580 this.vary("Accept");581582 if (key) {583 this.set('Content-Type', normalizeType(key).value);584 obj[key](req, this, next);585 } else if (obj.default) {586 obj.default(req, this, next)587 } else {588 next(createError(406, {589 types: normalizeTypes(keys).map(function (o) { return o.value })590 }))591 }592593 return this;594};595596/**597 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.598 *599 * @param {String} filename600 * @return {ServerResponse}601 * @public602 */603604res.attachment = function attachment(filename) {605 if (filename) {606 this.type(extname(filename));607 }608609 this.set('Content-Disposition', contentDisposition(filename));610611 return this;612};613614/**615 * Append additional header `field` with value `val`.616 *617 * Example:618 *619 * res.append('Link', ['<http://localhost/>', '<http://localhost:3000/>']);620 * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly');621 * res.append('Warning', '199 Miscellaneous warning');622 *623 * @param {String} field624 * @param {String|Array} val625 * @return {ServerResponse} for chaining626 * @public627 */628629res.append = function append(field, val) {630 var prev = this.get(field);631 var value = val;632633 if (prev) {634 // concat the new and prev vals635 value = Array.isArray(prev) ? prev.concat(val)636 : Array.isArray(val) ? [prev].concat(val)637 : [prev, val]638 }639640 return this.set(field, value);641};642643/**644 * Set header `field` to `val`, or pass645 * an object of header fields.646 *647 * Examples:648 *649 * res.set('Foo', ['bar', 'baz']);650 * res.set('Accept', 'application/json');651 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });652 *653 * Aliased as `res.header()`.654 *655 * When the set header is "Content-Type", the type is expanded to include656 * the charset if not present using `mime.contentType()`.657 *658 * @param {String|Object} field659 * @param {String|Array} val660 * @return {ServerResponse} for chaining661 * @public662 */663664res.set =665res.header = function header(field, val) {666 if (arguments.length === 2) {667 var value = Array.isArray(val)668 ? val.map(String)669 : String(val);670671 // add charset to content-type672 if (field.toLowerCase() === 'content-type') {673 if (Array.isArray(value)) {674 throw new TypeError('Content-Type cannot be set to an Array');675 }676 value = mime.contentType(value)677 }678679 this.setHeader(field, value);680 } else {681 for (var key in field) {682 this.set(key, field[key]);683 }684 }685 return this;686};687688/**689 * Get value for header `field`.690 *691 * @param {String} field692 * @return {String}693 * @public694 */695696res.get = function(field){697 return this.getHeader(field);698};699700/**701 * Clear cookie `name`.702 *703 * @param {String} name704 * @param {Object} [options]705 * @return {ServerResponse} for chaining706 * @public707 */708709res.clearCookie = function clearCookie(name, options) {710 // Force cookie expiration by setting expires to the past711 const opts = { path: '/', ...options, expires: new Date(1)};712 // ensure maxAge is not passed713 delete opts.maxAge714715 return this.cookie(name, '', opts);716};717718/**719 * Set cookie `name` to `value`, with the given `options`.720 *721 * Options:722 *723 * - `maxAge` max-age in milliseconds, converted to `expires`724 * - `signed` sign the cookie725 * - `path` defaults to "/"726 *727 * Examples:728 *729 * // "Remember Me" for 15 minutes730 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });731 *732 * // same as above733 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })734 *735 * @param {String} name736 * @param {String|Object} value737 * @param {Object} [options]738 * @return {ServerResponse} for chaining739 * @public740 */741742res.cookie = function (name, value, options) {743 var opts = merge({}, options);744 var secret = this.req.secret;745 var signed = opts.signed;746747 if (signed && !secret) {748 throw new Error('cookieParser("secret") required for signed cookies');749 }750751 var val = typeof value === 'object'752 ? 'j:' + JSON.stringify(value)753 : String(value);754755 if (signed) {756 val = 's:' + sign(val, secret);757 }758759 if (opts.maxAge != null) {760 var maxAge = opts.maxAge - 0761762 if (!isNaN(maxAge)) {763 opts.expires = new Date(Date.now() + maxAge)764 opts.maxAge = Math.floor(maxAge / 1000)765 }766 }767768 if (opts.path == null) {769 opts.path = '/';770 }771772 this.append('Set-Cookie', cookie.serialize(name, String(val), opts));773774 return this;775};776777/**778 * Set the location header to `url`.779 *780 * The given `url` can also be "back", which redirects781 * to the _Referrer_ or _Referer_ headers or "/".782 *783 * Examples:784 *785 * res.location('/foo/bar').;786 * res.location('http://example.com');787 * res.location('../login');788 *789 * @param {String} url790 * @return {ServerResponse} for chaining791 * @public792 */793794res.location = function location(url) {795 var loc;796797 // "back" is an alias for the referrer798 if (url === 'back') {799 loc = this.req.get('Referrer') || '/';800 } else {801 loc = String(url);802 }803804 var m = schemaAndHostRegExp.exec(loc);805 var pos = m ? m[0].length + 1 : 0;806807 // Only encode after host to avoid invalid encoding which can introduce808 // vulnerabilities (e.g. `\\` to `%5C`).809 loc = loc.slice(0, pos) + encodeUrl(loc.slice(pos));810811 return this.set('Location', loc);812};813814/**815 * Redirect to the given `url` with optional response `status`816 * defaulting to 302.817 *818 * The resulting `url` is determined by `res.location()`, so819 * it will play nicely with mounted apps, relative paths,820 * `"back"` etc.821 *822 * Examples:823 *824 * res.redirect('/foo/bar');825 * res.redirect('http://example.com');826 * res.redirect(301, 'http://example.com');827 * res.redirect('../login'); // /blog/post/1 -> /blog/login828 *829 * @public830 */831832res.redirect = function redirect(url) {833 var address = url;834 var body;835 var status = 302;836837 // allow status / url838 if (arguments.length === 2) {839 status = arguments[0]840 address = arguments[1]841 }842843 // Set location header844 address = this.location(address).get('Location');845846 // Support text/{plain,html} by default847 this.format({848 text: function(){849 body = statuses.message[status] + '. Redirecting to ' + address850 },851852 html: function(){853 var u = escapeHtml(address);854 body = '<p>' + statuses.message[status] + '. Redirecting to <a href="' + u + '">' + u + '</a></p>'855 },856857 default: function(){858 body = '';859 }860 });861862 // Respond863 this.status(status);864 this.set('Content-Length', Buffer.byteLength(body));865866 if (this.req.method === 'HEAD') {867 this.end();868 } else {869 this.end(body);870 }871};872873/**874 * Add `field` to Vary. If already present in the Vary set, then875 * this call is simply ignored.876 *877 * @param {Array|String} field878 * @return {ServerResponse} for chaining879 * @public880 */881882res.vary = function(field){883 vary(this, field);884885 return this;886};887888/**889 * Render `view` with the given `options` and optional callback `fn`.890 * When a callback function is given a response will _not_ be made891 * automatically, otherwise a response of _200_ and _text/html_ is given.892 *893 * Options:894 *895 * - `cache` boolean hinting to the engine it should cache896 * - `filename` filename of the view being rendered897 *898 * @public899 */900901res.render = function render(view, options, callback) {902 var app = this.req.app;903 var done = callback;904 var opts = options || {};905 var req = this.req;906 var self = this;907908 // support callback function as second arg909 if (typeof options === 'function') {910 done = options;911 opts = {};912 }913914 // merge res.locals915 opts._locals = self.locals;916917 // default callback to respond918 done = done || function (err, str) {919 if (err) return req.next(err);920 self.send(str);921 };922923 // render924 app.render(view, opts, done);925};926927// pipe the send file stream928function sendfile(res, file, options, callback) {929 var done = false;930 var streaming;931932 // request aborted933 function onaborted() {934 if (done) return;935 done = true;936937 var err = new Error('Request aborted');938 err.code = 'ECONNABORTED';939 callback(err);940 }941942 // directory943 function ondirectory() {944 if (done) return;945 done = true;946947 var err = new Error('EISDIR, read');948 err.code = 'EISDIR';949 callback(err);950 }951952 // errors953 function onerror(err) {954 if (done) return;955 done = true;956 callback(err);957 }958959 // ended960 function onend() {961 if (done) return;962 done = true;963 callback();964 }965966 // file967 function onfile() {968 streaming = false;969 }970971 // finished972 function onfinish(err) {973 if (err && err.code === 'ECONNRESET') return onaborted();974 if (err) return onerror(err);975 if (done) return;976977 setImmediate(function () {978 if (streaming !== false && !done) {979 onaborted();980 return;981 }982983 if (done) return;984 done = true;985 callback();986 });987 }988989 // streaming990 function onstream() {991 streaming = true;992 }993994 file.on('directory', ondirectory);995 file.on('end', onend);996 file.on('error', onerror);997 file.on('file', onfile);998 file.on('stream', onstream);999 onFinished(res, onfinish);10001001 if (options.headers) {1002 // set headers on successful transfer1003 file.on('headers', function headers(res) {1004 var obj = options.headers;1005 var keys = Object.keys(obj);10061007 for (var i = 0; i < keys.length; i++) {1008 var k = keys[i];1009 res.setHeader(k, obj[k]);1010 }1011 });1012 }10131014 // pipe1015 file.pipe(res);1016}10171018/**1019 * Stringify JSON, like JSON.stringify, but v8 optimized, with the1020 * ability to escape characters that can trigger HTML sniffing.1021 *1022 * @param {*} value1023 * @param {function} replacer1024 * @param {number} spaces1025 * @param {boolean} escape1026 * @returns {string}1027 * @private1028 */10291030function stringify (value, replacer, spaces, escape) {1031 // v8 checks arguments.length for optimizing simple call1032 // https://bugs.chromium.org/p/v8/issues/detail?id=47301033 var json = replacer || spaces1034 ? JSON.stringify(value, replacer, spaces)1035 : JSON.stringify(value);10361037 if (escape && typeof json === 'string') {1038 json = json.replace(/[<>&]/g, function (c) {1039 switch (c.charCodeAt(0)) {1040 case 0x3c:1041 return '\\u003c'1042 case 0x3e:1043 return '\\u003e'1044 case 0x26:1045 return '\\u0026'1046 /* istanbul ignore next: unreachable default */1047 default:1048 return c1049 }1050 })1051 }10521053 return json1054}