This commit is contained in:
Tutur33
2023-11-24 22:35:41 +01:00
parent 3c0b507a93
commit 7644b2a0f7
45165 changed files with 4803356 additions and 3 deletions
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2013 James Halliday
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+17
View File
@@ -0,0 +1,17 @@
/*
* @poppinss/inspect
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
const PrettyPrintHtml = require('./src/PrettyPrintHtml');
module.exports = {
inspect: require('./src/inspect'),
string: {
html: (value) => new PrettyPrintHtml().print(value)
},
}
+66
View File
@@ -0,0 +1,66 @@
{
"name": "@poppinss/inspect",
"version": "1.0.1",
"description": "Stringify Javascript values to a string or pretty print HTML",
"main": "index.js",
"files": [
"index.js",
"src"
],
"author": ["virk", "@poppinss"],
"devDependencies": {
"@ljharb/eslint-config": "^16.0.0",
"core-js": "^2.5.7",
"endent": "^2.0.1",
"eslint": "^6.8.0",
"np": "^6.2.3",
"tape": "^5.0.0"
},
"scripts": {
"pretest": "npm run lint",
"lint": "eslint .",
"test": "npm run tests-only",
"pretests-only": "node test-core-js",
"tests-only": "tape test/*.js",
"posttest": "npx aud --production"
},
"testling": {
"files": [
"test/*.js",
"test/browser/*.js"
]
},
"repository": {
"type": "git",
"url": "git://github.com/thetutlage/object-inspect.git"
},
"homepage": "https://github.com/thetutlage/object-inspect",
"keywords": [
"inspect",
"util.inspect",
"object",
"stringify",
"pretty"
],
"funding": {
"url": "https://github.com/sponsors/ljharb"
},
"license": "MIT",
"browser": {
"./util.inspect.js": false
},
"greenkeeper": {
"ignore": [
"nyc",
"core-js"
]
},
"bugs": {
"url": "https://github.com/thetutlage/object-inspect/issues"
},
"directories": {
"example": "example",
"test": "test"
},
"dependencies": {}
}
+55
View File
@@ -0,0 +1,55 @@
# object-inspect
> Fork of [object-inspect](https://github.com/inspect-js/object-inspect) to add support for newlines, indentation and slight modifications to the output.
Convert Javascript datatypes to their string representation. Handles every in-built data type including.
- Objects
- Arrays
- BigInt
- Symbols
- Map/WeakMap
- Set/WeakSet
- Date
- RegExp
- Object literals
- Classes
- String
- Boolean
- Number
- Null
- Undefined
- Error
- Buffer
> **This module will be re-written from scratch soon. So please, do not send any PR's for improvements. However, feel free to report issues and they will be picked up during re-write**.
## Installation
Install the package from npm registry as follows
```sh
npm install @poppinss/object-inspect
```
## Usage
```js
const { inspect } = require('@poppinss/inspect')
inspect({ foo: 'bar', bar: 'baz' })
```
## Pretty print to HTML
```js
const { stringify } = require('@poppinss/inspect')
stringify.html({ foo: 'bar', bar: 'baz' })
```
## Credits
To the original [object-inspect](https://github.com/inspect-js/object-inspect) package. 90% of the code is still the same, we have just made opinionated changes to suit it better to our needs.
I didn't created a PR for the original package, since the modifications are very specific to serve our use case.
# License
MIT
+162
View File
@@ -0,0 +1,162 @@
/*
* edge
*
* (c) Harminder Virk <virk@adonisjs.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* Pretty prints an Object with colors and formatting. Code is copied from
* https://www.npmjs.com/package/pretty-print-json package and then tweaked
* to fit our use cases.
*/
const inspect = require('./inspect');
const styles = {
string: 'color: rgb(173, 219, 103);',
key: 'color: rgb(127, 219, 202);',
boolean: 'color: rgb(247, 140, 108);',
number: 'color: rgb(199, 146, 234);',
bigInt: 'color: rgb(199, 146, 234);',
set: 'color: rgb(255, 203, 139);',
map: 'color: rgb(255, 203, 139);',
symbol: 'color: rgb(255, 203, 139);',
null: 'color: rgb(255, 203, 139);',
function: 'color: rgb(255, 203, 139);',
regex: 'color: rgb(255, 86, 86);',
error: 'color: rgb(255, 86, 86);',
weakMap: 'color: #f8f8f8;',
weakSet: 'color: #f8f8f8;',
circular: 'color: #f8f8f8;',
'undefined': 'color: #999;',
pre: `
padding: 30px 25px;
background-color: rgb(6, 21, 38);
color: rgb(214, 222, 235);
border-radius: 6px;
font-size: 14px;
overflow: auto;
white-space: pre;
word-spacing: normal;
word-break: normal;
word-wrap: normal;
tab-size: 4;
line-height: 1.4;
text-align: left;
`,
code: `font-family: JetBrains Mono, Menlo, Monaco, monospace;`
}
module.exports = class PrettyPrint {
/**
* Return a boolean telling if the variable name is a
* standard global
*/
isStandardGlobal (name) {
return ['inspect', 'truncate', 'excerpt', 'safe'].includes(name);
}
/**
* Encode html
*/
encodeHTML (value) {
return value
.replace(/&/g, '&amp;')
.replace(/\\"/g, '&bsol;&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
}
/**
* Build HTML value of the key
*/
buildValueHtml (value) {
let type = 'number';
if (value.startsWith('"[Function')) {
type = 'function';
value = value.substring(1, value.length - 1);
} else if (value === '"undefined"') {
type = 'undefined';
value = 'undefined';
} else if (value === '"[Circular]"') {
type = 'circular';
value = '[Circular]';
} else if (value === '"WeakSet {?}"') {
type = 'weakSet';
value = 'WeakSet {?}';
} else if (value === '"WeakMap {?}"') {
type = 'weakMap';
value = 'WeakMap {?}';
} else if (value.startsWith('"Symbol')) {
type = 'symbol';
value = value.substring(1, value.length - 1);
} else if (value.startsWith('"Error')) {
type = 'error';
value = value.substring(1, value.length - 1).replace('Error ', '');
} else if (value.startsWith('"RegExp')) {
type = 'regex';
value = value.substring(1, value.length - 1).replace('RegExp ', '');
} else if (value.endsWith('n"')) {
type = 'bigInt';
value = value.substring(1, value.length - 1);
} else if (value.startsWith('"Set(')) {
type = 'set';
const parts = value.split(') [')
if (parts.length === 2) {
const prefix = `<span style="${styles.undefined}">${parts[0].substr(1)})</span>`;
const values = `<span style="${styles.set}">[${parts[1].slice(0, -1)}</span>`;
return `${prefix} ${values}`;
}
} else if (value.startsWith('"Map(')) {
type = 'set';
const parts = value.split(') [')
if (parts.length === 2) {
const prefix = `<span style="${styles.undefined}">${parts[0].substr(1)})</span>`;
const values = `<span style="${styles.map}">[${parts[1].slice(0, -1)}</span>`;
return `${prefix} ${values}`;
}
} else if (value === '"<empty item>"') {
type = 'undefined';
value = '<empty item>';
} else if (/^"/.test(value)) {
type = 'string';
value = value.substring(1, value.length - 1);
} else if (['true', 'false'].includes(value)) {
type = 'boolean';
} else if (value === 'null') {
type = 'null';
}
return `<span style="${styles[type]}">${this.encodeHTML(value)}</span>`;
}
/**
* Build individual lines inside JSON
*/
replacer (_, p1, p2, p3, p4) {
const part = { indent: p1, key: p2, value: p3, end: p4 };
const findNameRegex = /(.*)(): /;
const indentHtml = part.indent || '';
const keyName = part.key && part.key.replace(findNameRegex, '$1$2');
const keyHtml = part.key ? `<span style="${styles.key}">${keyName}</span>: ` : '';
const valueHtml = part.value ? this.buildValueHtml(part.value) : '';
let endHtml = part.end || '';
return indentHtml + keyHtml + valueHtml + endHtml;
}
processJson (value) {
const jsonLineRegex = /^( *)("[^"]+": )?("[^"].*"|[\w.+-]*)?([{}[\],]*)?$/mg;
return value.replace(jsonLineRegex, this.replacer.bind(this));
}
/**
* Pretty print by converting the value to JSON string first
*/
print (value) {
const json = inspect(value);
return `<pre style="${styles.pre}"><code style="${styles.code}">${this.processJson(json)}</code></pre>`;
}
}
+433
View File
@@ -0,0 +1,433 @@
var hasMap = typeof Map === 'function' && Map.prototype;
var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null;
var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null;
var mapForEach = hasMap && Map.prototype.forEach;
var hasSet = typeof Set === 'function' && Set.prototype;
var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null;
var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null;
var setForEach = hasSet && Set.prototype.forEach;
var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype;
var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null;
var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype;
var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null;
var booleanValueOf = Boolean.prototype.valueOf;
var objectToString = Object.prototype.toString;
var match = String.prototype.match;
var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null;
function lowbyte(c) {
var n = c.charCodeAt(0);
var x = {
8: 'b',
9: 't',
10: 'n',
12: 'f',
13: 'r'
}[n];
if (x) {
return '\\' + x;
}
return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16);
}
function toStr(obj) {
return objectToString.call(obj);
}
function isSymbol(obj) {
return toStr(obj) === '[object Symbol]';
}
function isArray(obj) {
return toStr(obj) === '[object Array]';
}
function isDate(obj) {
return toStr(obj) === '[object Date]';
}
function isRegExp(obj) {
return toStr(obj) === '[object RegExp]';
}
function isError(obj) {
return toStr(obj) === '[object Error]';
}
function isString(obj) {
return toStr(obj) === '[object String]';
}
function isNumber(obj) {
return toStr(obj) === '[object Number]';
}
function isBigInt(obj) {
return toStr(obj) === '[object BigInt]';
}
function isBoolean(obj) {
return toStr(obj) === '[object Boolean]';
}
function isMap(x) {
if (!mapSize || !x || typeof x !== 'object') {
return false;
}
try {
mapSize.call(x);
try {
setSize.call(x);
} catch (s) {
return true;
}
return x instanceof Map; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakMap(x) {
if (!weakMapHas || !x || typeof x !== 'object') {
return false;
}
try {
weakMapHas.call(x, weakMapHas);
try {
weakSetHas.call(x, weakSetHas);
} catch (s) {
return true;
}
return x instanceof WeakMap; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isSet(x) {
if (!setSize || !x || typeof x !== 'object') {
return false;
}
try {
setSize.call(x);
try {
mapSize.call(x);
} catch (m) {
return true;
}
return x instanceof Set; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isWeakSet(x) {
if (!weakSetHas || !x || typeof x !== 'object') {
return false;
}
try {
weakSetHas.call(x, weakSetHas);
try {
weakMapHas.call(x, weakMapHas);
} catch (s) {
return true;
}
return x instanceof WeakSet; // core-js workaround, pre-v2.5.0
} catch (e) {}
return false;
}
function isElement(x) {
if (!x || typeof x !== 'object') {
return false;
}
if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) {
return true;
}
return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function';
}
function wrapQuotes(s, defaultStyle, opts) {
var quoteChar = (opts.quoteStyle || defaultStyle) === 'double' ? '"' : "'";
return quoteChar + s + quoteChar;
}
function quote(s) {
return String(s).replace(/"/g, '&quot;');
}
var hasOwn = Object.prototype.hasOwnProperty || function (key) {
return key in this;
};
function has(obj, key) {
return hasOwn.call(obj, key);
}
function nameOf(f) {
if (f.name) {
return f.name;
}
var m = match.call(f, /^function\s*([\w$]+)/);
if (m) {
return m[1];
}
return null;
}
function indexOf(xs, x) {
if (xs.indexOf) {
return xs.indexOf(x);
}
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) {
return i;
}
}
return -1;
}
function inspectString(str, opts) {
// eslint-disable-next-line no-control-regex
var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte);
return wrapQuotes(s, 'single', opts);
}
function getSpace(indentation) {
if (!indentation) {
return '';
}
let spaces = '';
for (let i = 0; i < indentation; i++) {
spaces += ' ';
}
return spaces;
}
function getArrayIndentation(indentation, inNewLine) {
if (!inNewLine) {
return {
children: 1,
end: 0,
start: 0
};
}
return {
children: indentation + 2,
end: indentation,
start: indentation + 2
};
}
function markBoxed(str) {
return `"Object(${str})"`;
}
function weakCollectionOf(type) {
return `"${type} {?}"`;
}
function collectionOf(type, size, entries) {
return `"${type}(${size}) [${entries.join(', ')}]"`;
}
function arrObjKeys(obj, inspect, indentation, inNewLine) {
var isArr = isArray(obj);
var xs = [];
if (isArr) {
xs.length = obj.length;
for (var i = 0; i < obj.length; i++) {
xs[i] = has(obj, i) ? inspect(obj[i], obj, undefined, indentation, inNewLine) : '"<empty item>"';
}
}
for (var key in obj) { // eslint-disable-line no-restricted-syntax
if (!has(obj, key)) {
continue; // eslint-disable-line no-restricted-syntax, no-continue
}
if (isArr && String(Number(key)) === key && key < obj.length) {
continue; // eslint-disable-line no-restricted-syntax, no-continue
}
if ((/[^\w$]/).test(key)) {
xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj, undefined, indentation, inNewLine));
} else {
xs.push('"' + key + '": ' + inspect(obj[key], obj, undefined, indentation, inNewLine));
}
}
return xs;
}
module.exports = function inspect_(obj, options, depth, seen, indentation, inNewLine) {
var opts = options || {};
indentation = indentation || 0;
inNewLine = inNewLine === undefined ? true : inNewLine;
var newLine = inNewLine ? '\n' : '';
if (has(opts, 'quoteStyle') && (opts.quoteStyle !== 'single' && opts.quoteStyle !== 'double')) {
throw new TypeError('option "quoteStyle" must be "single" or "double"');
}
function inspect(value, from, options, indentation, inNewLine) {
if (from) {
seen = seen.slice();
seen.push(from);
}
return inspect_(value, options || opts, depth + 1, seen, indentation, inNewLine);
}
if (typeof obj === 'undefined') {
return '"undefined"';
}
if (obj === null) {
return 'null';
}
if (typeof obj === 'boolean') {
return obj ? 'true' : 'false';
}
if (typeof obj === 'string') {
return opts.noWrap ? inspectString(obj, opts) : `"${inspectString(obj, opts)}"`;
}
if (typeof obj === 'number') {
if (obj === 0) {
return Infinity / obj > 0 ? '0' : '-0';
}
return String(obj);
}
if (typeof obj === 'bigint') {
return opts.noWrap ? String(obj) : `"${String(obj)}n"`
}
var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth;
if (typeof depth === 'undefined') {
depth = 0;
}
if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') {
return opts.noWrap ? '[Object]' : '"[Object]"';
}
if (typeof seen === 'undefined') {
seen = [];
} else if (indexOf(seen, obj) >= 0) {
return opts.noWrap ? '[Circular]' : '"[Circular]"';
}
if (typeof obj === 'function') {
var name = nameOf(obj);
return '"[Function' + (name ? ': ' + name : '') + ']"';
}
if (isSymbol(obj)) {
var symString = Symbol.prototype.toString.call(obj);
return typeof obj === 'object' ? markBoxed(symString) : `"${symString}"`;
}
if (isElement(obj)) {
var s = '<' + String(obj.nodeName).toLowerCase();
var attrs = obj.attributes || [];
for (var i = 0; i < attrs.length; i++) {
s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts);
}
s += '>';
if (obj.childNodes && obj.childNodes.length) {
s += '...';
}
s += '</' + String(obj.nodeName).toLowerCase() + '>';
return opts.noWrap ? s : `"${s}"`;
}
if (isArray(obj)) {
if (obj.length === 0) {
return '[]';
}
const { children, end, start } = getArrayIndentation(indentation, inNewLine);
const val = arrObjKeys(obj, inspect, children || indentation, inNewLine).join(',' + newLine + getSpace(children));
return '[' + newLine + getSpace(start) + val + newLine + getSpace(end) + ']';
}
if (isError(obj)) {
const { children, end, start } = getArrayIndentation(indentation, inNewLine);
var parts = arrObjKeys(obj, inspect, children, inNewLine);
if (parts.length === 0) {
return '"Error [' + String(obj) + ']"';
}
const val = parts.join(',' + newLine + getSpace(children));
return '"Error [' + String(obj) + ']"' + '{' + newLine + getSpace(start) + val + newLine + getSpace(end) + '}';
}
if (isMap(obj)) {
var mapParts = [];
const options = { quoteStyle: 'single', noWrap: true };
mapForEach.call(obj, function (value, key) {
mapParts.push(
inspect(key, obj, options, indentation, newLine) + ' => ' + inspect(value, obj, options, indentation, newLine)
);
});
return collectionOf('Map', mapSize.call(obj), mapParts);
}
if (isSet(obj)) {
var setParts = [];
setForEach.call(obj, function (value) {
setParts.push(inspect(value, obj, undefined, indentation, newLine));
});
return collectionOf('Set', setSize.call(obj), setParts);
}
if (isWeakMap(obj)) {
return weakCollectionOf('WeakMap');
}
if (isWeakSet(obj)) {
return weakCollectionOf('WeakSet');
}
if (isNumber(obj)) {
return markBoxed(inspect(Number(obj), undefined, undefined, 0, false));
}
if (isBigInt(obj)) {
return markBoxed(inspect(bigIntValueOf.call(obj), undefined, undefined, 0, false));
}
if (isBoolean(obj)) {
return markBoxed(booleanValueOf.call(obj));
}
if (isString(obj)) {
return markBoxed(inspect(String(obj), undefined, undefined, 0, false));
}
if (isRegExp(obj)) {
return `"RegExp ${String(obj)}"`;
}
if (Buffer.isBuffer(obj)) {
return `"${obj.inspect()}"`;
}
if (!isDate(obj)) {
const { children, end, start } = getArrayIndentation(indentation, inNewLine);
var xs = arrObjKeys(obj, inspect, children || indentation, newLine);
if (xs.length === 0) {
return '{}';
}
const value = xs.join(',' + newLine + getSpace(children));
return '{' + newLine + getSpace(start) + value + newLine + getSpace(end) + '}';
}
return opts.noWrap ? String(obj) : `"'${String(obj)}'"`;
};