Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

json-stream-stringify

Package Overview
Dependencies
Maintainers
1
Versions
27
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

json-stream-stringify - npm Package Compare versions

Comparing version 3.0.1 to 3.1.0

886

lib/cjs/index.js

@@ -7,37 +7,2 @@ 'use strict';

function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _defineProperty(obj, key, value) {

@@ -58,88 +23,7 @@ if (key in obj) {

function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
var _global, _global$JSON;
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
const rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
var rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var meta = {
const meta = {
'\b': '\\b',

@@ -174,7 +58,7 @@ '\t': '\\t',

if (Array.isArray(value)) return Types.Array;
if (_typeof(value) === 'object' || value instanceof Object) return Types.Object;
if (typeof value === 'object' || value instanceof Object) return Types.Object;
return Types.Primitive;
}
var stackItemOpen = [];
const stackItemOpen = [];
stackItemOpen[Types.Array] = '[';

@@ -184,3 +68,3 @@ stackItemOpen[Types.Object] = '{';

stackItemOpen[Types.ReadableObject] = '[';
var stackItemEnd = [];
const stackItemEnd = [];
stackItemEnd[Types.Array] = ']';

@@ -190,8 +74,2 @@ stackItemEnd[Types.Object] = '}';

stackItemEnd[Types.ReadableObject] = ']';
var processFunctionLookupTable = ['processArray', 'processObject', 'processReadableString', 'processReadableObject', 'processPrimitive', 'processPromise'];
/*
for (const [key, val] of Object.entries(Types)) {
if (typeof val === 'number') processFunctionLookupTable[val] = `process${key}`;
}
*/

@@ -205,24 +83,87 @@ function escapeString(string) {

// sequences.
return string.replace(rxEscapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c : "\\u".concat(a.charCodeAt(0).toString(16).padStart(4, '0'));
return string.replace(rxEscapable, a => {
const c = meta[a];
return typeof c === 'string' ? c : `\\u${a.charCodeAt(0).toString(16).padStart(4, '0')}`;
});
}
let primitiveToJSON;
if (((_global = global) === null || _global === void 0 ? void 0 : (_global$JSON = _global.JSON) === null || _global$JSON === void 0 ? void 0 : _global$JSON.stringify) instanceof Function) {
let canSerializeBigInt = true;
try {
if (JSON.stringify(global.BigInt ? global.BigInt('123') : '') !== '123') throw new Error();
} catch (err) {
canSerializeBigInt = false;
}
if (canSerializeBigInt) {
primitiveToJSON = JSON.parse;
} else {
// eslint-disable-next-line no-confusing-arrow
primitiveToJSON = value => typeof value === 'bigint' ? String(value) : JSON.stringify(value);
}
} else {
primitiveToJSON = value => {
switch (typeof value) {
case 'string':
return `"${escapeString(value)}"`;
case 'number':
return Number.isFinite(value) ? String(value) : 'null';
case 'bigint':
return String(value);
case 'boolean':
return value ? 'true' : 'false';
case 'object':
if (!value) {
return 'null';
}
// eslint-disable-next-line no-fallthrough
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error(`Not a primitive "${typeof value}".`), {
value
});
}
};
}
/*
function quoteString(string: string) {
return primitiveToJSON(String(string));
}
*/
const cache = new Map();
function quoteString(string) {
return "\"".concat(escapeString(string), "\"");
const useCache = string.length < 10000; // eslint-disable-next-line no-lonely-if
if (useCache && cache.has(string)) {
return cache.get(string);
}
const str = primitiveToJSON(String(string));
if (useCache) cache.set(string, str);
return str;
}
function readAsPromised(stream, size) {
var value = stream.read(size);
const value = stream.read(size);
if (value === null) {
return new Promise(function (resolve, reject) {
var endListener = function endListener() {
return resolve(null);
};
return new Promise((resolve, reject) => {
const endListener = () => resolve(null);
stream.once('end', endListener);
stream.once('error', reject);
stream.once('readable', function () {
stream.once('readable', () => {
stream.removeListener('end', endListener);

@@ -238,440 +179,449 @@ stream.removeListener('error', reject);

function recursiveResolve(promise) {
return promise.then(function (res) {
return getType(res) === Types.Promise ? recursiveResolve(res) : res;
});
}
var ReadState;
var JsonStreamStringify = /*#__PURE__*/function (_Readable) {
_inherits(JsonStreamStringify, _Readable);
(function (ReadState) {
ReadState[ReadState["NotReading"] = 0] = "NotReading";
ReadState[ReadState["Reading"] = 1] = "Reading";
ReadState[ReadState["ReadMore"] = 2] = "ReadMore";
ReadState[ReadState["Consumed"] = 3] = "Consumed";
})(ReadState || (ReadState = {}));
var _super = _createSuper(JsonStreamStringify);
class JsonStreamStringify extends stream.Readable {
constructor(input, replacer, spaces, cycle = false, bufferSize = 512) {
super({
encoding: 'utf8'
});
function JsonStreamStringify(value, replacer, spaces) {
var _this;
_defineProperty(this, "cycle", void 0);
var cycle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
_defineProperty(this, "bufferSize", void 0);
_classCallCheck(this, JsonStreamStringify);
_defineProperty(this, "item", void 0);
_this = _super.call(this, {
encoding: 'utf8'
});
_defineProperty(this, "indent", void 0);
_defineProperty(_assertThisInitialized(_this), "cycle", void 0);
_defineProperty(this, "root", void 0);
_defineProperty(_assertThisInitialized(_this), "visited", void 0);
_defineProperty(this, "include", void 0);
_defineProperty(_assertThisInitialized(_this), "stack", []);
_defineProperty(this, "replacer", void 0);
_defineProperty(_assertThisInitialized(_this), "replacerFunction", void 0);
_defineProperty(this, "visited", void 0);
_defineProperty(_assertThisInitialized(_this), "replacerArray", void 0);
_defineProperty(this, "objectItem", void 0);
_defineProperty(_assertThisInitialized(_this), "gap", void 0);
_defineProperty(this, "prePush", undefined);
_defineProperty(_assertThisInitialized(_this), "depth", 0);
_defineProperty(this, "buffer", '');
_defineProperty(_assertThisInitialized(_this), "error", void 0);
_defineProperty(this, "bufferLength", 0);
_defineProperty(_assertThisInitialized(_this), "pushCalled", false);
_defineProperty(this, "pushCalled", false);
_defineProperty(_assertThisInitialized(_this), "end", false);
_defineProperty(this, "readSize", 0);
_defineProperty(_assertThisInitialized(_this), "isReading", false);
_defineProperty(this, "reading", false);
_defineProperty(_assertThisInitialized(_this), "readMore", false);
_defineProperty(this, "readMore", false);
_this.cycle = cycle;
_defineProperty(this, "readState", ReadState.NotReading);
var spaceType = _typeof(spaces);
this.cycle = cycle;
this.bufferSize = bufferSize;
const spaceType = typeof spaces;
if (spaceType === 'string' || spaceType === 'number') {
_this.gap = Number.isFinite(spaces) ? ' '.repeat(spaces) : spaces;
if (spaceType === 'number') {
this.indent = ' '.repeat(spaces);
} else if (spaceType === 'string') {
this.indent = spaces;
}
Object.assign(_assertThisInitialized(_this), {
visited: cycle ? new WeakMap() : new WeakSet(),
replacerFunction: replacer instanceof Function && replacer,
replacerArray: Array.isArray(replacer) && replacer
});
if (replacer instanceof Function) _this.replacerFunction = replacer;
if (Array.isArray(replacer)) _this.replacerArray = replacer;
const replacerType = typeof replacer;
_this.addToStack(value);
if (replacerType === 'object') {
this.include = replacer;
} else if (replacerType === 'function') {
this.replacer = replacer;
}
return _this;
this.visited = cycle ? new WeakMap() : [];
this.root = {
value: {
'': input
},
depth: 0,
indent: '',
path: []
};
this.setItem(input, this.root, '');
}
_createClass(JsonStreamStringify, [{
key: "cycler",
value: function cycler(key, value) {
var existingPath = this.visited.get(value);
setItem(value, parent, key = '') {
// call toJSON where applicable
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
value = value.toJSON(key);
} // use replacer if applicable
if (existingPath) {
return {
$ref: existingPath
};
}
var path = this.path();
if (key !== undefined) path.push(key);
path = path.map(function (v) {
return "[".concat(Number.isInteger(v) ? v : quoteString(v), "]");
});
this.visited.set(value, path.length ? "$".concat(path.join('')) : '$');
return value;
}
}, {
key: "addToStack",
value: function addToStack(value, key, index, parent) {
var _this2 = this;
if (this.replacer) {
value = this.replacer.call(parent.value, key, value);
} // coerece functions and symbols into undefined
var realValue = value;
if (this.replacerFunction) {
realValue = this.replacerFunction(key || index, realValue, this);
} // ORDER?
if (value instanceof Function || typeof value === 'symbol') {
value = undefined;
}
const type = getType(value);
let path; // check for circular structure
if (realValue && realValue.toJSON instanceof Function) {
realValue = realValue.toJSON();
if (!this.cycle && type !== Types.Primitive) {
if (this.visited.some(v => v === value)) {
this.destroy(Object.assign(new Error('Converting circular structure to JSON'), {
value,
key
}));
return;
}
if (realValue instanceof Function || _typeof(value) === 'symbol') {
realValue = undefined;
this.visited.push(value);
} else if (this.cycle && type !== Types.Primitive) {
path = this.visited.get(value);
if (path) {
this._push(`{"$ref":"$${path.map(v => `[${Number.isInteger(v) ? v : escapeString(quoteString(v))}]`).join('')}"}`);
this.item = parent;
return;
}
if (key !== undefined && this.replacerArray) {
if (!this.replacerArray.includes(key)) {
realValue = undefined;
}
path = parent === this.root ? [] : parent.path.concat(key);
this.visited.set(value, path);
}
if (type === Types.Object) {
this.setObjectItem(value, parent);
} else if (type === Types.Array) {
this.setArrayItem(value, parent);
} else if (type === Types.Primitive) {
if (parent !== this.root && typeof key === 'string') {
// (<any>parent).write(key, primitiveToJSON(value));
if (value === undefined) ; else {
this._push(primitiveToJSON(value));
} // undefined values in objects should be rejected
} else if (value === undefined && typeof key === 'number') {
// undefined values in array should be null
this._push('null');
} else if (value === undefined) ; else {
this._push(primitiveToJSON(value));
}
var type = getType(realValue);
this.item = parent;
return;
} else if (type === Types.Promise) {
this.setPromiseItem(value, parent, key);
} else if (type === Types.ReadableString) {
this.setReadableStringItem(value, parent);
} else if (type === Types.ReadableObject) {
this.setReadableObjectItem(value, parent);
}
if ((parent && parent.type === Types.Array ? true : realValue !== undefined) && type !== Types.Promise) {
if (parent && !parent.first) {
this._push(',');
} // eslint-disable-next-line no-param-reassign
this.item.value = value;
this.item.depth = parent.depth + 1;
if (this.indent) this.item.indent = this.indent.repeat(this.item.depth);
this.item.path = path;
}
setReadableStringItem(input, parent) {
var _input$_readableState, _input$_readableState2;
if (parent) parent.first = false;
}
if (input.readableEnded || (_input$_readableState = input._readableState) !== null && _input$_readableState !== void 0 && _input$_readableState.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState2 = input._readableState) !== null && _input$_readableState2 !== void 0 && _input$_readableState2.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue !== undefined && type !== Types.Promise && key !== undefined) {
if (this.gap) {
this._push("\n".concat(this.gap.repeat(this.depth), "\"").concat(escapeString(key), "\": "));
} else {
this._push("\"".concat(escapeString(key), "\":"));
}
}
const that = this;
if (type !== Types.Primitive) {
if (this.cycle) {
// run cycler
realValue = this.cycler(key || index, realValue);
type = getType(realValue);
} else {
// check for circular structure
if (this.visited.has(realValue)) {
throw Object.assign(new Error('Converting circular structure to JSON'), {
realValue: realValue,
key: key || index
});
}
this._push('"');
this.visited.add(realValue);
input.once('end', () => {
this._push('"');
this.item = parent;
this.emit('readable');
});
this.item = {
type: 'readable string',
async read(size) {
try {
const data = await readAsPromised(input, size);
if (data) that._push(escapeString(data.toString()));
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
if (!key && index > -1 && this.depth && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
var open = stackItemOpen[type];
if (open) this._push(open);
var obj = {
key: key,
index: index,
type: type,
parent: parent,
value: realValue,
first: true
};
};
}
if (type === Types.Object) {
this.depth += 1;
obj.unread = Object.keys(realValue);
obj.isEmpty = !obj.unread.length;
} else if (type === Types.Array) {
this.depth += 1;
obj.unread = realValue.length;
obj.arrayLength = obj.unread;
obj.isEmpty = !obj.unread;
} else if (type === Types.ReadableString || type === Types.ReadableObject) {
var _realValue$_readableS, _realValue$_readableS2;
setReadableObjectItem(input, parent) {
var _input$_readableState3, _input$_readableState4;
this.depth += 1;
if (input.readableEnded || (_input$_readableState3 = input._readableState) !== null && _input$_readableState3 !== void 0 && _input$_readableState3.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState4 = input._readableState) !== null && _input$_readableState4 !== void 0 && _input$_readableState4.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue.readableEnded || (_realValue$_readableS = realValue._readableState) !== null && _realValue$_readableS !== void 0 && _realValue$_readableS.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), realValue, key || index);
} else if (realValue.readableFlowing || (_realValue$_readableS2 = realValue._readableState) !== null && _realValue$_readableS2 !== void 0 && _realValue$_readableS2.flowing) {
realValue.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), realValue, key || index);
}
const that = this;
obj.readCount = 0;
realValue.once('end', function () {
obj.end = true;
this._push('[');
_this2.__read();
});
realValue.once('error', function (err) {
_this2.error = true;
let first = true;
let i = 0;
const item = {
type: 'readable object',
_this2.emit('error', err);
});
}
async read(size) {
try {
let out = '';
const data = await readAsPromised(input, size);
this.stack.unshift(obj);
return obj;
}
}, {
key: "removeFromStack",
value: function removeFromStack(item) {
var type = item.type;
var isObject = type === Types.Object || type === Types.Array || type === Types.ReadableString || type === Types.ReadableObject;
if (data === null) {
if (i && that.indent) {
out += `\n${parent.indent}`;
}
if (type !== Types.Primitive) {
if (!this.cycle) {
this.visited["delete"](item.value);
}
out += ']';
if (isObject) {
this.depth -= 1;
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (first) first = false;else out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(data, item, i);
i += 1;
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
var end = stackItemEnd[type];
if (isObject && !item.isEmpty && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
if (end) this._push(end);
var stackIndex = this.stack.indexOf(item);
this.stack.splice(stackIndex, 1);
} // tslint:disable-next-line:function-name
};
this.item = item;
}
}, {
key: "_push",
value: function _push(data) {
this.pushCalled = true;
this.push(data);
}
}, {
key: "processReadableObject",
value: function processReadableObject(current, size) {
var _this3 = this;
if (current.end) {
this.removeFromStack(current);
return undefined;
setPromiseItem(input, parent, key) {
const that = this;
let read = false;
this.item = {
async read() {
if (read) return;
read = true;
input.then(v => that.setItem(v, parent, key), err => {
that.emit('error', err);
that.destroy();
});
}
return readAsPromised(current.value, size).then(function (value) {
if (value !== null) {
if (!current.first) {
_this3._push(',');
} // eslint-disable-next-line no-param-reassign
};
}
setArrayItem(input, parent) {
// const entries = input.slice().reverse();
let i = 0;
const len = input.length;
let first = true;
const that = this;
const item = {
read() {
let out = '';
let wasFirst = false;
current.first = false;
if (first) {
first = false;
wasFirst = true;
_this3.addToStack(value, undefined, current.readCount); // eslint-disable-next-line no-param-reassign
if (!len) {
that._push('[]');
that.item = parent;
return;
}
current.readCount += 1;
out += '[';
}
});
}
}, {
key: "processObject",
value: function processObject(current) {
// when no keys left, remove obj from stack
if (!current.unread.length) {
this.removeFromStack(current);
return;
}
var key = current.unread.shift();
var value = current.value[key];
this.addToStack(value, key, undefined, current);
}
}, {
key: "processArray",
value: function processArray(current) {
var key = current.unread;
const entry = input[i];
if (!key) {
this.removeFromStack(current);
return;
if (i === len) {
if (that.indent) out += `\n${parent.indent}`;
out += ']';
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (!wasFirst) out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(entry, item, i);
i += 1;
}
var index = current.arrayLength - key;
var value = current.value[index]; // eslint-disable-next-line no-param-reassign
};
this.item = item;
}
current.unread -= 1;
this.addToStack(value, undefined, index, current);
}
}, {
key: "processPrimitive",
value: function processPrimitive(current) {
if (current.value !== undefined) {
var type = _typeof(current.value);
unvisit(item) {
if (this.cycle) return;
var value;
const _i = this.visited.indexOf(item);
switch (type) {
case 'string':
value = quoteString(current.value);
break;
if (_i > -1) this.visited.splice(_i, 1);
}
case 'number':
value = Number.isFinite(current.value) ? String(current.value) : 'null';
break;
setObjectItem(input, parent = undefined) {
const keys = Object.keys(input);
let i = 0;
const len = keys.length;
let first = true;
const that = this;
const {
include
} = this;
let hasItems = false;
let key;
const item = {
read() {
var _include$indexOf;
case 'bigint':
value = String(current.value);
break;
if (i === 0) that._push('{');
case 'boolean':
value = String(current.value);
break;
if (i === len) {
that.objectItem = undefined;
case 'object':
if (!current.value) {
value = 'null';
break;
}
if (!hasItems) {
that._push('}');
} else {
that._push(`${that.indent ? `\n${parent.indent}` : ''}}`);
}
// eslint-disable-next-line no-fallthrough
that.item = parent;
that.unvisit(input);
return;
}
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error("Unknown type \"".concat(type, "\". Please file an issue!")), {
value: current.value
});
key = keys[i];
if ((include === null || include === void 0 ? void 0 : (_include$indexOf = include.indexOf) === null || _include$indexOf === void 0 ? void 0 : _include$indexOf.call(include, key)) === -1) {
// replacer array excludes this key
i += 1;
return;
}
this._push(value);
} else if (this.stack[1] && (this.stack[1].type === Types.Array || this.stack[1].type === Types.ReadableObject)) {
this._push('null');
} else {
// eslint-disable-next-line no-param-reassign
current.addSeparatorAfterEnd = false;
that.objectItem = item;
i += 1;
that.setItem(input[key], item, key);
},
write() {
const out = `${hasItems && !first ? ',' : ''}${item.indent ? `\n${item.indent}` : ''}${quoteString(key)}:${that.indent ? ' ' : ''}`;
first = false;
hasItems = true;
that.objectItem = undefined;
return out;
}
this.removeFromStack(current);
}
}, {
key: "processReadableString",
value: function processReadableString(current, size) {
var _this4 = this;
};
this.item = item;
}
if (current.end) {
this.removeFromStack(current);
return undefined;
}
_push(data) {
this.buffer += (this.objectItem ? this.objectItem.write() : '') + data;
this.prePush = undefined;
return readAsPromised(current.value, size).then(function (value) {
if (value) _this4._push(escapeString(value.toString()));
});
if (this.buffer.length >= this.bufferSize) {
this.pushCalled = !this.push(this.buffer);
this.buffer = '';
this.bufferLength = 0;
return false;
}
}, {
key: "processPromise",
value: function processPromise(current) {
var _this5 = this;
return recursiveResolve(current.value).then(function (value) {
_this5.removeFromStack(current);
return true;
}
_this5.addToStack(value, current.key, current.index, current.parent);
});
async _read(size) {
if (this.readState !== ReadState.NotReading) {
this.readState = ReadState.ReadMore;
return;
}
}, {
key: "processStackTopItem",
value: function processStackTopItem(size) {
var _this6 = this;
var current = this.stack[0];
if (!current || this.error) return Promise.resolve();
var out;
this.readState = ReadState.Reading;
this.pushCalled = false;
let p;
try {
out = this[processFunctionLookupTable[current.type]](current, size);
} catch (err) {
return Promise.reject(err);
}
while (!this.pushCalled && this.item !== this.root && !this.destroyed) {
p = this.item.read(size); // eslint-disable-next-line no-await-in-loop
return Promise.resolve(out).then(function () {
if (_this6.stack.length === 0) {
_this6.end = true;
if (p) await p;
}
_this6._push(null);
}
});
} // tslint:disable-next-line:function-name
if (this.item === this.root) {
if (this.buffer.length) this.push(this.buffer);
this.push(null);
this.readState = ReadState.Consumed;
}, {
key: "__read",
value: function __read(size) {
var _this7 = this;
this._destroy();
}
if (this.isReading || this.error) {
this.readMore = true;
return undefined;
}
if (this.readState === ReadState.ReadMore) {
this.readState = ReadState.NotReading;
this.isReading = true; // we must continue to read while push has not been called
this._read(size);
}
this.readMore = false;
return this.processStackTopItem(size).then(function () {
var readAgain = !_this7.end && !_this7.error && (_this7.readMore || !_this7.pushCalled);
this.readState = ReadState.NotReading;
}
if (readAgain) {
setImmediate(function () {
_this7.isReading = false;
_destroy() {
this.destroyed = true;
this.buffer = undefined;
this.visited = undefined;
this.item = undefined;
this.prePush = undefined;
}
_this7.__read();
});
} else {
_this7.isReading = false;
}
})["catch"](function (err) {
_this7.error = true;
destroy(error) {
var _super$destroy;
_this7.emit('error', err);
});
} // tslint:disable-next-line:function-name
if (error) this.emit('error', error);
(_super$destroy = super.destroy) === null || _super$destroy === void 0 ? void 0 : _super$destroy.call(this);
}, {
key: "_read",
value: function _read(size) {
this.pushCalled = false;
this._destroy();
this.__read(size);
}
}, {
key: "path",
value: function path() {
return this.stack.map(function (_ref) {
var key = _ref.key,
index = _ref.index;
return key || index;
}).filter(function (v) {
return v || v > -1;
}).reverse();
}
}]);
return this;
}
return JsonStreamStringify;
}(stream.Readable);
}
exports.JsonStreamStringify = JsonStreamStringify;
//# sourceMappingURL=index.js.map

@@ -5,41 +5,10 @@ 'use strict';

require('core-js/modules/es.reflect.construct.js');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _assertThisInitialized = require('@babel/runtime/helpers/assertThisInitialized');
var _inherits = require('@babel/runtime/helpers/inherits');
var _possibleConstructorReturn = require('@babel/runtime/helpers/possibleConstructorReturn');
var _getPrototypeOf = require('@babel/runtime/helpers/getPrototypeOf');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _typeof = require('@babel/runtime/helpers/typeof');
require('core-js/modules/es.array.is-array.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.replace.js');
require('core-js/modules/es.string.pad-start.js');
require('core-js/modules/es.date.to-string.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.regexp.to-string.js');
require('core-js/modules/es.promise.js');
require('core-js/modules/es.number.is-finite.js');
require('core-js/modules/es.number.constructor.js');
require('core-js/modules/es.string.repeat.js');
require('core-js/modules/es.object.assign.js');
require('core-js/modules/es.array.iterator.js');
require('core-js/modules/es.string.iterator.js');
require('core-js/modules/es.weak-map.js');
require('core-js/modules/web.dom-collections.iterator.js');
require('core-js/modules/es.weak-set.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.number.is-integer.js');
require('core-js/modules/es.array.join.js');
require('core-js/modules/es.date.to-json.js');
require('core-js/modules/es.promise.js');
require('core-js/modules/web.url.to-json.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.array.index-of.js');
require('core-js/modules/es.array.splice.js');
require('core-js/modules/web.immediate.js');
require('core-js/modules/es.array.filter.js');
var stream = require('stream');

@@ -49,18 +18,9 @@

var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
var _global, _global$JSON;
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
const rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var meta = {
const meta = {
'\b': '\\b',

@@ -95,7 +55,7 @@ '\t': '\\t',

if (Array.isArray(value)) return Types.Array;
if (_typeof__default["default"](value) === 'object' || value instanceof Object) return Types.Object;
if (typeof value === 'object' || value instanceof Object) return Types.Object;
return Types.Primitive;
}
var stackItemOpen = [];
const stackItemOpen = [];
stackItemOpen[Types.Array] = '[';

@@ -105,3 +65,3 @@ stackItemOpen[Types.Object] = '{';

stackItemOpen[Types.ReadableObject] = '[';
var stackItemEnd = [];
const stackItemEnd = [];
stackItemEnd[Types.Array] = ']';

@@ -111,8 +71,2 @@ stackItemEnd[Types.Object] = '}';

stackItemEnd[Types.ReadableObject] = ']';
var processFunctionLookupTable = ['processArray', 'processObject', 'processReadableString', 'processReadableObject', 'processPrimitive', 'processPromise'];
/*
for (const [key, val] of Object.entries(Types)) {
if (typeof val === 'number') processFunctionLookupTable[val] = `process${key}`;
}
*/

@@ -126,24 +80,87 @@ function escapeString(string) {

// sequences.
return string.replace(rxEscapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c : "\\u".concat(a.charCodeAt(0).toString(16).padStart(4, '0'));
return string.replace(rxEscapable, a => {
const c = meta[a];
return typeof c === 'string' ? c : `\\u${a.charCodeAt(0).toString(16).padStart(4, '0')}`;
});
}
let primitiveToJSON;
if (((_global = global) === null || _global === void 0 ? void 0 : (_global$JSON = _global.JSON) === null || _global$JSON === void 0 ? void 0 : _global$JSON.stringify) instanceof Function) {
let canSerializeBigInt = true;
try {
if (JSON.stringify(global.BigInt ? global.BigInt('123') : '') !== '123') throw new Error();
} catch (err) {
canSerializeBigInt = false;
}
if (canSerializeBigInt) {
primitiveToJSON = JSON.parse;
} else {
// eslint-disable-next-line no-confusing-arrow
primitiveToJSON = value => typeof value === 'bigint' ? String(value) : JSON.stringify(value);
}
} else {
primitiveToJSON = value => {
switch (typeof value) {
case 'string':
return `"${escapeString(value)}"`;
case 'number':
return Number.isFinite(value) ? String(value) : 'null';
case 'bigint':
return String(value);
case 'boolean':
return value ? 'true' : 'false';
case 'object':
if (!value) {
return 'null';
}
// eslint-disable-next-line no-fallthrough
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error(`Not a primitive "${typeof value}".`), {
value
});
}
};
}
/*
function quoteString(string: string) {
return primitiveToJSON(String(string));
}
*/
const cache = new Map();
function quoteString(string) {
return "\"".concat(escapeString(string), "\"");
const useCache = string.length < 10000; // eslint-disable-next-line no-lonely-if
if (useCache && cache.has(string)) {
return cache.get(string);
}
const str = primitiveToJSON(String(string));
if (useCache) cache.set(string, str);
return str;
}
function readAsPromised(stream, size) {
var value = stream.read(size);
const value = stream.read(size);
if (value === null) {
return new Promise(function (resolve, reject) {
var endListener = function endListener() {
return resolve(null);
};
return new Promise((resolve, reject) => {
const endListener = () => resolve(null);
stream.once('end', endListener);
stream.once('error', reject);
stream.once('readable', function () {
stream.once('readable', () => {
stream.removeListener('end', endListener);

@@ -159,440 +176,449 @@ stream.removeListener('error', reject);

function recursiveResolve(promise) {
return promise.then(function (res) {
return getType(res) === Types.Promise ? recursiveResolve(res) : res;
});
}
var ReadState;
var JsonStreamStringify = /*#__PURE__*/function (_Readable) {
_inherits__default["default"](JsonStreamStringify, _Readable);
(function (ReadState) {
ReadState[ReadState["NotReading"] = 0] = "NotReading";
ReadState[ReadState["Reading"] = 1] = "Reading";
ReadState[ReadState["ReadMore"] = 2] = "ReadMore";
ReadState[ReadState["Consumed"] = 3] = "Consumed";
})(ReadState || (ReadState = {}));
var _super = _createSuper(JsonStreamStringify);
class JsonStreamStringify extends stream.Readable {
constructor(input, replacer, spaces, cycle = false, bufferSize = 512) {
super({
encoding: 'utf8'
});
function JsonStreamStringify(value, replacer, spaces) {
var _this;
_defineProperty__default["default"](this, "cycle", void 0);
var cycle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
_defineProperty__default["default"](this, "bufferSize", void 0);
_classCallCheck__default["default"](this, JsonStreamStringify);
_defineProperty__default["default"](this, "item", void 0);
_this = _super.call(this, {
encoding: 'utf8'
});
_defineProperty__default["default"](this, "indent", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "cycle", void 0);
_defineProperty__default["default"](this, "root", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "visited", void 0);
_defineProperty__default["default"](this, "include", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "stack", []);
_defineProperty__default["default"](this, "replacer", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "replacerFunction", void 0);
_defineProperty__default["default"](this, "visited", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "replacerArray", void 0);
_defineProperty__default["default"](this, "objectItem", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "gap", void 0);
_defineProperty__default["default"](this, "prePush", undefined);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "depth", 0);
_defineProperty__default["default"](this, "buffer", '');
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "error", void 0);
_defineProperty__default["default"](this, "bufferLength", 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "pushCalled", false);
_defineProperty__default["default"](this, "pushCalled", false);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "end", false);
_defineProperty__default["default"](this, "readSize", 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "isReading", false);
_defineProperty__default["default"](this, "reading", false);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "readMore", false);
_defineProperty__default["default"](this, "readMore", false);
_this.cycle = cycle;
_defineProperty__default["default"](this, "readState", ReadState.NotReading);
var spaceType = _typeof__default["default"](spaces);
this.cycle = cycle;
this.bufferSize = bufferSize;
const spaceType = typeof spaces;
if (spaceType === 'string' || spaceType === 'number') {
_this.gap = Number.isFinite(spaces) ? ' '.repeat(spaces) : spaces;
if (spaceType === 'number') {
this.indent = ' '.repeat(spaces);
} else if (spaceType === 'string') {
this.indent = spaces;
}
Object.assign(_assertThisInitialized__default["default"](_this), {
visited: cycle ? new WeakMap() : new WeakSet(),
replacerFunction: replacer instanceof Function && replacer,
replacerArray: Array.isArray(replacer) && replacer
});
if (replacer instanceof Function) _this.replacerFunction = replacer;
if (Array.isArray(replacer)) _this.replacerArray = replacer;
const replacerType = typeof replacer;
_this.addToStack(value);
if (replacerType === 'object') {
this.include = replacer;
} else if (replacerType === 'function') {
this.replacer = replacer;
}
return _this;
this.visited = cycle ? new WeakMap() : [];
this.root = {
value: {
'': input
},
depth: 0,
indent: '',
path: []
};
this.setItem(input, this.root, '');
}
_createClass__default["default"](JsonStreamStringify, [{
key: "cycler",
value: function cycler(key, value) {
var existingPath = this.visited.get(value);
setItem(value, parent, key = '') {
// call toJSON where applicable
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
value = value.toJSON(key);
} // use replacer if applicable
if (existingPath) {
return {
$ref: existingPath
};
}
var path = this.path();
if (key !== undefined) path.push(key);
path = path.map(function (v) {
return "[".concat(Number.isInteger(v) ? v : quoteString(v), "]");
});
this.visited.set(value, path.length ? "$".concat(path.join('')) : '$');
return value;
}
}, {
key: "addToStack",
value: function addToStack(value, key, index, parent) {
var _this2 = this;
if (this.replacer) {
value = this.replacer.call(parent.value, key, value);
} // coerece functions and symbols into undefined
var realValue = value;
if (this.replacerFunction) {
realValue = this.replacerFunction(key || index, realValue, this);
} // ORDER?
if (value instanceof Function || typeof value === 'symbol') {
value = undefined;
}
const type = getType(value);
let path; // check for circular structure
if (realValue && realValue.toJSON instanceof Function) {
realValue = realValue.toJSON();
if (!this.cycle && type !== Types.Primitive) {
if (this.visited.some(v => v === value)) {
this.destroy(Object.assign(new Error('Converting circular structure to JSON'), {
value,
key
}));
return;
}
if (realValue instanceof Function || _typeof__default["default"](value) === 'symbol') {
realValue = undefined;
this.visited.push(value);
} else if (this.cycle && type !== Types.Primitive) {
path = this.visited.get(value);
if (path) {
this._push(`{"$ref":"$${path.map(v => `[${Number.isInteger(v) ? v : escapeString(quoteString(v))}]`).join('')}"}`);
this.item = parent;
return;
}
if (key !== undefined && this.replacerArray) {
if (!this.replacerArray.includes(key)) {
realValue = undefined;
}
path = parent === this.root ? [] : parent.path.concat(key);
this.visited.set(value, path);
}
if (type === Types.Object) {
this.setObjectItem(value, parent);
} else if (type === Types.Array) {
this.setArrayItem(value, parent);
} else if (type === Types.Primitive) {
if (parent !== this.root && typeof key === 'string') {
// (<any>parent).write(key, primitiveToJSON(value));
if (value === undefined) ; else {
this._push(primitiveToJSON(value));
} // undefined values in objects should be rejected
} else if (value === undefined && typeof key === 'number') {
// undefined values in array should be null
this._push('null');
} else if (value === undefined) ; else {
this._push(primitiveToJSON(value));
}
var type = getType(realValue);
this.item = parent;
return;
} else if (type === Types.Promise) {
this.setPromiseItem(value, parent, key);
} else if (type === Types.ReadableString) {
this.setReadableStringItem(value, parent);
} else if (type === Types.ReadableObject) {
this.setReadableObjectItem(value, parent);
}
if ((parent && parent.type === Types.Array ? true : realValue !== undefined) && type !== Types.Promise) {
if (parent && !parent.first) {
this._push(',');
} // eslint-disable-next-line no-param-reassign
this.item.value = value;
this.item.depth = parent.depth + 1;
if (this.indent) this.item.indent = this.indent.repeat(this.item.depth);
this.item.path = path;
}
setReadableStringItem(input, parent) {
var _input$_readableState, _input$_readableState2;
if (parent) parent.first = false;
}
if (input.readableEnded || (_input$_readableState = input._readableState) !== null && _input$_readableState !== void 0 && _input$_readableState.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState2 = input._readableState) !== null && _input$_readableState2 !== void 0 && _input$_readableState2.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue !== undefined && type !== Types.Promise && key !== undefined) {
if (this.gap) {
this._push("\n".concat(this.gap.repeat(this.depth), "\"").concat(escapeString(key), "\": "));
} else {
this._push("\"".concat(escapeString(key), "\":"));
}
}
const that = this;
if (type !== Types.Primitive) {
if (this.cycle) {
// run cycler
realValue = this.cycler(key || index, realValue);
type = getType(realValue);
} else {
// check for circular structure
if (this.visited.has(realValue)) {
throw Object.assign(new Error('Converting circular structure to JSON'), {
realValue: realValue,
key: key || index
});
}
this._push('"');
this.visited.add(realValue);
input.once('end', () => {
this._push('"');
this.item = parent;
this.emit('readable');
});
this.item = {
type: 'readable string',
async read(size) {
try {
const data = await readAsPromised(input, size);
if (data) that._push(escapeString(data.toString()));
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
if (!key && index > -1 && this.depth && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
var open = stackItemOpen[type];
if (open) this._push(open);
var obj = {
key: key,
index: index,
type: type,
parent: parent,
value: realValue,
first: true
};
};
}
if (type === Types.Object) {
this.depth += 1;
obj.unread = Object.keys(realValue);
obj.isEmpty = !obj.unread.length;
} else if (type === Types.Array) {
this.depth += 1;
obj.unread = realValue.length;
obj.arrayLength = obj.unread;
obj.isEmpty = !obj.unread;
} else if (type === Types.ReadableString || type === Types.ReadableObject) {
var _realValue$_readableS, _realValue$_readableS2;
setReadableObjectItem(input, parent) {
var _input$_readableState3, _input$_readableState4;
this.depth += 1;
if (input.readableEnded || (_input$_readableState3 = input._readableState) !== null && _input$_readableState3 !== void 0 && _input$_readableState3.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState4 = input._readableState) !== null && _input$_readableState4 !== void 0 && _input$_readableState4.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue.readableEnded || (_realValue$_readableS = realValue._readableState) !== null && _realValue$_readableS !== void 0 && _realValue$_readableS.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), realValue, key || index);
} else if (realValue.readableFlowing || (_realValue$_readableS2 = realValue._readableState) !== null && _realValue$_readableS2 !== void 0 && _realValue$_readableS2.flowing) {
realValue.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), realValue, key || index);
}
const that = this;
obj.readCount = 0;
realValue.once('end', function () {
obj.end = true;
this._push('[');
_this2.__read();
});
realValue.once('error', function (err) {
_this2.error = true;
let first = true;
let i = 0;
const item = {
type: 'readable object',
_this2.emit('error', err);
});
}
async read(size) {
try {
let out = '';
const data = await readAsPromised(input, size);
this.stack.unshift(obj);
return obj;
}
}, {
key: "removeFromStack",
value: function removeFromStack(item) {
var type = item.type;
var isObject = type === Types.Object || type === Types.Array || type === Types.ReadableString || type === Types.ReadableObject;
if (data === null) {
if (i && that.indent) {
out += `\n${parent.indent}`;
}
if (type !== Types.Primitive) {
if (!this.cycle) {
this.visited["delete"](item.value);
}
out += ']';
if (isObject) {
this.depth -= 1;
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (first) first = false;else out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(data, item, i);
i += 1;
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
var end = stackItemEnd[type];
if (isObject && !item.isEmpty && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
if (end) this._push(end);
var stackIndex = this.stack.indexOf(item);
this.stack.splice(stackIndex, 1);
} // tslint:disable-next-line:function-name
};
this.item = item;
}
}, {
key: "_push",
value: function _push(data) {
this.pushCalled = true;
this.push(data);
}
}, {
key: "processReadableObject",
value: function processReadableObject(current, size) {
var _this3 = this;
if (current.end) {
this.removeFromStack(current);
return undefined;
setPromiseItem(input, parent, key) {
const that = this;
let read = false;
this.item = {
async read() {
if (read) return;
read = true;
input.then(v => that.setItem(v, parent, key), err => {
that.emit('error', err);
that.destroy();
});
}
return readAsPromised(current.value, size).then(function (value) {
if (value !== null) {
if (!current.first) {
_this3._push(',');
} // eslint-disable-next-line no-param-reassign
};
}
setArrayItem(input, parent) {
// const entries = input.slice().reverse();
let i = 0;
const len = input.length;
let first = true;
const that = this;
const item = {
read() {
let out = '';
let wasFirst = false;
current.first = false;
if (first) {
first = false;
wasFirst = true;
_this3.addToStack(value, undefined, current.readCount); // eslint-disable-next-line no-param-reassign
if (!len) {
that._push('[]');
that.item = parent;
return;
}
current.readCount += 1;
out += '[';
}
});
}
}, {
key: "processObject",
value: function processObject(current) {
// when no keys left, remove obj from stack
if (!current.unread.length) {
this.removeFromStack(current);
return;
}
var key = current.unread.shift();
var value = current.value[key];
this.addToStack(value, key, undefined, current);
}
}, {
key: "processArray",
value: function processArray(current) {
var key = current.unread;
const entry = input[i];
if (!key) {
this.removeFromStack(current);
return;
if (i === len) {
if (that.indent) out += `\n${parent.indent}`;
out += ']';
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (!wasFirst) out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(entry, item, i);
i += 1;
}
var index = current.arrayLength - key;
var value = current.value[index]; // eslint-disable-next-line no-param-reassign
};
this.item = item;
}
current.unread -= 1;
this.addToStack(value, undefined, index, current);
}
}, {
key: "processPrimitive",
value: function processPrimitive(current) {
if (current.value !== undefined) {
var type = _typeof__default["default"](current.value);
unvisit(item) {
if (this.cycle) return;
var value;
const _i = this.visited.indexOf(item);
switch (type) {
case 'string':
value = quoteString(current.value);
break;
if (_i > -1) this.visited.splice(_i, 1);
}
case 'number':
value = Number.isFinite(current.value) ? String(current.value) : 'null';
break;
setObjectItem(input, parent = undefined) {
const keys = Object.keys(input);
let i = 0;
const len = keys.length;
let first = true;
const that = this;
const {
include
} = this;
let hasItems = false;
let key;
const item = {
read() {
var _include$indexOf;
case 'bigint':
value = String(current.value);
break;
if (i === 0) that._push('{');
case 'boolean':
value = String(current.value);
break;
if (i === len) {
that.objectItem = undefined;
case 'object':
if (!current.value) {
value = 'null';
break;
}
if (!hasItems) {
that._push('}');
} else {
that._push(`${that.indent ? `\n${parent.indent}` : ''}}`);
}
// eslint-disable-next-line no-fallthrough
that.item = parent;
that.unvisit(input);
return;
}
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error("Unknown type \"".concat(type, "\". Please file an issue!")), {
value: current.value
});
key = keys[i];
if ((include === null || include === void 0 ? void 0 : (_include$indexOf = include.indexOf) === null || _include$indexOf === void 0 ? void 0 : _include$indexOf.call(include, key)) === -1) {
// replacer array excludes this key
i += 1;
return;
}
this._push(value);
} else if (this.stack[1] && (this.stack[1].type === Types.Array || this.stack[1].type === Types.ReadableObject)) {
this._push('null');
} else {
// eslint-disable-next-line no-param-reassign
current.addSeparatorAfterEnd = false;
that.objectItem = item;
i += 1;
that.setItem(input[key], item, key);
},
write() {
const out = `${hasItems && !first ? ',' : ''}${item.indent ? `\n${item.indent}` : ''}${quoteString(key)}:${that.indent ? ' ' : ''}`;
first = false;
hasItems = true;
that.objectItem = undefined;
return out;
}
this.removeFromStack(current);
}
}, {
key: "processReadableString",
value: function processReadableString(current, size) {
var _this4 = this;
};
this.item = item;
}
if (current.end) {
this.removeFromStack(current);
return undefined;
}
_push(data) {
this.buffer += (this.objectItem ? this.objectItem.write() : '') + data;
this.prePush = undefined;
return readAsPromised(current.value, size).then(function (value) {
if (value) _this4._push(escapeString(value.toString()));
});
if (this.buffer.length >= this.bufferSize) {
this.pushCalled = !this.push(this.buffer);
this.buffer = '';
this.bufferLength = 0;
return false;
}
}, {
key: "processPromise",
value: function processPromise(current) {
var _this5 = this;
return recursiveResolve(current.value).then(function (value) {
_this5.removeFromStack(current);
return true;
}
_this5.addToStack(value, current.key, current.index, current.parent);
});
async _read(size) {
if (this.readState !== ReadState.NotReading) {
this.readState = ReadState.ReadMore;
return;
}
}, {
key: "processStackTopItem",
value: function processStackTopItem(size) {
var _this6 = this;
var current = this.stack[0];
if (!current || this.error) return Promise.resolve();
var out;
this.readState = ReadState.Reading;
this.pushCalled = false;
let p;
try {
out = this[processFunctionLookupTable[current.type]](current, size);
} catch (err) {
return Promise.reject(err);
}
while (!this.pushCalled && this.item !== this.root && !this.destroyed) {
p = this.item.read(size); // eslint-disable-next-line no-await-in-loop
return Promise.resolve(out).then(function () {
if (_this6.stack.length === 0) {
_this6.end = true;
if (p) await p;
}
_this6._push(null);
}
});
} // tslint:disable-next-line:function-name
if (this.item === this.root) {
if (this.buffer.length) this.push(this.buffer);
this.push(null);
this.readState = ReadState.Consumed;
}, {
key: "__read",
value: function __read(size) {
var _this7 = this;
this._destroy();
}
if (this.isReading || this.error) {
this.readMore = true;
return undefined;
}
if (this.readState === ReadState.ReadMore) {
this.readState = ReadState.NotReading;
this.isReading = true; // we must continue to read while push has not been called
this._read(size);
}
this.readMore = false;
return this.processStackTopItem(size).then(function () {
var readAgain = !_this7.end && !_this7.error && (_this7.readMore || !_this7.pushCalled);
this.readState = ReadState.NotReading;
}
if (readAgain) {
setImmediate(function () {
_this7.isReading = false;
_destroy() {
this.destroyed = true;
this.buffer = undefined;
this.visited = undefined;
this.item = undefined;
this.prePush = undefined;
}
_this7.__read();
});
} else {
_this7.isReading = false;
}
})["catch"](function (err) {
_this7.error = true;
destroy(error) {
var _super$destroy;
_this7.emit('error', err);
});
} // tslint:disable-next-line:function-name
if (error) this.emit('error', error);
(_super$destroy = super.destroy) === null || _super$destroy === void 0 ? void 0 : _super$destroy.call(this);
}, {
key: "_read",
value: function _read(size) {
this.pushCalled = false;
this._destroy();
this.__read(size);
}
}, {
key: "path",
value: function path() {
return this.stack.map(function (_ref) {
var key = _ref.key,
index = _ref.index;
return key || index;
}).filter(function (v) {
return v || v > -1;
}).reverse();
}
}]);
return this;
}
return JsonStreamStringify;
}(stream.Readable);
}
exports.JsonStreamStringify = JsonStreamStringify;
//# sourceMappingURL=polyfill.js.map
import { Readable } from 'stream';
declare enum Types {
Array = 0,
Object = 1,
ReadableString = 2,
ReadableObject = 3,
Primitive = 4,
Promise = 5
interface Item {
read(size?: number): Promise<void> | void;
depth?: number;
value?: any;
indent?: string;
path?: (string | number)[];
}
interface IStackItem {
key?: string;
index?: number;
type: Types;
value: any;
parent?: IStackItem;
first: boolean;
unread?: string[] | number;
isEmpty?: boolean;
arrayLength?: number;
readCount?: number;
end?: boolean;
addSeparatorAfterEnd?: boolean;
declare enum ReadState {
NotReading = 0,
Reading = 1,
ReadMore = 2,
Consumed = 3
}
declare class JsonStreamStringify extends Readable {
private cycle;
private visited;
private stack;
private replacerFunction?;
private replacerArray?;
private gap?;
private depth;
private error;
private pushCalled;
private end;
private isReading;
private readMore;
constructor(value: any, replacer?: Function | any[], spaces?: number | string, cycle?: boolean);
private cycler;
private addToStack;
private removeFromStack;
private bufferSize;
item?: Item;
indent?: string;
root: Item;
include: string[];
replacer: Function;
visited: [] | WeakMap<any, string[]>;
constructor(input: any, replacer?: Function | any[] | undefined, spaces?: number | string | undefined, cycle?: boolean, bufferSize?: number);
setItem(value: any, parent: Item, key?: string | number): void;
setReadableStringItem(input: Readable, parent: Item): void;
setReadableObjectItem(input: Readable, parent: Item): void;
setPromiseItem(input: Promise<any>, parent: Item, key: any): void;
setArrayItem(input: any[], parent: any): void;
unvisit(item: any): void;
objectItem?: any;
setObjectItem(input: Record<any, any>, parent?: any): void;
prePush?: Function;
buffer: string;
bufferLength: number;
pushCalled: boolean;
readSize: number;
private _push;
private processReadableObject;
private processObject;
private processArray;
processPrimitive(current: IStackItem): void;
private processReadableString;
private processPromise;
private processStackTopItem;
private __read;
_read(size: number): void;
path(): (string | number)[];
reading: boolean;
readMore: boolean;
readState: ReadState;
_read(size?: number): Promise<void>;
_destroy(): void;
destroy(error?: Error): this;
}
export { JsonStreamStringify };

@@ -7,37 +7,2 @@ (function (global, factory) {

function _typeof(obj) {
"@babel/helpers - typeof";
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
}, _typeof(obj);
}
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
Object.defineProperty(Constructor, "prototype", {
writable: false
});
return Constructor;
}
function _defineProperty(obj, key, value) {

@@ -58,88 +23,7 @@ if (key in obj) {

function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
var _global, _global$JSON;
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
Object.defineProperty(subClass, "prototype", {
writable: false
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
const rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _isNativeReflectConstruct() {
if (typeof Reflect === "undefined" || !Reflect.construct) return false;
if (Reflect.construct.sham) return false;
if (typeof Proxy === "function") return true;
try {
Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
return true;
} catch (e) {
return false;
}
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _possibleConstructorReturn(self, call) {
if (call && (typeof call === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _createSuper(Derived) {
var hasNativeReflectConstruct = _isNativeReflectConstruct();
return function _createSuperInternal() {
var Super = _getPrototypeOf(Derived),
result;
if (hasNativeReflectConstruct) {
var NewTarget = _getPrototypeOf(this).constructor;
result = Reflect.construct(Super, arguments, NewTarget);
} else {
result = Super.apply(this, arguments);
}
return _possibleConstructorReturn(this, result);
};
}
var rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var meta = {
const meta = {
'\b': '\\b',

@@ -174,7 +58,7 @@ '\t': '\\t',

if (Array.isArray(value)) return Types.Array;
if (_typeof(value) === 'object' || value instanceof Object) return Types.Object;
if (typeof value === 'object' || value instanceof Object) return Types.Object;
return Types.Primitive;
}
var stackItemOpen = [];
const stackItemOpen = [];
stackItemOpen[Types.Array] = '[';

@@ -184,3 +68,3 @@ stackItemOpen[Types.Object] = '{';

stackItemOpen[Types.ReadableObject] = '[';
var stackItemEnd = [];
const stackItemEnd = [];
stackItemEnd[Types.Array] = ']';

@@ -190,8 +74,2 @@ stackItemEnd[Types.Object] = '}';

stackItemEnd[Types.ReadableObject] = ']';
var processFunctionLookupTable = ['processArray', 'processObject', 'processReadableString', 'processReadableObject', 'processPrimitive', 'processPromise'];
/*
for (const [key, val] of Object.entries(Types)) {
if (typeof val === 'number') processFunctionLookupTable[val] = `process${key}`;
}
*/

@@ -205,24 +83,87 @@ function escapeString(string) {

// sequences.
return string.replace(rxEscapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c : "\\u".concat(a.charCodeAt(0).toString(16).padStart(4, '0'));
return string.replace(rxEscapable, a => {
const c = meta[a];
return typeof c === 'string' ? c : `\\u${a.charCodeAt(0).toString(16).padStart(4, '0')}`;
});
}
let primitiveToJSON;
if (((_global = global) === null || _global === void 0 ? void 0 : (_global$JSON = _global.JSON) === null || _global$JSON === void 0 ? void 0 : _global$JSON.stringify) instanceof Function) {
let canSerializeBigInt = true;
try {
if (JSON.stringify(global.BigInt ? global.BigInt('123') : '') !== '123') throw new Error();
} catch (err) {
canSerializeBigInt = false;
}
if (canSerializeBigInt) {
primitiveToJSON = JSON.parse;
} else {
// eslint-disable-next-line no-confusing-arrow
primitiveToJSON = value => typeof value === 'bigint' ? String(value) : JSON.stringify(value);
}
} else {
primitiveToJSON = value => {
switch (typeof value) {
case 'string':
return `"${escapeString(value)}"`;
case 'number':
return Number.isFinite(value) ? String(value) : 'null';
case 'bigint':
return String(value);
case 'boolean':
return value ? 'true' : 'false';
case 'object':
if (!value) {
return 'null';
}
// eslint-disable-next-line no-fallthrough
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error(`Not a primitive "${typeof value}".`), {
value
});
}
};
}
/*
function quoteString(string: string) {
return primitiveToJSON(String(string));
}
*/
const cache = new Map();
function quoteString(string) {
return "\"".concat(escapeString(string), "\"");
const useCache = string.length < 10000; // eslint-disable-next-line no-lonely-if
if (useCache && cache.has(string)) {
return cache.get(string);
}
const str = primitiveToJSON(String(string));
if (useCache) cache.set(string, str);
return str;
}
function readAsPromised(stream, size) {
var value = stream.read(size);
const value = stream.read(size);
if (value === null) {
return new Promise(function (resolve, reject) {
var endListener = function endListener() {
return resolve(null);
};
return new Promise((resolve, reject) => {
const endListener = () => resolve(null);
stream.once('end', endListener);
stream.once('error', reject);
stream.once('readable', function () {
stream.once('readable', () => {
stream.removeListener('end', endListener);

@@ -238,438 +179,447 @@ stream.removeListener('error', reject);

function recursiveResolve(promise) {
return promise.then(function (res) {
return getType(res) === Types.Promise ? recursiveResolve(res) : res;
});
}
var ReadState;
var JsonStreamStringify = /*#__PURE__*/function (_Readable) {
_inherits(JsonStreamStringify, _Readable);
(function (ReadState) {
ReadState[ReadState["NotReading"] = 0] = "NotReading";
ReadState[ReadState["Reading"] = 1] = "Reading";
ReadState[ReadState["ReadMore"] = 2] = "ReadMore";
ReadState[ReadState["Consumed"] = 3] = "Consumed";
})(ReadState || (ReadState = {}));
var _super = _createSuper(JsonStreamStringify);
class JsonStreamStringify extends stream.Readable {
constructor(input, replacer, spaces, cycle = false, bufferSize = 512) {
super({
encoding: 'utf8'
});
function JsonStreamStringify(value, replacer, spaces) {
var _this;
_defineProperty(this, "cycle", void 0);
var cycle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
_defineProperty(this, "bufferSize", void 0);
_classCallCheck(this, JsonStreamStringify);
_defineProperty(this, "item", void 0);
_this = _super.call(this, {
encoding: 'utf8'
});
_defineProperty(this, "indent", void 0);
_defineProperty(_assertThisInitialized(_this), "cycle", void 0);
_defineProperty(this, "root", void 0);
_defineProperty(_assertThisInitialized(_this), "visited", void 0);
_defineProperty(this, "include", void 0);
_defineProperty(_assertThisInitialized(_this), "stack", []);
_defineProperty(this, "replacer", void 0);
_defineProperty(_assertThisInitialized(_this), "replacerFunction", void 0);
_defineProperty(this, "visited", void 0);
_defineProperty(_assertThisInitialized(_this), "replacerArray", void 0);
_defineProperty(this, "objectItem", void 0);
_defineProperty(_assertThisInitialized(_this), "gap", void 0);
_defineProperty(this, "prePush", undefined);
_defineProperty(_assertThisInitialized(_this), "depth", 0);
_defineProperty(this, "buffer", '');
_defineProperty(_assertThisInitialized(_this), "error", void 0);
_defineProperty(this, "bufferLength", 0);
_defineProperty(_assertThisInitialized(_this), "pushCalled", false);
_defineProperty(this, "pushCalled", false);
_defineProperty(_assertThisInitialized(_this), "end", false);
_defineProperty(this, "readSize", 0);
_defineProperty(_assertThisInitialized(_this), "isReading", false);
_defineProperty(this, "reading", false);
_defineProperty(_assertThisInitialized(_this), "readMore", false);
_defineProperty(this, "readMore", false);
_this.cycle = cycle;
_defineProperty(this, "readState", ReadState.NotReading);
var spaceType = _typeof(spaces);
this.cycle = cycle;
this.bufferSize = bufferSize;
const spaceType = typeof spaces;
if (spaceType === 'string' || spaceType === 'number') {
_this.gap = Number.isFinite(spaces) ? ' '.repeat(spaces) : spaces;
if (spaceType === 'number') {
this.indent = ' '.repeat(spaces);
} else if (spaceType === 'string') {
this.indent = spaces;
}
Object.assign(_assertThisInitialized(_this), {
visited: cycle ? new WeakMap() : new WeakSet(),
replacerFunction: replacer instanceof Function && replacer,
replacerArray: Array.isArray(replacer) && replacer
});
if (replacer instanceof Function) _this.replacerFunction = replacer;
if (Array.isArray(replacer)) _this.replacerArray = replacer;
const replacerType = typeof replacer;
_this.addToStack(value);
if (replacerType === 'object') {
this.include = replacer;
} else if (replacerType === 'function') {
this.replacer = replacer;
}
return _this;
this.visited = cycle ? new WeakMap() : [];
this.root = {
value: {
'': input
},
depth: 0,
indent: '',
path: []
};
this.setItem(input, this.root, '');
}
_createClass(JsonStreamStringify, [{
key: "cycler",
value: function cycler(key, value) {
var existingPath = this.visited.get(value);
setItem(value, parent, key = '') {
// call toJSON where applicable
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
value = value.toJSON(key);
} // use replacer if applicable
if (existingPath) {
return {
$ref: existingPath
};
}
var path = this.path();
if (key !== undefined) path.push(key);
path = path.map(function (v) {
return "[".concat(Number.isInteger(v) ? v : quoteString(v), "]");
});
this.visited.set(value, path.length ? "$".concat(path.join('')) : '$');
return value;
}
}, {
key: "addToStack",
value: function addToStack(value, key, index, parent) {
var _this2 = this;
if (this.replacer) {
value = this.replacer.call(parent.value, key, value);
} // coerece functions and symbols into undefined
var realValue = value;
if (this.replacerFunction) {
realValue = this.replacerFunction(key || index, realValue, this);
} // ORDER?
if (value instanceof Function || typeof value === 'symbol') {
value = undefined;
}
const type = getType(value);
let path; // check for circular structure
if (realValue && realValue.toJSON instanceof Function) {
realValue = realValue.toJSON();
if (!this.cycle && type !== Types.Primitive) {
if (this.visited.some(v => v === value)) {
this.destroy(Object.assign(new Error('Converting circular structure to JSON'), {
value,
key
}));
return;
}
if (realValue instanceof Function || _typeof(value) === 'symbol') {
realValue = undefined;
this.visited.push(value);
} else if (this.cycle && type !== Types.Primitive) {
path = this.visited.get(value);
if (path) {
this._push(`{"$ref":"$${path.map(v => `[${Number.isInteger(v) ? v : escapeString(quoteString(v))}]`).join('')}"}`);
this.item = parent;
return;
}
if (key !== undefined && this.replacerArray) {
if (!this.replacerArray.includes(key)) {
realValue = undefined;
}
path = parent === this.root ? [] : parent.path.concat(key);
this.visited.set(value, path);
}
if (type === Types.Object) {
this.setObjectItem(value, parent);
} else if (type === Types.Array) {
this.setArrayItem(value, parent);
} else if (type === Types.Primitive) {
if (parent !== this.root && typeof key === 'string') {
// (<any>parent).write(key, primitiveToJSON(value));
if (value === undefined) ; else {
this._push(primitiveToJSON(value));
} // undefined values in objects should be rejected
} else if (value === undefined && typeof key === 'number') {
// undefined values in array should be null
this._push('null');
} else if (value === undefined) ; else {
this._push(primitiveToJSON(value));
}
var type = getType(realValue);
this.item = parent;
return;
} else if (type === Types.Promise) {
this.setPromiseItem(value, parent, key);
} else if (type === Types.ReadableString) {
this.setReadableStringItem(value, parent);
} else if (type === Types.ReadableObject) {
this.setReadableObjectItem(value, parent);
}
if ((parent && parent.type === Types.Array ? true : realValue !== undefined) && type !== Types.Promise) {
if (parent && !parent.first) {
this._push(',');
} // eslint-disable-next-line no-param-reassign
this.item.value = value;
this.item.depth = parent.depth + 1;
if (this.indent) this.item.indent = this.indent.repeat(this.item.depth);
this.item.path = path;
}
setReadableStringItem(input, parent) {
var _input$_readableState, _input$_readableState2;
if (parent) parent.first = false;
}
if (input.readableEnded || (_input$_readableState = input._readableState) !== null && _input$_readableState !== void 0 && _input$_readableState.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState2 = input._readableState) !== null && _input$_readableState2 !== void 0 && _input$_readableState2.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue !== undefined && type !== Types.Promise && key !== undefined) {
if (this.gap) {
this._push("\n".concat(this.gap.repeat(this.depth), "\"").concat(escapeString(key), "\": "));
} else {
this._push("\"".concat(escapeString(key), "\":"));
}
}
const that = this;
if (type !== Types.Primitive) {
if (this.cycle) {
// run cycler
realValue = this.cycler(key || index, realValue);
type = getType(realValue);
} else {
// check for circular structure
if (this.visited.has(realValue)) {
throw Object.assign(new Error('Converting circular structure to JSON'), {
realValue: realValue,
key: key || index
});
}
this._push('"');
this.visited.add(realValue);
input.once('end', () => {
this._push('"');
this.item = parent;
this.emit('readable');
});
this.item = {
type: 'readable string',
async read(size) {
try {
const data = await readAsPromised(input, size);
if (data) that._push(escapeString(data.toString()));
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
if (!key && index > -1 && this.depth && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
var open = stackItemOpen[type];
if (open) this._push(open);
var obj = {
key: key,
index: index,
type: type,
parent: parent,
value: realValue,
first: true
};
};
}
if (type === Types.Object) {
this.depth += 1;
obj.unread = Object.keys(realValue);
obj.isEmpty = !obj.unread.length;
} else if (type === Types.Array) {
this.depth += 1;
obj.unread = realValue.length;
obj.arrayLength = obj.unread;
obj.isEmpty = !obj.unread;
} else if (type === Types.ReadableString || type === Types.ReadableObject) {
var _realValue$_readableS, _realValue$_readableS2;
setReadableObjectItem(input, parent) {
var _input$_readableState3, _input$_readableState4;
this.depth += 1;
if (input.readableEnded || (_input$_readableState3 = input._readableState) !== null && _input$_readableState3 !== void 0 && _input$_readableState3.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState4 = input._readableState) !== null && _input$_readableState4 !== void 0 && _input$_readableState4.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue.readableEnded || (_realValue$_readableS = realValue._readableState) !== null && _realValue$_readableS !== void 0 && _realValue$_readableS.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), realValue, key || index);
} else if (realValue.readableFlowing || (_realValue$_readableS2 = realValue._readableState) !== null && _realValue$_readableS2 !== void 0 && _realValue$_readableS2.flowing) {
realValue.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), realValue, key || index);
}
const that = this;
obj.readCount = 0;
realValue.once('end', function () {
obj.end = true;
this._push('[');
_this2.__read();
});
realValue.once('error', function (err) {
_this2.error = true;
let first = true;
let i = 0;
const item = {
type: 'readable object',
_this2.emit('error', err);
});
}
async read(size) {
try {
let out = '';
const data = await readAsPromised(input, size);
this.stack.unshift(obj);
return obj;
}
}, {
key: "removeFromStack",
value: function removeFromStack(item) {
var type = item.type;
var isObject = type === Types.Object || type === Types.Array || type === Types.ReadableString || type === Types.ReadableObject;
if (data === null) {
if (i && that.indent) {
out += `\n${parent.indent}`;
}
if (type !== Types.Primitive) {
if (!this.cycle) {
this.visited["delete"](item.value);
}
out += ']';
if (isObject) {
this.depth -= 1;
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (first) first = false;else out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(data, item, i);
i += 1;
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
var end = stackItemEnd[type];
if (isObject && !item.isEmpty && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
if (end) this._push(end);
var stackIndex = this.stack.indexOf(item);
this.stack.splice(stackIndex, 1);
} // tslint:disable-next-line:function-name
};
this.item = item;
}
}, {
key: "_push",
value: function _push(data) {
this.pushCalled = true;
this.push(data);
}
}, {
key: "processReadableObject",
value: function processReadableObject(current, size) {
var _this3 = this;
if (current.end) {
this.removeFromStack(current);
return undefined;
setPromiseItem(input, parent, key) {
const that = this;
let read = false;
this.item = {
async read() {
if (read) return;
read = true;
input.then(v => that.setItem(v, parent, key), err => {
that.emit('error', err);
that.destroy();
});
}
return readAsPromised(current.value, size).then(function (value) {
if (value !== null) {
if (!current.first) {
_this3._push(',');
} // eslint-disable-next-line no-param-reassign
};
}
setArrayItem(input, parent) {
// const entries = input.slice().reverse();
let i = 0;
const len = input.length;
let first = true;
const that = this;
const item = {
read() {
let out = '';
let wasFirst = false;
current.first = false;
if (first) {
first = false;
wasFirst = true;
_this3.addToStack(value, undefined, current.readCount); // eslint-disable-next-line no-param-reassign
if (!len) {
that._push('[]');
that.item = parent;
return;
}
current.readCount += 1;
out += '[';
}
});
}
}, {
key: "processObject",
value: function processObject(current) {
// when no keys left, remove obj from stack
if (!current.unread.length) {
this.removeFromStack(current);
return;
}
var key = current.unread.shift();
var value = current.value[key];
this.addToStack(value, key, undefined, current);
}
}, {
key: "processArray",
value: function processArray(current) {
var key = current.unread;
const entry = input[i];
if (!key) {
this.removeFromStack(current);
return;
if (i === len) {
if (that.indent) out += `\n${parent.indent}`;
out += ']';
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (!wasFirst) out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(entry, item, i);
i += 1;
}
var index = current.arrayLength - key;
var value = current.value[index]; // eslint-disable-next-line no-param-reassign
};
this.item = item;
}
current.unread -= 1;
this.addToStack(value, undefined, index, current);
}
}, {
key: "processPrimitive",
value: function processPrimitive(current) {
if (current.value !== undefined) {
var type = _typeof(current.value);
unvisit(item) {
if (this.cycle) return;
var value;
const _i = this.visited.indexOf(item);
switch (type) {
case 'string':
value = quoteString(current.value);
break;
if (_i > -1) this.visited.splice(_i, 1);
}
case 'number':
value = Number.isFinite(current.value) ? String(current.value) : 'null';
break;
setObjectItem(input, parent = undefined) {
const keys = Object.keys(input);
let i = 0;
const len = keys.length;
let first = true;
const that = this;
const {
include
} = this;
let hasItems = false;
let key;
const item = {
read() {
var _include$indexOf;
case 'bigint':
value = String(current.value);
break;
if (i === 0) that._push('{');
case 'boolean':
value = String(current.value);
break;
if (i === len) {
that.objectItem = undefined;
case 'object':
if (!current.value) {
value = 'null';
break;
}
if (!hasItems) {
that._push('}');
} else {
that._push(`${that.indent ? `\n${parent.indent}` : ''}}`);
}
// eslint-disable-next-line no-fallthrough
that.item = parent;
that.unvisit(input);
return;
}
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error("Unknown type \"".concat(type, "\". Please file an issue!")), {
value: current.value
});
key = keys[i];
if ((include === null || include === void 0 ? void 0 : (_include$indexOf = include.indexOf) === null || _include$indexOf === void 0 ? void 0 : _include$indexOf.call(include, key)) === -1) {
// replacer array excludes this key
i += 1;
return;
}
this._push(value);
} else if (this.stack[1] && (this.stack[1].type === Types.Array || this.stack[1].type === Types.ReadableObject)) {
this._push('null');
} else {
// eslint-disable-next-line no-param-reassign
current.addSeparatorAfterEnd = false;
that.objectItem = item;
i += 1;
that.setItem(input[key], item, key);
},
write() {
const out = `${hasItems && !first ? ',' : ''}${item.indent ? `\n${item.indent}` : ''}${quoteString(key)}:${that.indent ? ' ' : ''}`;
first = false;
hasItems = true;
that.objectItem = undefined;
return out;
}
this.removeFromStack(current);
}
}, {
key: "processReadableString",
value: function processReadableString(current, size) {
var _this4 = this;
};
this.item = item;
}
if (current.end) {
this.removeFromStack(current);
return undefined;
}
_push(data) {
this.buffer += (this.objectItem ? this.objectItem.write() : '') + data;
this.prePush = undefined;
return readAsPromised(current.value, size).then(function (value) {
if (value) _this4._push(escapeString(value.toString()));
});
if (this.buffer.length >= this.bufferSize) {
this.pushCalled = !this.push(this.buffer);
this.buffer = '';
this.bufferLength = 0;
return false;
}
}, {
key: "processPromise",
value: function processPromise(current) {
var _this5 = this;
return recursiveResolve(current.value).then(function (value) {
_this5.removeFromStack(current);
return true;
}
_this5.addToStack(value, current.key, current.index, current.parent);
});
async _read(size) {
if (this.readState !== ReadState.NotReading) {
this.readState = ReadState.ReadMore;
return;
}
}, {
key: "processStackTopItem",
value: function processStackTopItem(size) {
var _this6 = this;
var current = this.stack[0];
if (!current || this.error) return Promise.resolve();
var out;
this.readState = ReadState.Reading;
this.pushCalled = false;
let p;
try {
out = this[processFunctionLookupTable[current.type]](current, size);
} catch (err) {
return Promise.reject(err);
}
while (!this.pushCalled && this.item !== this.root && !this.destroyed) {
p = this.item.read(size); // eslint-disable-next-line no-await-in-loop
return Promise.resolve(out).then(function () {
if (_this6.stack.length === 0) {
_this6.end = true;
if (p) await p;
}
_this6._push(null);
}
});
} // tslint:disable-next-line:function-name
if (this.item === this.root) {
if (this.buffer.length) this.push(this.buffer);
this.push(null);
this.readState = ReadState.Consumed;
}, {
key: "__read",
value: function __read(size) {
var _this7 = this;
this._destroy();
}
if (this.isReading || this.error) {
this.readMore = true;
return undefined;
}
if (this.readState === ReadState.ReadMore) {
this.readState = ReadState.NotReading;
this.isReading = true; // we must continue to read while push has not been called
this._read(size);
}
this.readMore = false;
return this.processStackTopItem(size).then(function () {
var readAgain = !_this7.end && !_this7.error && (_this7.readMore || !_this7.pushCalled);
this.readState = ReadState.NotReading;
}
if (readAgain) {
setImmediate(function () {
_this7.isReading = false;
_destroy() {
this.destroyed = true;
this.buffer = undefined;
this.visited = undefined;
this.item = undefined;
this.prePush = undefined;
}
_this7.__read();
});
} else {
_this7.isReading = false;
}
})["catch"](function (err) {
_this7.error = true;
destroy(error) {
var _super$destroy;
_this7.emit('error', err);
});
} // tslint:disable-next-line:function-name
if (error) this.emit('error', error);
(_super$destroy = super.destroy) === null || _super$destroy === void 0 ? void 0 : _super$destroy.call(this);
}, {
key: "_read",
value: function _read(size) {
this.pushCalled = false;
this._destroy();
this.__read(size);
}
}, {
key: "path",
value: function path() {
return this.stack.map(function (_ref) {
var key = _ref.key,
index = _ref.index;
return key || index;
}).filter(function (v) {
return v || v > -1;
}).reverse();
}
}]);
return this;
}
return JsonStreamStringify;
}(stream.Readable);
}

@@ -676,0 +626,0 @@ exports.JsonStreamStringify = JsonStreamStringify;

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('core-js/modules/es.reflect.construct.js'), require('@babel/runtime/helpers/classCallCheck'), require('@babel/runtime/helpers/createClass'), require('@babel/runtime/helpers/assertThisInitialized'), require('@babel/runtime/helpers/inherits'), require('@babel/runtime/helpers/possibleConstructorReturn'), require('@babel/runtime/helpers/getPrototypeOf'), require('@babel/runtime/helpers/defineProperty'), require('@babel/runtime/helpers/typeof'), require('core-js/modules/es.array.is-array.js'), require('core-js/modules/es.regexp.exec.js'), require('core-js/modules/es.string.replace.js'), require('core-js/modules/es.string.pad-start.js'), require('core-js/modules/es.date.to-string.js'), require('core-js/modules/es.object.to-string.js'), require('core-js/modules/es.regexp.to-string.js'), require('core-js/modules/es.promise.js'), require('core-js/modules/es.number.is-finite.js'), require('core-js/modules/es.number.constructor.js'), require('core-js/modules/es.string.repeat.js'), require('core-js/modules/es.object.assign.js'), require('core-js/modules/es.array.iterator.js'), require('core-js/modules/es.string.iterator.js'), require('core-js/modules/es.weak-map.js'), require('core-js/modules/web.dom-collections.iterator.js'), require('core-js/modules/es.weak-set.js'), require('core-js/modules/es.array.map.js'), require('core-js/modules/es.number.is-integer.js'), require('core-js/modules/es.array.join.js'), require('core-js/modules/es.date.to-json.js'), require('core-js/modules/web.url.to-json.js'), require('core-js/modules/es.array.includes.js'), require('core-js/modules/es.string.includes.js'), require('core-js/modules/es.array.concat.js'), require('core-js/modules/es.object.keys.js'), require('core-js/modules/es.array.index-of.js'), require('core-js/modules/es.array.splice.js'), require('core-js/modules/web.immediate.js'), require('core-js/modules/es.array.filter.js'), require('stream')) :
typeof define === 'function' && define.amd ? define(['exports', 'core-js/modules/es.reflect.construct.js', '@babel/runtime/helpers/classCallCheck', '@babel/runtime/helpers/createClass', '@babel/runtime/helpers/assertThisInitialized', '@babel/runtime/helpers/inherits', '@babel/runtime/helpers/possibleConstructorReturn', '@babel/runtime/helpers/getPrototypeOf', '@babel/runtime/helpers/defineProperty', '@babel/runtime/helpers/typeof', 'core-js/modules/es.array.is-array.js', 'core-js/modules/es.regexp.exec.js', 'core-js/modules/es.string.replace.js', 'core-js/modules/es.string.pad-start.js', 'core-js/modules/es.date.to-string.js', 'core-js/modules/es.object.to-string.js', 'core-js/modules/es.regexp.to-string.js', 'core-js/modules/es.promise.js', 'core-js/modules/es.number.is-finite.js', 'core-js/modules/es.number.constructor.js', 'core-js/modules/es.string.repeat.js', 'core-js/modules/es.object.assign.js', 'core-js/modules/es.array.iterator.js', 'core-js/modules/es.string.iterator.js', 'core-js/modules/es.weak-map.js', 'core-js/modules/web.dom-collections.iterator.js', 'core-js/modules/es.weak-set.js', 'core-js/modules/es.array.map.js', 'core-js/modules/es.number.is-integer.js', 'core-js/modules/es.array.join.js', 'core-js/modules/es.date.to-json.js', 'core-js/modules/web.url.to-json.js', 'core-js/modules/es.array.includes.js', 'core-js/modules/es.string.includes.js', 'core-js/modules/es.array.concat.js', 'core-js/modules/es.object.keys.js', 'core-js/modules/es.array.index-of.js', 'core-js/modules/es.array.splice.js', 'core-js/modules/web.immediate.js', 'core-js/modules/es.array.filter.js', 'stream'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jsonStreamStringify = {}, null, global._classCallCheck, global._createClass, global._assertThisInitialized, global._inherits, global._possibleConstructorReturn, global._getPrototypeOf, global._defineProperty, global._typeof, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, global.stream));
})(this, (function (exports, es_reflect_construct_js, _classCallCheck, _createClass, _assertThisInitialized, _inherits, _possibleConstructorReturn, _getPrototypeOf, _defineProperty, _typeof, es_array_isArray_js, es_regexp_exec_js, es_string_replace_js, es_string_padStart_js, es_date_toString_js, es_object_toString_js, es_regexp_toString_js, es_promise_js, es_number_isFinite_js, es_number_constructor_js, es_string_repeat_js, es_object_assign_js, es_array_iterator_js, es_string_iterator_js, es_weakMap_js, web_domCollections_iterator_js, es_weakSet_js, es_array_map_js, es_number_isInteger_js, es_array_join_js, es_date_toJson_js, web_url_toJson_js, es_array_includes_js, es_string_includes_js, es_array_concat_js, es_object_keys_js, es_array_indexOf_js, es_array_splice_js, web_immediate_js, es_array_filter_js, stream) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@babel/runtime/helpers/defineProperty'), require('core-js/modules/es.regexp.exec.js'), require('core-js/modules/es.string.replace.js'), require('core-js/modules/es.string.pad-start.js'), require('core-js/modules/es.array.iterator.js'), require('core-js/modules/web.dom-collections.iterator.js'), require('core-js/modules/es.promise.js'), require('core-js/modules/web.url.to-json.js'), require('stream')) :
typeof define === 'function' && define.amd ? define(['exports', '@babel/runtime/helpers/defineProperty', 'core-js/modules/es.regexp.exec.js', 'core-js/modules/es.string.replace.js', 'core-js/modules/es.string.pad-start.js', 'core-js/modules/es.array.iterator.js', 'core-js/modules/web.dom-collections.iterator.js', 'core-js/modules/es.promise.js', 'core-js/modules/web.url.to-json.js', 'stream'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.jsonStreamStringify = {}, global._defineProperty, null, null, null, null, null, null, null, global.stream));
})(this, (function (exports, _defineProperty, es_regexp_exec_js, es_string_replace_js, es_string_padStart_js, es_array_iterator_js, web_domCollections_iterator_js, es_promise_js, web_url_toJson_js, stream) { 'use strict';
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var _classCallCheck__default = /*#__PURE__*/_interopDefaultLegacy(_classCallCheck);
var _createClass__default = /*#__PURE__*/_interopDefaultLegacy(_createClass);
var _assertThisInitialized__default = /*#__PURE__*/_interopDefaultLegacy(_assertThisInitialized);
var _inherits__default = /*#__PURE__*/_interopDefaultLegacy(_inherits);
var _possibleConstructorReturn__default = /*#__PURE__*/_interopDefaultLegacy(_possibleConstructorReturn);
var _getPrototypeOf__default = /*#__PURE__*/_interopDefaultLegacy(_getPrototypeOf);
var _defineProperty__default = /*#__PURE__*/_interopDefaultLegacy(_defineProperty);
var _typeof__default = /*#__PURE__*/_interopDefaultLegacy(_typeof);
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf__default["default"](Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf__default["default"](this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn__default["default"](this, result); }; }
var _global, _global$JSON;
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
const rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var rxEscapable = /[\\"\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; // table of character substitutions
var meta = {
const meta = {
'\b': '\\b',

@@ -54,7 +45,7 @@ '\t': '\\t',

if (Array.isArray(value)) return Types.Array;
if (_typeof__default["default"](value) === 'object' || value instanceof Object) return Types.Object;
if (typeof value === 'object' || value instanceof Object) return Types.Object;
return Types.Primitive;
}
var stackItemOpen = [];
const stackItemOpen = [];
stackItemOpen[Types.Array] = '[';

@@ -64,3 +55,3 @@ stackItemOpen[Types.Object] = '{';

stackItemOpen[Types.ReadableObject] = '[';
var stackItemEnd = [];
const stackItemEnd = [];
stackItemEnd[Types.Array] = ']';

@@ -70,8 +61,2 @@ stackItemEnd[Types.Object] = '}';

stackItemEnd[Types.ReadableObject] = ']';
var processFunctionLookupTable = ['processArray', 'processObject', 'processReadableString', 'processReadableObject', 'processPrimitive', 'processPromise'];
/*
for (const [key, val] of Object.entries(Types)) {
if (typeof val === 'number') processFunctionLookupTable[val] = `process${key}`;
}
*/

@@ -85,24 +70,87 @@ function escapeString(string) {

// sequences.
return string.replace(rxEscapable, function (a) {
var c = meta[a];
return typeof c === 'string' ? c : "\\u".concat(a.charCodeAt(0).toString(16).padStart(4, '0'));
return string.replace(rxEscapable, a => {
const c = meta[a];
return typeof c === 'string' ? c : `\\u${a.charCodeAt(0).toString(16).padStart(4, '0')}`;
});
}
let primitiveToJSON;
if (((_global = global) === null || _global === void 0 ? void 0 : (_global$JSON = _global.JSON) === null || _global$JSON === void 0 ? void 0 : _global$JSON.stringify) instanceof Function) {
let canSerializeBigInt = true;
try {
if (JSON.stringify(global.BigInt ? global.BigInt('123') : '') !== '123') throw new Error();
} catch (err) {
canSerializeBigInt = false;
}
if (canSerializeBigInt) {
primitiveToJSON = JSON.parse;
} else {
// eslint-disable-next-line no-confusing-arrow
primitiveToJSON = value => typeof value === 'bigint' ? String(value) : JSON.stringify(value);
}
} else {
primitiveToJSON = value => {
switch (typeof value) {
case 'string':
return `"${escapeString(value)}"`;
case 'number':
return Number.isFinite(value) ? String(value) : 'null';
case 'bigint':
return String(value);
case 'boolean':
return value ? 'true' : 'false';
case 'object':
if (!value) {
return 'null';
}
// eslint-disable-next-line no-fallthrough
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error(`Not a primitive "${typeof value}".`), {
value
});
}
};
}
/*
function quoteString(string: string) {
return primitiveToJSON(String(string));
}
*/
const cache = new Map();
function quoteString(string) {
return "\"".concat(escapeString(string), "\"");
const useCache = string.length < 10000; // eslint-disable-next-line no-lonely-if
if (useCache && cache.has(string)) {
return cache.get(string);
}
const str = primitiveToJSON(String(string));
if (useCache) cache.set(string, str);
return str;
}
function readAsPromised(stream, size) {
var value = stream.read(size);
const value = stream.read(size);
if (value === null) {
return new Promise(function (resolve, reject) {
var endListener = function endListener() {
return resolve(null);
};
return new Promise((resolve, reject) => {
const endListener = () => resolve(null);
stream.once('end', endListener);
stream.once('error', reject);
stream.once('readable', function () {
stream.once('readable', () => {
stream.removeListener('end', endListener);

@@ -118,438 +166,447 @@ stream.removeListener('error', reject);

function recursiveResolve(promise) {
return promise.then(function (res) {
return getType(res) === Types.Promise ? recursiveResolve(res) : res;
});
}
var ReadState;
var JsonStreamStringify = /*#__PURE__*/function (_Readable) {
_inherits__default["default"](JsonStreamStringify, _Readable);
(function (ReadState) {
ReadState[ReadState["NotReading"] = 0] = "NotReading";
ReadState[ReadState["Reading"] = 1] = "Reading";
ReadState[ReadState["ReadMore"] = 2] = "ReadMore";
ReadState[ReadState["Consumed"] = 3] = "Consumed";
})(ReadState || (ReadState = {}));
var _super = _createSuper(JsonStreamStringify);
class JsonStreamStringify extends stream.Readable {
constructor(input, replacer, spaces, cycle = false, bufferSize = 512) {
super({
encoding: 'utf8'
});
function JsonStreamStringify(value, replacer, spaces) {
var _this;
_defineProperty__default["default"](this, "cycle", void 0);
var cycle = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false;
_defineProperty__default["default"](this, "bufferSize", void 0);
_classCallCheck__default["default"](this, JsonStreamStringify);
_defineProperty__default["default"](this, "item", void 0);
_this = _super.call(this, {
encoding: 'utf8'
});
_defineProperty__default["default"](this, "indent", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "cycle", void 0);
_defineProperty__default["default"](this, "root", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "visited", void 0);
_defineProperty__default["default"](this, "include", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "stack", []);
_defineProperty__default["default"](this, "replacer", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "replacerFunction", void 0);
_defineProperty__default["default"](this, "visited", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "replacerArray", void 0);
_defineProperty__default["default"](this, "objectItem", void 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "gap", void 0);
_defineProperty__default["default"](this, "prePush", undefined);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "depth", 0);
_defineProperty__default["default"](this, "buffer", '');
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "error", void 0);
_defineProperty__default["default"](this, "bufferLength", 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "pushCalled", false);
_defineProperty__default["default"](this, "pushCalled", false);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "end", false);
_defineProperty__default["default"](this, "readSize", 0);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "isReading", false);
_defineProperty__default["default"](this, "reading", false);
_defineProperty__default["default"](_assertThisInitialized__default["default"](_this), "readMore", false);
_defineProperty__default["default"](this, "readMore", false);
_this.cycle = cycle;
_defineProperty__default["default"](this, "readState", ReadState.NotReading);
var spaceType = _typeof__default["default"](spaces);
this.cycle = cycle;
this.bufferSize = bufferSize;
const spaceType = typeof spaces;
if (spaceType === 'string' || spaceType === 'number') {
_this.gap = Number.isFinite(spaces) ? ' '.repeat(spaces) : spaces;
if (spaceType === 'number') {
this.indent = ' '.repeat(spaces);
} else if (spaceType === 'string') {
this.indent = spaces;
}
Object.assign(_assertThisInitialized__default["default"](_this), {
visited: cycle ? new WeakMap() : new WeakSet(),
replacerFunction: replacer instanceof Function && replacer,
replacerArray: Array.isArray(replacer) && replacer
});
if (replacer instanceof Function) _this.replacerFunction = replacer;
if (Array.isArray(replacer)) _this.replacerArray = replacer;
const replacerType = typeof replacer;
_this.addToStack(value);
if (replacerType === 'object') {
this.include = replacer;
} else if (replacerType === 'function') {
this.replacer = replacer;
}
return _this;
this.visited = cycle ? new WeakMap() : [];
this.root = {
value: {
'': input
},
depth: 0,
indent: '',
path: []
};
this.setItem(input, this.root, '');
}
_createClass__default["default"](JsonStreamStringify, [{
key: "cycler",
value: function cycler(key, value) {
var existingPath = this.visited.get(value);
setItem(value, parent, key = '') {
// call toJSON where applicable
if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
value = value.toJSON(key);
} // use replacer if applicable
if (existingPath) {
return {
$ref: existingPath
};
}
var path = this.path();
if (key !== undefined) path.push(key);
path = path.map(function (v) {
return "[".concat(Number.isInteger(v) ? v : quoteString(v), "]");
});
this.visited.set(value, path.length ? "$".concat(path.join('')) : '$');
return value;
}
}, {
key: "addToStack",
value: function addToStack(value, key, index, parent) {
var _this2 = this;
if (this.replacer) {
value = this.replacer.call(parent.value, key, value);
} // coerece functions and symbols into undefined
var realValue = value;
if (this.replacerFunction) {
realValue = this.replacerFunction(key || index, realValue, this);
} // ORDER?
if (value instanceof Function || typeof value === 'symbol') {
value = undefined;
}
const type = getType(value);
let path; // check for circular structure
if (realValue && realValue.toJSON instanceof Function) {
realValue = realValue.toJSON();
if (!this.cycle && type !== Types.Primitive) {
if (this.visited.some(v => v === value)) {
this.destroy(Object.assign(new Error('Converting circular structure to JSON'), {
value,
key
}));
return;
}
if (realValue instanceof Function || _typeof__default["default"](value) === 'symbol') {
realValue = undefined;
this.visited.push(value);
} else if (this.cycle && type !== Types.Primitive) {
path = this.visited.get(value);
if (path) {
this._push(`{"$ref":"$${path.map(v => `[${Number.isInteger(v) ? v : escapeString(quoteString(v))}]`).join('')}"}`);
this.item = parent;
return;
}
if (key !== undefined && this.replacerArray) {
if (!this.replacerArray.includes(key)) {
realValue = undefined;
}
path = parent === this.root ? [] : parent.path.concat(key);
this.visited.set(value, path);
}
if (type === Types.Object) {
this.setObjectItem(value, parent);
} else if (type === Types.Array) {
this.setArrayItem(value, parent);
} else if (type === Types.Primitive) {
if (parent !== this.root && typeof key === 'string') {
// (<any>parent).write(key, primitiveToJSON(value));
if (value === undefined) ; else {
this._push(primitiveToJSON(value));
} // undefined values in objects should be rejected
} else if (value === undefined && typeof key === 'number') {
// undefined values in array should be null
this._push('null');
} else if (value === undefined) ; else {
this._push(primitiveToJSON(value));
}
var type = getType(realValue);
this.item = parent;
return;
} else if (type === Types.Promise) {
this.setPromiseItem(value, parent, key);
} else if (type === Types.ReadableString) {
this.setReadableStringItem(value, parent);
} else if (type === Types.ReadableObject) {
this.setReadableObjectItem(value, parent);
}
if ((parent && parent.type === Types.Array ? true : realValue !== undefined) && type !== Types.Promise) {
if (parent && !parent.first) {
this._push(',');
} // eslint-disable-next-line no-param-reassign
this.item.value = value;
this.item.depth = parent.depth + 1;
if (this.indent) this.item.indent = this.indent.repeat(this.item.depth);
this.item.path = path;
}
setReadableStringItem(input, parent) {
var _input$_readableState, _input$_readableState2;
if (parent) parent.first = false;
}
if (input.readableEnded || (_input$_readableState = input._readableState) !== null && _input$_readableState !== void 0 && _input$_readableState.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState2 = input._readableState) !== null && _input$_readableState2 !== void 0 && _input$_readableState2.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue !== undefined && type !== Types.Promise && key !== undefined) {
if (this.gap) {
this._push("\n".concat(this.gap.repeat(this.depth), "\"").concat(escapeString(key), "\": "));
} else {
this._push("\"".concat(escapeString(key), "\":"));
}
}
const that = this;
if (type !== Types.Primitive) {
if (this.cycle) {
// run cycler
realValue = this.cycler(key || index, realValue);
type = getType(realValue);
} else {
// check for circular structure
if (this.visited.has(realValue)) {
throw Object.assign(new Error('Converting circular structure to JSON'), {
realValue: realValue,
key: key || index
});
}
this._push('"');
this.visited.add(realValue);
input.once('end', () => {
this._push('"');
this.item = parent;
this.emit('readable');
});
this.item = {
type: 'readable string',
async read(size) {
try {
const data = await readAsPromised(input, size);
if (data) that._push(escapeString(data.toString()));
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
if (!key && index > -1 && this.depth && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
var open = stackItemOpen[type];
if (open) this._push(open);
var obj = {
key: key,
index: index,
type: type,
parent: parent,
value: realValue,
first: true
};
};
}
if (type === Types.Object) {
this.depth += 1;
obj.unread = Object.keys(realValue);
obj.isEmpty = !obj.unread.length;
} else if (type === Types.Array) {
this.depth += 1;
obj.unread = realValue.length;
obj.arrayLength = obj.unread;
obj.isEmpty = !obj.unread;
} else if (type === Types.ReadableString || type === Types.ReadableObject) {
var _realValue$_readableS, _realValue$_readableS2;
setReadableObjectItem(input, parent) {
var _input$_readableState3, _input$_readableState4;
this.depth += 1;
if (input.readableEnded || (_input$_readableState3 = input._readableState) !== null && _input$_readableState3 !== void 0 && _input$_readableState3.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), input, parent.path);
} else if (input.readableFlowing || (_input$_readableState4 = input._readableState) !== null && _input$_readableState4 !== void 0 && _input$_readableState4.flowing) {
input.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), input, parent.path);
}
if (realValue.readableEnded || (_realValue$_readableS = realValue._readableState) !== null && _realValue$_readableS !== void 0 && _realValue$_readableS.endEmitted) {
this.emit('error', new Error('Readable Stream has ended before it was serialized. All stream data have been lost'), realValue, key || index);
} else if (realValue.readableFlowing || (_realValue$_readableS2 = realValue._readableState) !== null && _realValue$_readableS2 !== void 0 && _realValue$_readableS2.flowing) {
realValue.pause();
this.emit('error', new Error('Readable Stream is in flowing mode, data may have been lost. Trying to pause stream.'), realValue, key || index);
}
const that = this;
obj.readCount = 0;
realValue.once('end', function () {
obj.end = true;
this._push('[');
_this2.__read();
});
realValue.once('error', function (err) {
_this2.error = true;
let first = true;
let i = 0;
const item = {
type: 'readable object',
_this2.emit('error', err);
});
}
async read(size) {
try {
let out = '';
const data = await readAsPromised(input, size);
this.stack.unshift(obj);
return obj;
}
}, {
key: "removeFromStack",
value: function removeFromStack(item) {
var type = item.type;
var isObject = type === Types.Object || type === Types.Array || type === Types.ReadableString || type === Types.ReadableObject;
if (data === null) {
if (i && that.indent) {
out += `\n${parent.indent}`;
}
if (type !== Types.Primitive) {
if (!this.cycle) {
this.visited["delete"](item.value);
}
out += ']';
if (isObject) {
this.depth -= 1;
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (first) first = false;else out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(data, item, i);
i += 1;
} catch (err) {
that.emit('error', err);
that.destroy();
}
}
var end = stackItemEnd[type];
if (isObject && !item.isEmpty && this.gap) this._push("\n".concat(this.gap.repeat(this.depth)));
if (end) this._push(end);
var stackIndex = this.stack.indexOf(item);
this.stack.splice(stackIndex, 1);
} // tslint:disable-next-line:function-name
};
this.item = item;
}
}, {
key: "_push",
value: function _push(data) {
this.pushCalled = true;
this.push(data);
}
}, {
key: "processReadableObject",
value: function processReadableObject(current, size) {
var _this3 = this;
if (current.end) {
this.removeFromStack(current);
return undefined;
setPromiseItem(input, parent, key) {
const that = this;
let read = false;
this.item = {
async read() {
if (read) return;
read = true;
input.then(v => that.setItem(v, parent, key), err => {
that.emit('error', err);
that.destroy();
});
}
return readAsPromised(current.value, size).then(function (value) {
if (value !== null) {
if (!current.first) {
_this3._push(',');
} // eslint-disable-next-line no-param-reassign
};
}
setArrayItem(input, parent) {
// const entries = input.slice().reverse();
let i = 0;
const len = input.length;
let first = true;
const that = this;
const item = {
read() {
let out = '';
let wasFirst = false;
current.first = false;
if (first) {
first = false;
wasFirst = true;
_this3.addToStack(value, undefined, current.readCount); // eslint-disable-next-line no-param-reassign
if (!len) {
that._push('[]');
that.item = parent;
return;
}
current.readCount += 1;
out += '[';
}
});
}
}, {
key: "processObject",
value: function processObject(current) {
// when no keys left, remove obj from stack
if (!current.unread.length) {
this.removeFromStack(current);
return;
}
var key = current.unread.shift();
var value = current.value[key];
this.addToStack(value, key, undefined, current);
}
}, {
key: "processArray",
value: function processArray(current) {
var key = current.unread;
const entry = input[i];
if (!key) {
this.removeFromStack(current);
return;
if (i === len) {
if (that.indent) out += `\n${parent.indent}`;
out += ']';
that._push(out);
that.item = parent;
that.unvisit(input);
return;
}
if (!wasFirst) out += ',';
if (that.indent) out += `\n${item.indent}`;
that._push(out);
that.setItem(entry, item, i);
i += 1;
}
var index = current.arrayLength - key;
var value = current.value[index]; // eslint-disable-next-line no-param-reassign
};
this.item = item;
}
current.unread -= 1;
this.addToStack(value, undefined, index, current);
}
}, {
key: "processPrimitive",
value: function processPrimitive(current) {
if (current.value !== undefined) {
var type = _typeof__default["default"](current.value);
unvisit(item) {
if (this.cycle) return;
var value;
const _i = this.visited.indexOf(item);
switch (type) {
case 'string':
value = quoteString(current.value);
break;
if (_i > -1) this.visited.splice(_i, 1);
}
case 'number':
value = Number.isFinite(current.value) ? String(current.value) : 'null';
break;
setObjectItem(input, parent = undefined) {
const keys = Object.keys(input);
let i = 0;
const len = keys.length;
let first = true;
const that = this;
const {
include
} = this;
let hasItems = false;
let key;
const item = {
read() {
var _include$indexOf;
case 'bigint':
value = String(current.value);
break;
if (i === 0) that._push('{');
case 'boolean':
value = String(current.value);
break;
if (i === len) {
that.objectItem = undefined;
case 'object':
if (!current.value) {
value = 'null';
break;
}
if (!hasItems) {
that._push('}');
} else {
that._push(`${that.indent ? `\n${parent.indent}` : ''}}`);
}
// eslint-disable-next-line no-fallthrough
that.item = parent;
that.unvisit(input);
return;
}
default:
// This should never happen, I can't imagine a situation where this executes.
// If you find a way, please open a ticket or PR
throw Object.assign(new Error("Unknown type \"".concat(type, "\". Please file an issue!")), {
value: current.value
});
key = keys[i];
if ((include === null || include === void 0 ? void 0 : (_include$indexOf = include.indexOf) === null || _include$indexOf === void 0 ? void 0 : _include$indexOf.call(include, key)) === -1) {
// replacer array excludes this key
i += 1;
return;
}
this._push(value);
} else if (this.stack[1] && (this.stack[1].type === Types.Array || this.stack[1].type === Types.ReadableObject)) {
this._push('null');
} else {
// eslint-disable-next-line no-param-reassign
current.addSeparatorAfterEnd = false;
that.objectItem = item;
i += 1;
that.setItem(input[key], item, key);
},
write() {
const out = `${hasItems && !first ? ',' : ''}${item.indent ? `\n${item.indent}` : ''}${quoteString(key)}:${that.indent ? ' ' : ''}`;
first = false;
hasItems = true;
that.objectItem = undefined;
return out;
}
this.removeFromStack(current);
}
}, {
key: "processReadableString",
value: function processReadableString(current, size) {
var _this4 = this;
};
this.item = item;
}
if (current.end) {
this.removeFromStack(current);
return undefined;
}
_push(data) {
this.buffer += (this.objectItem ? this.objectItem.write() : '') + data;
this.prePush = undefined;
return readAsPromised(current.value, size).then(function (value) {
if (value) _this4._push(escapeString(value.toString()));
});
if (this.buffer.length >= this.bufferSize) {
this.pushCalled = !this.push(this.buffer);
this.buffer = '';
this.bufferLength = 0;
return false;
}
}, {
key: "processPromise",
value: function processPromise(current) {
var _this5 = this;
return recursiveResolve(current.value).then(function (value) {
_this5.removeFromStack(current);
return true;
}
_this5.addToStack(value, current.key, current.index, current.parent);
});
async _read(size) {
if (this.readState !== ReadState.NotReading) {
this.readState = ReadState.ReadMore;
return;
}
}, {
key: "processStackTopItem",
value: function processStackTopItem(size) {
var _this6 = this;
var current = this.stack[0];
if (!current || this.error) return Promise.resolve();
var out;
this.readState = ReadState.Reading;
this.pushCalled = false;
let p;
try {
out = this[processFunctionLookupTable[current.type]](current, size);
} catch (err) {
return Promise.reject(err);
}
while (!this.pushCalled && this.item !== this.root && !this.destroyed) {
p = this.item.read(size); // eslint-disable-next-line no-await-in-loop
return Promise.resolve(out).then(function () {
if (_this6.stack.length === 0) {
_this6.end = true;
if (p) await p;
}
_this6._push(null);
}
});
} // tslint:disable-next-line:function-name
if (this.item === this.root) {
if (this.buffer.length) this.push(this.buffer);
this.push(null);
this.readState = ReadState.Consumed;
}, {
key: "__read",
value: function __read(size) {
var _this7 = this;
this._destroy();
}
if (this.isReading || this.error) {
this.readMore = true;
return undefined;
}
if (this.readState === ReadState.ReadMore) {
this.readState = ReadState.NotReading;
this.isReading = true; // we must continue to read while push has not been called
this._read(size);
}
this.readMore = false;
return this.processStackTopItem(size).then(function () {
var readAgain = !_this7.end && !_this7.error && (_this7.readMore || !_this7.pushCalled);
this.readState = ReadState.NotReading;
}
if (readAgain) {
setImmediate(function () {
_this7.isReading = false;
_destroy() {
this.destroyed = true;
this.buffer = undefined;
this.visited = undefined;
this.item = undefined;
this.prePush = undefined;
}
_this7.__read();
});
} else {
_this7.isReading = false;
}
})["catch"](function (err) {
_this7.error = true;
destroy(error) {
var _super$destroy;
_this7.emit('error', err);
});
} // tslint:disable-next-line:function-name
if (error) this.emit('error', error);
(_super$destroy = super.destroy) === null || _super$destroy === void 0 ? void 0 : _super$destroy.call(this);
}, {
key: "_read",
value: function _read(size) {
this.pushCalled = false;
this._destroy();
this.__read(size);
}
}, {
key: "path",
value: function path() {
return this.stack.map(function (_ref) {
var key = _ref.key,
index = _ref.index;
return key || index;
}).filter(function (v) {
return v || v > -1;
}).reverse();
}
}]);
return this;
}
return JsonStreamStringify;
}(stream.Readable);
}

@@ -556,0 +613,0 @@ exports.JsonStreamStringify = JsonStreamStringify;

{
"name": "json-stream-stringify",
"description": "JSON.Stringify as a readable stream",
"version": "3.0.1",
"version": "3.1.0",
"license": "MIT",

@@ -65,3 +65,3 @@ "author": "Faleij <faleij@gmail.com> (https://github.com/faleij)",

"expect.js": "0.3.1",
"mocha": "10.0.0",
"mocha": "^10.2.0",
"nyc": "15.1.0",

@@ -75,4 +75,7 @@ "rollup": "2.77.0",

"volta": {
"node": "16.16.0"
"node": "18.16.0"
},
"engines": {
"node": ">=7.10.1"
},
"exports": {

@@ -79,0 +82,0 @@ ".": {

@@ -12,20 +12,8 @@ # JSON Stream Stringify

## Breaking Changes in v3
## Important and Breaking Changes in v3.1.0
- [Import formatting has changed](#usage)
- [CJS output added](#usage)
- Completely rewritten from scratch - again
- Buffer argument added (Stream will not output data untill buffer size is reached - improves speed)
- Dropped support for node <7.10.1 - async supporting environment now required
## Important and Breaking Changes in v2
- Completely rewritten from scratch
- 100% Code Coverage! 🎉
- Space argument finally implemented! 🎉
- ⚠️ Cycling is off by default
- ⚠️ JsonStreamStringify is now a constructor; use ``new`` operator
- Removed dependency on global JSON.stringify, Async/Await and Generators
- JsonStreamStringify is now compiled with babel to target ES5 (polyfills needed)
- Rejected promises and input stream errors are now handled and emitted as errors
- Added cyclic structure detection to prevent infinite recursion
- 🆕 Converted to Typescript
## Main Features

@@ -97,3 +85,3 @@

### `new JsonStreamStringify(value[, replacer[, spaces[, cycle]]])`
### `new JsonStreamStringify(value[, replacer[, spaces[, cycle[, bufferSize=512]]]])`

@@ -100,0 +88,0 @@ Streaming conversion of ``value`` to JSON string.

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc