Compile-3

This commit is contained in:
Ruslan Gladov 2024-06-15 15:02:48 +03:00
parent ff1f7fc631
commit 0e47b9b200
18201 changed files with 27 additions and 2920987 deletions

View file

@ -39,7 +39,9 @@ jobs:
docker-compose up -d
- name: Deploy contracts
run: npx hardhat ignition deploy /home/runner/work/go-ethereum/go-ethereum/test/Lock.js
run: |
cd ./hardhat
npx hardhat ignition deploy ./ignition/modules/Lock.js
- name: Build and push Docker image

View file

@ -1,24 +1,24 @@
#name: i386 linux tests
#
#on:
# push:
# branches: [ master ]
# pull_request:
# branches: [ master ]
# workflow_dispatch:
#
#jobs:
# build:
# runs-on: self-hosted
# steps:
# - uses: actions/checkout@v4
# - name: Set up Go
# uses: actions/setup-go@v5
# with:
# go-version: 1.21.4
# cache: false
# - name: Run tests
# run: go test -short ./...
# env:
# GOOS: linux
# GOARCH: 386
name: i386 linux tests
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
build:
runs-on: self-hosted
steps:
- uses: actions/checkout@v4
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version: 1.21.4
cache: false
- name: Run tests
run: go test -short ./...
env:
GOOS: linux
GOARCH: 386

View file

@ -1,13 +0,0 @@
# Sample Hardhat Project
This project demonstrates a basic Hardhat use case. It comes with a sample contract, a test for that contract, and a Hardhat Ignition module that deploys that contract.
Try running some of the following tasks:
```shell
npx hardhat help
npx hardhat test
REPORT_GAS=true npx hardhat test
npx hardhat node
npx hardhat ignition deploy ./ignition/modules/Lock.js
```

View file

@ -1,34 +0,0 @@
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.24;
// Uncomment this line to use console.log
// import "hardhat/console.sol";
contract Lock {
uint public unlockTime;
address payable public owner;
event Withdrawal(uint amount, uint when);
constructor(uint _unlockTime) payable {
require(
block.timestamp < _unlockTime,
"Unlock time should be in the future"
);
unlockTime = _unlockTime;
owner = payable(msg.sender);
}
function withdraw() public {
// Uncomment this line, and the import of "hardhat/console.sol", to print a log in your terminal
// console.log("Unlock time is %o and block timestamp is %o", unlockTime, block.timestamp);
require(block.timestamp >= unlockTime, "You can't withdraw yet");
require(msg.sender == owner, "You aren't the owner");
emit Withdrawal(address(this).balance, block.timestamp);
owner.transfer(address(this).balance);
}
}

View file

@ -1,15 +0,0 @@
const { buildModule } = require("@nomicfoundation/hardhat-ignition/modules");
const JAN_1ST_2030 = 1893456000;
const ONE_GWEI = 1_000_000_000n;
module.exports = buildModule("LockModule", (m) => {
const unlockTime = m.getParameter("unlockTime", JAN_1ST_2030);
const lockedAmount = m.getParameter("lockedAmount", ONE_GWEI);
const lock = m.contract("Lock", [unlockTime], {
value: lockedAmount,
});
return { lock };
});

10
node_modules/.bin/_mocha generated vendored
View file

@ -1,10 +0,0 @@
#!/usr/bin/env node
'use strict';
/**
* This file remains for backwards compatibility only.
* Don't put stuff in this file.
* @see module:lib/cli
*/
require('../lib/cli').main();

4
node_modules/.bin/acorn generated vendored
View file

@ -1,4 +0,0 @@
#!/usr/bin/env node
"use strict"
require("../dist/bin.js")

77
node_modules/.bin/escodegen generated vendored
View file

@ -1,77 +0,0 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true node:true */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
esprima = require('esprima'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: escodegen [options] file...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options,
esprimaOptions = {
raw: true,
tokens: true,
range: true,
comment: true
};
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'));
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8'),
syntax = esprima.parse(content, esprimaOptions);
if (options.comment) {
escodegen.attachComments(syntax, syntax.comments, syntax.tokens);
}
console.log(escodegen.generate(syntax, options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

64
node_modules/.bin/esgenerate generated vendored
View file

@ -1,64 +0,0 @@
#!/usr/bin/env node
/*
Copyright (C) 2012 Yusuke Suzuki <utatane.tea@gmail.com>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true node:true */
var fs = require('fs'),
path = require('path'),
root = path.join(path.dirname(fs.realpathSync(__filename)), '..'),
escodegen = require(root),
optionator = require('optionator')({
prepend: 'Usage: esgenerate [options] file.json ...',
options: [
{
option: 'config',
alias: 'c',
type: 'String',
description: 'configuration json for escodegen'
}
]
}),
args = optionator.parse(process.argv),
files = args._,
options;
if (files.length === 0) {
console.log(optionator.generateHelp());
process.exit(1);
}
if (args.config) {
try {
options = JSON.parse(fs.readFileSync(args.config, 'utf-8'))
} catch (err) {
console.error('Error parsing config: ', err);
}
}
files.forEach(function (filename) {
var content = fs.readFileSync(filename, 'utf-8');
console.log(escodegen.generate(JSON.parse(content), options));
});
/* vim: set sw=4 ts=4 et tw=80 : */

126
node_modules/.bin/esparse generated vendored
View file

@ -1,126 +0,0 @@
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true node:true rhino:true */
var fs, esprima, fname, content, options, syntax;
if (typeof require === 'function') {
fs = require('fs');
esprima = require('esprima');
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esparse.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esparse [options] file.js');
console.log();
console.log('Available options:');
console.log();
console.log(' --comment Gather all line and block comments in an array');
console.log(' --loc Include line-column location info for each syntax node');
console.log(' --range Include index-based range for each syntax node');
console.log(' --raw Display the raw value of literals');
console.log(' --tokens List all tokens in an array');
console.log(' --tolerant Tolerate errors on a best-effort basis (experimental)');
console.log(' -v, --version Shows program version');
console.log();
process.exit(1);
}
if (process.argv.length <= 2) {
showUsage();
}
options = {};
process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Parser (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry === '--comment') {
options.comment = true;
} else if (entry === '--loc') {
options.loc = true;
} else if (entry === '--range') {
options.range = true;
} else if (entry === '--raw') {
options.raw = true;
} else if (entry === '--tokens') {
options.tokens = true;
} else if (entry === '--tolerant') {
options.tolerant = true;
} else if (entry.slice(0, 2) === '--') {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
} else if (typeof fname === 'string') {
console.log('Error: more than one input file.');
process.exit(1);
} else {
fname = entry;
}
});
if (typeof fname !== 'string') {
console.log('Error: no input file.');
process.exit(1);
}
// Special handling for regular expression literal since we need to
// convert it to a string literal, otherwise it will be decoded
// as object "{}" and the regular expression would be lost.
function adjustRegexLiteral(key, value) {
if (key === 'value' && value instanceof RegExp) {
value = value.toString();
}
return value;
}
try {
content = fs.readFileSync(fname, 'utf-8');
syntax = esprima.parse(content, options);
console.log(JSON.stringify(syntax, adjustRegexLiteral, 4));
} catch (e) {
console.log('Error: ' + e.message);
process.exit(1);
}

199
node_modules/.bin/esvalidate generated vendored
View file

@ -1,199 +0,0 @@
#!/usr/bin/env node
/*
Copyright (c) jQuery Foundation, Inc. and Contributors, All Rights Reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*jslint sloppy:true plusplus:true node:true rhino:true */
/*global phantom:true */
var fs, system, esprima, options, fnames, count;
if (typeof esprima === 'undefined') {
// PhantomJS can only require() relative files
if (typeof phantom === 'object') {
fs = require('fs');
system = require('system');
esprima = require('./esprima');
} else if (typeof require === 'function') {
fs = require('fs');
esprima = require('esprima');
} else if (typeof load === 'function') {
try {
load('esprima.js');
} catch (e) {
load('../esprima.js');
}
}
}
// Shims to Node.js objects when running under PhantomJS 1.7+.
if (typeof phantom === 'object') {
fs.readFileSync = fs.read;
process = {
argv: [].slice.call(system.args),
exit: phantom.exit
};
process.argv.unshift('phantomjs');
}
// Shims to Node.js objects when running under Rhino.
if (typeof console === 'undefined' && typeof process === 'undefined') {
console = { log: print };
fs = { readFileSync: readFile };
process = { argv: arguments, exit: quit };
process.argv.unshift('esvalidate.js');
process.argv.unshift('rhino');
}
function showUsage() {
console.log('Usage:');
console.log(' esvalidate [options] file.js');
console.log();
console.log('Available options:');
console.log();
console.log(' --format=type Set the report format, plain (default) or junit');
console.log(' -v, --version Print program version');
console.log();
process.exit(1);
}
if (process.argv.length <= 2) {
showUsage();
}
options = {
format: 'plain'
};
fnames = [];
process.argv.splice(2).forEach(function (entry) {
if (entry === '-h' || entry === '--help') {
showUsage();
} else if (entry === '-v' || entry === '--version') {
console.log('ECMAScript Validator (using Esprima version', esprima.version, ')');
console.log();
process.exit(0);
} else if (entry.slice(0, 9) === '--format=') {
options.format = entry.slice(9);
if (options.format !== 'plain' && options.format !== 'junit') {
console.log('Error: unknown report format ' + options.format + '.');
process.exit(1);
}
} else if (entry.slice(0, 2) === '--') {
console.log('Error: unknown option ' + entry + '.');
process.exit(1);
} else {
fnames.push(entry);
}
});
if (fnames.length === 0) {
console.log('Error: no input file.');
process.exit(1);
}
if (options.format === 'junit') {
console.log('<?xml version="1.0" encoding="UTF-8"?>');
console.log('<testsuites>');
}
count = 0;
fnames.forEach(function (fname) {
var content, timestamp, syntax, name;
try {
content = fs.readFileSync(fname, 'utf-8');
if (content[0] === '#' && content[1] === '!') {
content = '//' + content.substr(2, content.length);
}
timestamp = Date.now();
syntax = esprima.parse(content, { tolerant: true });
if (options.format === 'junit') {
name = fname;
if (name.lastIndexOf('/') >= 0) {
name = name.slice(name.lastIndexOf('/') + 1);
}
console.log('<testsuite name="' + fname + '" errors="0" ' +
' failures="' + syntax.errors.length + '" ' +
' tests="' + syntax.errors.length + '" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) +
'">');
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
console.log(' <testcase name="Line ' + error.lineNumber + ': ' + msg + '" ' +
' time="0">');
console.log(' <error type="SyntaxError" message="' + error.message + '">' +
error.message + '(' + name + ':' + error.lineNumber + ')' +
'</error>');
console.log(' </testcase>');
});
console.log('</testsuite>');
} else if (options.format === 'plain') {
syntax.errors.forEach(function (error) {
var msg = error.message;
msg = msg.replace(/^Line\ [0-9]*\:\ /, '');
msg = fname + ':' + error.lineNumber + ': ' + msg;
console.log(msg);
++count;
});
}
} catch (e) {
++count;
if (options.format === 'junit') {
console.log('<testsuite name="' + fname + '" errors="1" failures="0" tests="1" ' +
' time="' + Math.round((Date.now() - timestamp) / 1000) + '">');
console.log(' <testcase name="' + e.message + '" ' + ' time="0">');
console.log(' <error type="ParseError" message="' + e.message + '">' +
e.message + '(' + fname + ((e.lineNumber) ? ':' + e.lineNumber : '') +
')</error>');
console.log(' </testcase>');
console.log('</testsuite>');
} else {
console.log('Error: ' + e.message);
}
}
});
if (options.format === 'junit') {
console.log('</testsuites>');
}
if (count > 0) {
process.exit(1);
}
if (count === 0 && typeof phantom === 'object') {
process.exit(0);
}

42
node_modules/.bin/flat generated vendored
View file

@ -1,42 +0,0 @@
#!/usr/bin/env node
const fs = require('fs')
const path = require('path')
const readline = require('readline')
const flat = require('./index')
const filepath = process.argv.slice(2)[0]
if (filepath) {
// Read from file
const file = path.resolve(process.cwd(), filepath)
fs.accessSync(file, fs.constants.R_OK) // allow to throw if not readable
out(require(file))
} else if (process.stdin.isTTY) {
usage(0)
} else {
// Read from newline-delimited STDIN
const lines = []
readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false
})
.on('line', line => lines.push(line))
.on('close', () => out(JSON.parse(lines.join('\n'))))
}
function out (data) {
process.stdout.write(JSON.stringify(flat(data), null, 2))
}
function usage (code) {
console.log(`
Usage:
flat foo.json
cat foo.json | flat
`)
process.exit(code || 0)
}

176
node_modules/.bin/handlebars generated vendored
View file

@ -1,176 +0,0 @@
#!/usr/bin/env node
var argv = parseArgs({
'f': {
'type': 'string',
'description': 'Output File',
'alias': 'output'
},
'map': {
'type': 'string',
'description': 'Source Map File'
},
'a': {
'type': 'boolean',
'description': 'Exports amd style (require.js)',
'alias': 'amd'
},
'c': {
'type': 'string',
'description': 'Exports CommonJS style, path to Handlebars module',
'alias': 'commonjs',
'default': null
},
'h': {
'type': 'string',
'description': 'Path to handlebar.js (only valid for amd-style)',
'alias': 'handlebarPath',
'default': ''
},
'k': {
'type': 'string',
'description': 'Known helpers',
'alias': 'known'
},
'o': {
'type': 'boolean',
'description': 'Known helpers only',
'alias': 'knownOnly'
},
'm': {
'type': 'boolean',
'description': 'Minimize output',
'alias': 'min'
},
'n': {
'type': 'string',
'description': 'Template namespace',
'alias': 'namespace',
'default': 'Handlebars.templates'
},
's': {
'type': 'boolean',
'description': 'Output template function only.',
'alias': 'simple'
},
'N': {
'type': 'string',
'description': 'Name of passed string templates. Optional if running in a simple mode. Required when operating on multiple templates.',
'alias': 'name'
},
'i': {
'type': 'string',
'description': 'Generates a template from the passed CLI argument.\n"-" is treated as a special value and causes stdin to be read for the template value.',
'alias': 'string'
},
'r': {
'type': 'string',
'description': 'Template root. Base value that will be stripped from template names.',
'alias': 'root'
},
'p': {
'type': 'boolean',
'description': 'Compiling a partial template',
'alias': 'partial'
},
'd': {
'type': 'boolean',
'description': 'Include data when compiling',
'alias': 'data'
},
'e': {
'type': 'string',
'description': 'Template extension.',
'alias': 'extension',
'default': 'handlebars'
},
'b': {
'type': 'boolean',
'description': 'Removes the BOM (Byte Order Mark) from the beginning of the templates.',
'alias': 'bom'
},
'v': {
'type': 'boolean',
'description': 'Prints the current compiler version',
'alias': 'version'
},
'help': {
'type': 'boolean',
'description': 'Outputs this message'
}
});
argv.files = argv._;
delete argv._;
var Precompiler = require('../dist/cjs/precompiler');
Precompiler.loadTemplates(argv, function(err, opts) {
if (err) {
throw err;
}
if (opts.help || (!opts.templates.length && !opts.version)) {
printUsage(argv._spec, 120);
} else {
Precompiler.cli(opts);
}
});
function pad(n) {
var str = '';
while (str.length < n) {
str += ' ';
}
return str;
}
function parseArgs(spec) {
var opts = { alias: {}, boolean: [], default: {}, string: [] };
Object.keys(spec).forEach(function (arg) {
var opt = spec[arg];
opts[opt.type].push(arg);
if ('alias' in opt) opts.alias[arg] = opt.alias;
if ('default' in opt) opts.default[arg] = opt.default;
});
var argv = require('minimist')(process.argv.slice(2), opts);
argv._spec = spec;
return argv;
}
function printUsage(spec, wrap) {
var wordwrap = require('wordwrap');
console.log('Precompile handlebar templates.');
console.log('Usage: handlebars [template|directory]...');
var opts = [];
var width = 0;
Object.keys(spec).forEach(function (arg) {
var opt = spec[arg];
var name = (arg.length === 1 ? '-' : '--') + arg;
if ('alias' in opt) name += ', --' + opt.alias;
var meta = '[' + opt.type + ']';
if ('default' in opt) meta += ' [default: ' + JSON.stringify(opt.default) + ']';
opts.push({ name: name, desc: opt.description, meta: meta });
if (name.length > width) width = name.length;
});
console.log('Options:');
opts.forEach(function (opt) {
var desc = wordwrap(width + 4, wrap + 1)(opt.desc);
console.log(' %s%s%s%s%s',
opt.name,
pad(width - opt.name.length + 2),
desc.slice(width + 4),
pad(wrap - opt.meta.length - desc.split(/\n/).pop().length),
opt.meta
);
});
}

16
node_modules/.bin/hardhat generated vendored
View file

@ -1,16 +0,0 @@
#!/usr/bin/env node
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const semver_1 = __importDefault(require("semver"));
const chalk_1 = __importDefault(require("chalk"));
const constants_1 = require("./constants");
if (!semver_1.default.satisfies(process.version, constants_1.SUPPORTED_NODE_VERSIONS.join(" || "))) {
console.warn(chalk_1.default.yellow.bold(`WARNING:`), `You are currently using Node.js ${process.version}, which is not supported by Hardhat. This can lead to unexpected behavior. See https://hardhat.org/nodejs-versions`);
console.log();
console.log();
}
require("./cli");
//# sourceMappingURL=bootstrap.js.map

148
node_modules/.bin/he generated vendored
View file

@ -1,148 +0,0 @@
#!/usr/bin/env node
(function() {
var fs = require('fs');
var he = require('../he.js');
var strings = process.argv.splice(2);
var stdin = process.stdin;
var data;
var timeout;
var action;
var options = {};
var log = console.log;
var main = function() {
var option = strings[0];
var count = 0;
if (/^(?:-h|--help|undefined)$/.test(option)) {
log(
'he v%s - https://mths.be/he',
he.version
);
log([
'\nUsage:\n',
'\the [--escape] string',
'\the [--encode] [--use-named-refs] [--everything] [--allow-unsafe] [--decimal] string',
'\the [--decode] [--attribute] [--strict] string',
'\the [-v | --version]',
'\the [-h | --help]',
'\nExamples:\n',
'\the --escape \\<img\\ src\\=\\\'x\\\'\\ onerror\\=\\"prompt\\(1\\)\\"\\>',
'\techo \'&copy; &#x1D306;\' | he --decode'
].join('\n'));
return process.exit(option ? 0 : 1);
}
if (/^(?:-v|--version)$/.test(option)) {
log('v%s', he.version);
return process.exit(0);
}
strings.forEach(function(string) {
// Process options
if (string == '--escape') {
action = 'escape';
return;
}
if (string == '--encode') {
action = 'encode';
return;
}
if (string == '--use-named-refs') {
action = 'encode';
options.useNamedReferences = true;
return;
}
if (string == '--everything') {
action = 'encode';
options.encodeEverything = true;
return;
}
if (string == '--allow-unsafe') {
action = 'encode';
options.allowUnsafeSymbols = true;
return;
}
if (string == '--decimal') {
action = 'encode';
options.decimal = true;
return;
}
if (string == '--decode') {
action = 'decode';
return;
}
if (string == '--attribute') {
action = 'decode';
options.isAttributeValue = true;
return;
}
if (string == '--strict') {
action = 'decode';
options.strict = true;
return;
}
// Process string(s)
var result;
if (!action) {
log('Error: he requires at least one option and a string argument.');
log('Try `he --help` for more information.');
return process.exit(1);
}
try {
result = he[action](string, options);
log(result);
count++;
} catch(error) {
log(error.message + '\n');
log('Error: failed to %s.', action);
log('If you think this is a bug in he, please report it:');
log('https://github.com/mathiasbynens/he/issues/new');
log(
'\nStack trace using he@%s:\n',
he.version
);
log(error.stack);
return process.exit(1);
}
});
if (!count) {
log('Error: he requires a string argument.');
log('Try `he --help` for more information.');
return process.exit(1);
}
// Return with exit status 0 outside of the `forEach` loop, in case
// multiple strings were passed in.
return process.exit(0);
};
if (stdin.isTTY) {
// handle shell arguments
main();
} else {
// Either the script is called from within a non-TTY context, or `stdin`
// content is being piped in.
if (!process.stdout.isTTY) {
// The script was called from a non-TTY context. This is a rather uncommon
// use case we dont actively support. However, we dont want the script
// to wait forever in such cases, so…
timeout = setTimeout(function() {
// …if no piped data arrived after a whole minute, handle shell
// arguments instead.
main();
}, 60000);
}
data = '';
stdin.on('data', function(chunk) {
clearTimeout(timeout);
data += chunk;
});
stdin.on('end', function() {
strings.push(data.trim());
main();
});
stdin.resume();
}
}());

99
node_modules/.bin/istanbul generated vendored
View file

@ -1,99 +0,0 @@
#!/usr/bin/env node
/*
Copyright (c) 2012, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License. See the accompanying LICENSE file for terms.
*/
var async = require('async'),
Command = require('./command'),
inputError = require('./util/input-error'),
exitProcess = process.exit; //hold a reference to original process.exit so that we are not affected even when a test changes it
require('./register-plugins');
function findCommandPosition(args) {
var i;
for (i = 0; i < args.length; i += 1) {
if (args[i].charAt(0) !== '-') {
return i;
}
}
return -1;
}
function exit(ex, code) {
// flush output for Node.js Windows pipe bug
// https://github.com/joyent/node/issues/6247 is just one bug example
// https://github.com/visionmedia/mocha/issues/333 has a good discussion
var streams = [process.stdout, process.stderr];
async.forEach(streams, function (stream, done) {
// submit a write request and wait until it's written
stream.write('', done);
}, function () {
if (ex) {
if (typeof ex === 'string') {
console.error(ex);
exitProcess(1);
} else {
throw ex; // turn it into an uncaught exception
}
} else {
exitProcess(code);
}
});
}
function errHandler (ex) {
if (!ex) { return; }
if (!ex.inputError) {
// exit with exception stack trace
exit(ex);
} else {
//don't print nasty traces but still exit(1)
console.error(ex.message);
console.error('Try "istanbul help" for usage');
exit(null, 1);
}
}
function runCommand(args, callback) {
var pos = findCommandPosition(args),
command,
commandArgs,
commandObject;
if (pos < 0) {
return callback(inputError.create('Need a command to run'));
}
commandArgs = args.slice(0, pos);
command = args[pos];
commandArgs.push.apply(commandArgs, args.slice(pos + 1));
try {
commandObject = Command.create(command);
} catch (ex) {
errHandler(inputError.create(ex.message));
return;
}
commandObject.run(commandArgs, errHandler);
}
function runToCompletion(args) {
runCommand(args, errHandler);
}
/* istanbul ignore if: untestable */
if (require.main === module) {
var args = Array.prototype.slice.call(process.argv, 2);
runToCompletion(args);
}
module.exports = {
runToCompletion: runToCompletion
};

126
node_modules/.bin/js-yaml generated vendored
View file

@ -1,126 +0,0 @@
#!/usr/bin/env node
'use strict';
/*eslint-disable no-console*/
var fs = require('fs');
var argparse = require('argparse');
var yaml = require('..');
////////////////////////////////////////////////////////////////////////////////
var cli = new argparse.ArgumentParser({
prog: 'js-yaml',
add_help: true
});
cli.add_argument('-v', '--version', {
action: 'version',
version: require('../package.json').version
});
cli.add_argument('-c', '--compact', {
help: 'Display errors in compact mode',
action: 'store_true'
});
// deprecated (not needed after we removed output colors)
// option suppressed, but not completely removed for compatibility
cli.add_argument('-j', '--to-json', {
help: argparse.SUPPRESS,
dest: 'json',
action: 'store_true'
});
cli.add_argument('-t', '--trace', {
help: 'Show stack trace on error',
action: 'store_true'
});
cli.add_argument('file', {
help: 'File to read, utf-8 encoded without BOM',
nargs: '?',
default: '-'
});
////////////////////////////////////////////////////////////////////////////////
var options = cli.parse_args();
////////////////////////////////////////////////////////////////////////////////
function readFile(filename, encoding, callback) {
if (options.file === '-') {
// read from stdin
var chunks = [];
process.stdin.on('data', function (chunk) {
chunks.push(chunk);
});
process.stdin.on('end', function () {
return callback(null, Buffer.concat(chunks).toString(encoding));
});
} else {
fs.readFile(filename, encoding, callback);
}
}
readFile(options.file, 'utf8', function (error, input) {
var output, isYaml;
if (error) {
if (error.code === 'ENOENT') {
console.error('File not found: ' + options.file);
process.exit(2);
}
console.error(
options.trace && error.stack ||
error.message ||
String(error));
process.exit(1);
}
try {
output = JSON.parse(input);
isYaml = false;
} catch (err) {
if (err instanceof SyntaxError) {
try {
output = [];
yaml.loadAll(input, function (doc) { output.push(doc); }, {});
isYaml = true;
if (output.length === 0) output = null;
else if (output.length === 1) output = output[0];
} catch (e) {
if (options.trace && err.stack) console.error(e.stack);
else console.error(e.toString(options.compact));
process.exit(1);
}
} else {
console.error(
options.trace && err.stack ||
err.message ||
String(err));
process.exit(1);
}
}
if (isYaml) console.log(JSON.stringify(output, null, ' '));
else console.log(yaml.dump(output));
});

33
node_modules/.bin/mkdirp generated vendored
View file

@ -1,33 +0,0 @@
#!/usr/bin/env node
var mkdirp = require('../');
var minimist = require('minimist');
var fs = require('fs');
var argv = minimist(process.argv.slice(2), {
alias: { m: 'mode', h: 'help' },
string: [ 'mode' ]
});
if (argv.help) {
fs.createReadStream(__dirname + '/usage.txt').pipe(process.stdout);
return;
}
var paths = argv._.slice();
var mode = argv.mode ? parseInt(argv.mode, 8) : undefined;
(function next () {
if (paths.length === 0) return;
var p = paths.shift();
if (mode === undefined) mkdirp(p, cb)
else mkdirp(p, mode, cb)
function cb (err) {
if (err) {
console.error(err.message);
process.exit(1);
}
else next();
}
})();

142
node_modules/.bin/mocha generated vendored
View file

@ -1,142 +0,0 @@
#!/usr/bin/env node
'use strict';
/**
* This wrapper executable checks for known node flags and appends them when found,
* before invoking the "real" executable (`lib/cli/cli.js`)
*
* @module bin/mocha
* @private
*/
const {loadOptions} = require('../lib/cli/options');
const {
unparseNodeFlags,
isNodeFlag,
impliesNoTimeouts
} = require('../lib/cli/node-flags');
const unparse = require('yargs-unparser');
const debug = require('debug')('mocha:cli:mocha');
const {aliases} = require('../lib/cli/run-option-metadata');
const mochaArgs = {};
const nodeArgs = {};
let hasInspect = false;
const opts = loadOptions(process.argv.slice(2));
debug('loaded opts', opts);
/**
* Given option/command `value`, disable timeouts if applicable
* @param {string} [value] - Value to check
* @ignore
*/
const disableTimeouts = value => {
if (impliesNoTimeouts(value)) {
debug('option %s disabled timeouts', value);
mochaArgs.timeout = 0;
}
};
/**
* If `value` begins with `v8-` and is not explicitly `v8-options`, remove prefix
* @param {string} [value] - Value to check
* @returns {string} `value` with prefix (maybe) removed
* @ignore
*/
const trimV8Option = value =>
value !== 'v8-options' && /^v8-/.test(value) ? value.slice(3) : value;
// sort options into "node" and "mocha" buckets
Object.keys(opts).forEach(opt => {
if (isNodeFlag(opt)) {
nodeArgs[trimV8Option(opt)] = opts[opt];
} else {
mochaArgs[opt] = opts[opt];
}
});
// disable 'timeout' for debugFlags
Object.keys(nodeArgs).forEach(opt => disableTimeouts(opt));
mochaArgs['node-option'] &&
mochaArgs['node-option'].forEach(opt => disableTimeouts(opt));
// Native debugger handling
// see https://nodejs.org/api/debugger.html#debugger_debugger
// look for 'inspect' that would launch this debugger,
// remove it from Mocha's opts and prepend it to Node's opts.
// A deprecation warning will be printed by node, if applicable.
// (mochaArgs._ are "positional" arguments, not prefixed with - or --)
if (mochaArgs._) {
const i = mochaArgs._.findIndex(val => val === 'inspect');
if (i > -1) {
mochaArgs._.splice(i, 1);
disableTimeouts('inspect');
hasInspect = true;
}
}
if (mochaArgs['node-option'] || Object.keys(nodeArgs).length || hasInspect) {
const {spawn} = require('child_process');
const mochaPath = require.resolve('../lib/cli/cli.js');
const nodeArgv =
(mochaArgs['node-option'] && mochaArgs['node-option'].map(v => '--' + v)) ||
unparseNodeFlags(nodeArgs);
if (hasInspect) nodeArgv.unshift('inspect');
delete mochaArgs['node-option'];
debug('final node argv', nodeArgv);
const args = [].concat(
nodeArgv,
mochaPath,
unparse(mochaArgs, {alias: aliases})
);
debug(
'forking child process via command: %s %s',
process.execPath,
args.join(' ')
);
const proc = spawn(process.execPath, args, {
stdio: 'inherit'
});
proc.on('exit', (code, signal) => {
process.on('exit', () => {
if (signal) {
process.kill(process.pid, signal);
} else {
process.exit(code);
}
});
});
// terminate children.
process.on('SIGINT', () => {
// XXX: a previous comment said this would abort the runner, but I can't see that it does
// anything with the default runner.
debug('main process caught SIGINT');
proc.kill('SIGINT');
// if running in parallel mode, we will have a proper SIGINT handler, so the below won't
// be needed.
if (!args.parallel || args.jobs < 2) {
// win32 does not support SIGTERM, so use next best thing.
if (require('os').platform() === 'win32') {
proc.kill('SIGKILL');
} else {
// using SIGKILL won't cleanly close the output streams, which can result
// in cut-off text or a befouled terminal.
debug('sending SIGTERM to child process');
proc.kill('SIGTERM');
}
}
});
} else {
debug('running Mocha in-process');
require('../lib/cli/cli').main([], mochaArgs);
}

28
node_modules/.bin/ndjson generated vendored
View file

@ -1,28 +0,0 @@
#!/usr/bin/env node
const fs = require('fs')
const { pipeline } = require('readable-stream')
const minimist = require('minimist')
const ndjson = require('./index.js')
const args = minimist(process.argv.slice(2))
const first = args._[0]
if (!first) {
console.error('Usage: ndjson [input] <options>')
process.exit(1)
}
const inputStream = first === '-'
? process.stdin
: fs.createReadStream(first)
pipeline(
inputStream,
ndjson.parse(args),
ndjson.stringify(args),
process.stdout,
(err) => {
err ? process.exit(1) : process.exit(0)
}
)

82
node_modules/.bin/node-gyp-build generated vendored
View file

@ -1,82 +0,0 @@
#!/usr/bin/env node
var proc = require('child_process')
var os = require('os')
var path = require('path')
if (!buildFromSource()) {
proc.exec('node-gyp-build-test', function (err, stdout, stderr) {
if (err) {
if (verbose()) console.error(stderr)
preinstall()
}
})
} else {
preinstall()
}
function build () {
var win32 = os.platform() === 'win32'
var args = [win32 ? 'node-gyp.cmd' : 'node-gyp', 'rebuild']
try {
var pkg = require('node-gyp/package.json')
args = [
process.execPath,
path.join(require.resolve('node-gyp/package.json'), '..', typeof pkg.bin === 'string' ? pkg.bin : pkg.bin['node-gyp']),
'rebuild'
]
} catch (_) {}
proc.spawn(args[0], args.slice(1), { stdio: 'inherit', shell: win32, windowsHide: true }).on('exit', function (code) {
if (code || !process.argv[3]) process.exit(code)
exec(process.argv[3]).on('exit', function (code) {
process.exit(code)
})
})
}
function preinstall () {
if (!process.argv[2]) return build()
exec(process.argv[2]).on('exit', function (code) {
if (code) process.exit(code)
build()
})
}
function exec (cmd) {
if (process.platform !== 'win32') {
var shell = os.platform() === 'android' ? 'sh' : true
return proc.spawn(cmd, [], {
shell,
stdio: 'inherit'
})
}
return proc.spawn(cmd, [], {
windowsVerbatimArguments: true,
stdio: 'inherit',
shell: true,
windowsHide: true
})
}
function buildFromSource () {
return hasFlag('--build-from-source') || process.env.npm_config_build_from_source === 'true'
}
function verbose () {
return hasFlag('--verbose') || process.env.npm_config_loglevel === 'verbose'
}
// TODO (next major): remove in favor of env.npm_config_* which works since npm
// 0.1.8 while npm_config_argv will stop working in npm 7. See npm/rfcs#90
function hasFlag (flag) {
if (!process.env.npm_config_argv) return false
try {
return JSON.parse(process.env.npm_config_argv).original.indexOf(flag) !== -1
} catch (_) {
return false
}
}

View file

@ -1,7 +0,0 @@
#!/usr/bin/env node
/*
I am only useful as an install script to make node-gyp not compile for purely optional native deps
*/
process.exit(0)

View file

@ -1,19 +0,0 @@
#!/usr/bin/env node
process.env.NODE_ENV = 'test'
var path = require('path')
var test = null
try {
var pkg = require(path.join(process.cwd(), 'package.json'))
if (pkg.name && process.env[pkg.name.toUpperCase().replace(/-/g, '_')]) {
process.exit(0)
}
test = pkg.prebuild.test
} catch (err) {
// do nothing
}
if (test) require(path.join(process.cwd(), test))
else require('./')()

54
node_modules/.bin/nopt generated vendored
View file

@ -1,54 +0,0 @@
#!/usr/bin/env node
var nopt = require("../lib/nopt")
, path = require("path")
, types = { num: Number
, bool: Boolean
, help: Boolean
, list: Array
, "num-list": [Number, Array]
, "str-list": [String, Array]
, "bool-list": [Boolean, Array]
, str: String
, clear: Boolean
, config: Boolean
, length: Number
, file: path
}
, shorthands = { s: [ "--str", "astring" ]
, b: [ "--bool" ]
, nb: [ "--no-bool" ]
, tft: [ "--bool-list", "--no-bool-list", "--bool-list", "true" ]
, "?": ["--help"]
, h: ["--help"]
, H: ["--help"]
, n: [ "--num", "125" ]
, c: ["--config"]
, l: ["--length"]
, f: ["--file"]
}
, parsed = nopt( types
, shorthands
, process.argv
, 2 )
console.log("parsed", parsed)
if (parsed.help) {
console.log("")
console.log("nopt cli tester")
console.log("")
console.log("types")
console.log(Object.keys(types).map(function M (t) {
var type = types[t]
if (Array.isArray(type)) {
return [t, type.map(function (type) { return type.name })]
}
return [t, type && type.name]
}).reduce(function (s, i) {
s[i[0]] = i[1]
return s
}, {}))
console.log("")
console.log("shorthands")
console.log(shorthands)
}

64
node_modules/.bin/prettier generated vendored
View file

@ -1,64 +0,0 @@
#!/usr/bin/env node
"use strict";
var __getOwnPropNames = Object.getOwnPropertyNames;
var __commonJS = function(cb, mod) {
return function __require() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
};
// node_modules/semver-compare/index.js
var require_semver_compare = __commonJS({
"node_modules/semver-compare/index.js": function(exports2, module2) {
module2.exports = function cmp(a, b) {
var pa = a.split(".");
var pb = b.split(".");
for (var i = 0; i < 3; i++) {
var na = Number(pa[i]);
var nb = Number(pb[i]);
if (na > nb)
return 1;
if (nb > na)
return -1;
if (!isNaN(na) && isNaN(nb))
return 1;
if (isNaN(na) && !isNaN(nb))
return -1;
}
return 0;
};
}
});
// node_modules/please-upgrade-node/index.js
var require_please_upgrade_node = __commonJS({
"node_modules/please-upgrade-node/index.js": function(exports2, module2) {
var semverCompare = require_semver_compare();
module2.exports = function pleaseUpgradeNode2(pkg, opts) {
var opts = opts || {};
var requiredVersion = pkg.engines.node.replace(">=", "");
var currentVersion = process.version.replace("v", "");
if (semverCompare(currentVersion, requiredVersion) === -1) {
if (opts.message) {
console.error(opts.message(requiredVersion));
} else {
console.error(
pkg.name + " requires at least version " + requiredVersion + " of Node, please upgrade"
);
}
if (opts.hasOwnProperty("exitCode")) {
process.exit(opts.exitCode);
} else {
process.exit(1);
}
}
};
}
});
// bin/prettier.js
var pleaseUpgradeNode = require_please_upgrade_node();
var packageJson = require("./package.json");
pleaseUpgradeNode(packageJson);
var cli = require("./cli.js");
module.exports = cli.run(process.argv.slice(2));

50
node_modules/.bin/rimraf generated vendored
View file

@ -1,50 +0,0 @@
#!/usr/bin/env node
var rimraf = require('./')
var help = false
var dashdash = false
var noglob = false
var args = process.argv.slice(2).filter(function(arg) {
if (dashdash)
return !!arg
else if (arg === '--')
dashdash = true
else if (arg === '--no-glob' || arg === '-G')
noglob = true
else if (arg === '--glob' || arg === '-g')
noglob = false
else if (arg.match(/^(-+|\/)(h(elp)?|\?)$/))
help = true
else
return !!arg
})
if (help || args.length === 0) {
// If they didn't ask for help, then this is not a "success"
var log = help ? console.log : console.error
log('Usage: rimraf <path> [<path> ...]')
log('')
log(' Deletes all files and folders at "path" recursively.')
log('')
log('Options:')
log('')
log(' -h, --help Display this usage info')
log(' -G, --no-glob Do not expand glob patterns in arguments')
log(' -g, --glob Expand glob patterns in arguments (default)')
process.exit(help ? 0 : 1)
} else
go(0)
function go (n) {
if (n >= args.length)
return
var options = {}
if (noglob)
options = { glob: false }
rimraf(args[n], options, function (er) {
if (er)
throw er
go(n+1)
})
}

58
node_modules/.bin/rlp generated vendored
View file

@ -1,58 +0,0 @@
#!/usr/bin/env node
const RLP = require('../dist/index.js')
const method = process.argv[2]
const strInput = process.argv[3]
const { bytesToHex } = RLP.utils
if (typeof strInput !== 'string') {
return console.error(`Expected JSON string input, received type: ${typeof strInput}`)
}
if (method === 'encode') {
// Parse JSON
let json
try {
json = JSON.parse(strInput)
} catch (error) {
const errorMsg = error.message ? error.message : error
return console.error(`Error could not parse JSON: ${errorMsg}`)
}
// Encode RLP
try {
const encoded = RLP.encode(json)
console.log('0x' + bytesToHex(encoded))
} catch (error) {
const errorMsg = error.message ? error.message : error
console.error(`Error encoding RLP: ${errorMsg}`)
}
} else if (method === 'decode') {
// Decode
try {
const decoded = RLP.decode(strInput)
const json = JSON.stringify(arrToJSON(decoded))
console.log(json)
} catch (error) {
const errorMsg = error.message ? error.message : error
console.error(`Error decoding RLP: ${errorMsg}`)
}
} else {
console.error('Unsupported method')
}
/**
* Uint8Array or Array<Uint8Array> to JSON
*/
function arrToJSON(ba) {
if (ba instanceof Uint8Array) {
return bytesToHex(ba)
} else if (ba instanceof Array) {
const arr = []
for (let i = 0; i < ba.length; i++) {
arr.push(arrToJSON(ba[i]))
}
return arr
}
}

174
node_modules/.bin/semver generated vendored
View file

@ -1,174 +0,0 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
var argv = process.argv.slice(2)
var versions = []
var range = []
var inc = null
var version = require('../package.json').version
var loose = false
var includePrerelease = false
var coerce = false
var rtl = false
var identifier
var semver = require('../semver')
var reverse = false
var options = {}
main()
function main () {
if (!argv.length) return help()
while (argv.length) {
var a = argv.shift()
var indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
a = a.slice(0, indexOfEqualSign)
argv.unshift(a.slice(indexOfEqualSign + 1))
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
var options = { loose: loose, includePrerelease: includePrerelease, rtl: rtl }
versions = versions.map(function (v) {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter(function (v) {
return semver.valid(v)
})
if (!versions.length) return fail()
if (inc && (versions.length !== 1 || range.length)) { return failInc() }
for (var i = 0, l = range.length; i < l; i++) {
versions = versions.filter(function (v) {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) return fail()
}
return success(versions)
}
function failInc () {
console.error('--inc can only be used on a single version with no range')
fail()
}
function fail () { process.exit(1) }
function success () {
var compare = reverse ? 'rcompare' : 'compare'
versions.sort(function (a, b) {
return semver[compare](a, b, options)
}).map(function (v) {
return semver.clean(v, options)
}).map(function (v) {
return inc ? semver.inc(v, inc, options, identifier) : v
}).forEach(function (v, i, _) { console.log(v) })
}
function help () {
console.log(['SemVer ' + version,
'',
'A JavaScript implementation of the https://semver.org/ specification',
'Copyright Isaac Z. Schlueter',
'',
'Usage: semver [options] <version> [<version> [...]]',
'Prints valid versions sorted by SemVer precedence',
'',
'Options:',
'-r --range <range>',
' Print versions that match the specified range.',
'',
'-i --increment [<level>]',
' Increment a version by the specified level. Level can',
' be one of: major, minor, patch, premajor, preminor,',
" prepatch, or prerelease. Default level is 'patch'.",
' Only one version may be specified.',
'',
'--preid <identifier>',
' Identifier to be used to prefix premajor, preminor,',
' prepatch or prerelease version increments.',
'',
'-l --loose',
' Interpret versions and ranges loosely',
'',
'-p --include-prerelease',
' Always include prerelease versions in range matching',
'',
'-c --coerce',
' Coerce a string into SemVer if possible',
' (does not imply --loose)',
'',
'--rtl',
' Coerce version strings right to left',
'',
'--ltr',
' Coerce version strings left to right (default)',
'',
'Program exits successfully if any valid version satisfies',
'all supplied ranges, and prints all satisfying versions.',
'',
'If no satisfying versions are found, then exits failure.',
'',
'Versions are printed in ascending order, so supplying',
'multiple versions to the utility will just sort them.'
].join('\n'))
}

41
node_modules/.bin/sha.js generated vendored
View file

@ -1,41 +0,0 @@
#! /usr/bin/env node
var createHash = require('./browserify')
var argv = process.argv.slice(2)
function pipe (algorithm, s) {
var start = Date.now()
var hash = createHash(algorithm || 'sha1')
s.on('data', function (data) {
hash.update(data)
})
s.on('end', function () {
if (process.env.DEBUG) {
return console.log(hash.digest('hex'), Date.now() - start)
}
console.log(hash.digest('hex'))
})
}
function usage () {
console.error('sha.js [algorithm=sha1] [filename] # hash filename with algorithm')
console.error('input | sha.js [algorithm=sha1] # hash stdin with algorithm')
console.error('sha.js --help # display this message')
}
if (!process.stdin.isTTY) {
pipe(argv[0], process.stdin)
} else if (argv.length) {
if (/--help|-h/.test(argv[0])) {
usage()
} else {
var filename = argv.pop()
var algorithm = argv.pop()
pipe(algorithm, require('fs').createReadStream(filename))
}
} else {
usage()
}

48
node_modules/.bin/shjs generated vendored
View file

@ -1,48 +0,0 @@
#!/usr/bin/env node
if (require.main !== module) {
throw new Error('Executable-only module should not be required');
}
// we must import global ShellJS methods after the require.main check to prevent the global
// namespace from being polluted if the error is caught
require('../global');
function exitWithErrorMessage(msg) {
console.log(msg);
console.log();
process.exit(1);
}
if (process.argv.length < 3) {
exitWithErrorMessage('ShellJS: missing argument (script name)');
}
var args,
scriptName = process.argv[2];
env['NODE_PATH'] = __dirname + '/../..';
if (!scriptName.match(/\.js/) && !scriptName.match(/\.coffee/)) {
if (test('-f', scriptName + '.js'))
scriptName += '.js';
if (test('-f', scriptName + '.coffee'))
scriptName += '.coffee';
}
if (!test('-f', scriptName)) {
exitWithErrorMessage('ShellJS: script not found ('+scriptName+')');
}
args = process.argv.slice(3);
for (var i = 0, l = args.length; i < l; i++) {
if (args[i][0] !== "-"){
args[i] = '"' + args[i] + '"'; // fixes arguments with multiple words
}
}
var path = require('path');
var extensions = require('interpret').extensions;
var rechoir = require('rechoir');
rechoir.prepare(extensions, scriptName);
require(require.resolve(path.resolve(process.cwd(), scriptName)));

170
node_modules/.bin/solcjs generated vendored
View file

@ -1,170 +0,0 @@
#!/usr/bin/env node
// hold on to any exception handlers that existed prior to this script running, we'll be adding them back at the end
var originalUncaughtExceptionListeners = process.listeners("uncaughtException");
var fs = require('fs-extra');
var path = require('path');
var solc = require('./index.js');
var smtchecker = require('./smtchecker.js');
var smtsolver = require('./smtsolver.js');
// FIXME: remove annoying exception catcher of Emscripten
// see https://github.com/chriseth/browser-solidity/issues/167
process.removeAllListeners('uncaughtException');
var commander = require('commander');
var program = new commander.Command();
program.name('solcjs');
program.version(solc.version());
program
.option('--version', 'Show version and exit.')
.option('--optimize', 'Enable bytecode optimizer.')
.option('--bin', 'Binary of the contracts in hex.')
.option('--abi', 'ABI of the contracts.')
.option('--standard-json', 'Turn on Standard JSON Input / Output mode.')
.option('--base-path <path>', 'Automatically resolve all imports inside the given path.')
.option('-o, --output-dir <output-directory>', 'Output directory for the contracts.');
program.parse(process.argv);
var files = program.args;
var destination = program.outputDir || '.'
function abort (msg) {
console.error(msg || 'Error occured');
process.exit(1);
}
function readFileCallback(path) {
path = program.basePath + '/' + path;
if (fs.existsSync(path)) {
try {
return { 'contents': fs.readFileSync(path).toString('utf8') }
} catch (e) {
return { error: 'Error reading ' + path + ': ' + e };
}
} else
return { error: 'File not found at ' + path}
}
function stripBasePath(path) {
if (program.basePath && path.startsWith(program.basePath))
return path.slice(program.basePath.length);
else
return path;
}
var callbacks = undefined
if (program.basePath)
callbacks = {'import': readFileCallback};
if (program.standardJson) {
var input = fs.readFileSync(process.stdin.fd).toString('utf8');
var output = solc.compile(input, callbacks);
try {
var inputJSON = smtchecker.handleSMTQueries(JSON.parse(input), JSON.parse(output), smtsolver.smtSolver);
if (inputJSON) {
output = solc.compile(JSON.stringify(inputJSON), callbacks);
}
}
catch (e) {
var addError = {
component: "general",
formattedMessage: e.toString(),
message: e.toString(),
type: "Warning"
};
var outputJSON = JSON.parse(output);
if (!outputJSON.errors) {
outputJSON.errors = []
}
outputJSON.errors.push(addError);
output = JSON.stringify(outputJSON);
}
console.log(output);
process.exit(0);
} else if (files.length === 0) {
console.error('Must provide a file');
process.exit(1);
}
if (!(program.bin || program.abi)) {
abort('Invalid option selected, must specify either --bin or --abi');
}
var sources = {};
for (var i = 0; i < files.length; i++) {
try {
sources[stripBasePath(files[i])] = { content: fs.readFileSync(files[i]).toString() };
} catch (e) {
abort('Error reading ' + files[i] + ': ' + e);
}
}
var output = JSON.parse(solc.compile(JSON.stringify({
language: 'Solidity',
settings: {
optimizer: {
enabled: program.optimize
},
outputSelection: {
'*': {
'*': [ 'abi', 'evm.bytecode' ]
}
}
},
sources: sources
}), callbacks));
let hasError = false;
if (!output) {
abort('No output from compiler');
} else if (output['errors']) {
for (var error in output['errors']) {
var message = output['errors'][error]
if (message.severity === 'warning') {
console.log(message.formattedMessage)
} else {
console.error(message.formattedMessage)
hasError = true
}
}
}
fs.ensureDirSync (destination);
function writeFile (file, content) {
file = path.join(destination, file);
fs.writeFile(file, content, function (err) {
if (err) {
console.error('Failed to write ' + file + ': ' + err);
}
});
}
for (var fileName in output.contracts) {
for (var contractName in output.contracts[fileName]) {
var contractFileName = fileName + ':' + contractName;
contractFileName = contractFileName.replace(/[:./\\]/g, '_');
if (program.bin) {
writeFile(contractFileName + '.bin', output.contracts[fileName][contractName].evm.bytecode.object);
}
if (program.abi) {
writeFile(contractFileName + '.abi', JSON.stringify(output.contracts[fileName][contractName].abi));
}
}
}
// Put back original exception handlers.
originalUncaughtExceptionListeners.forEach(function (listener) {
process.addListener('uncaughtException', listener);
});
if (hasError) {
process.exit(1);
}

10
node_modules/.bin/solidity-coverage generated vendored
View file

@ -1,10 +0,0 @@
#!/usr/bin/env node
/*
Logs a warning / informational message when user tries to
invoke 'solidity-coverage' as a shell command. This file
is listed as the package.json "bin".
*/
const AppUI = require('../lib/ui').AppUI;
(new AppUI()).report('command');

29
node_modules/.bin/testrpc-sc generated vendored
View file

@ -1,29 +0,0 @@
#!/usr/bin/env node
const c = require('chalk');
const emoji = require('node-emoji');
const title = `
:warning: ${c.red.bold('solidity-coverage >= 0.7.0 does not use "testrpc-sc"')} :warning:
${c.bold('===========================================================')}`;
const info = `
Instead, you can use any ganache version you'd like & configure it as you wish
via the .solcover.js options. (It also comes with a default version for easy use.)
> ${c.bold('Launching the client independently of the coverage tool is no longer supported.')}
> See github.com/sc-forks/solidity-coverage for help with configuration.`;
const thanks = `
Thanks! - sc-forks
`;
const msg = `
${title}
${info}
${c.green.bold(thanks)}
`
console.log(emoji.emojify(msg));
process.exit(1);

581
node_modules/.bin/ts-node generated vendored
View file

@ -1,581 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.bootstrap = exports.main = void 0;
const path_1 = require("path");
const util_1 = require("util");
const Module = require("module");
let arg;
const util_2 = require("./util");
const repl_1 = require("./repl");
const index_1 = require("./index");
const node_internal_modules_cjs_helpers_1 = require("../dist-raw/node-internal-modules-cjs-helpers");
const spawn_child_1 = require("./child/spawn-child");
const configuration_1 = require("./configuration");
/**
* Main `bin` functionality.
*
* This file is split into a chain of functions (phases), each one adding to a shared state object.
* This is done so that the next function can either be invoked in-process or, if necessary, invoked in a child process.
*
* The functions are intentionally given uncreative names and left in the same order as the original code, to make a
* smaller git diff.
*/
function main(argv = process.argv.slice(2), entrypointArgs = {}) {
const args = parseArgv(argv, entrypointArgs);
const state = {
shouldUseChildProcess: false,
isInChildProcess: false,
isCli: true,
tsNodeScript: __filename,
parseArgvResult: args,
};
return bootstrap(state);
}
exports.main = main;
/** @internal */
function bootstrap(state) {
if (!state.phase2Result) {
state.phase2Result = phase2(state);
if (state.shouldUseChildProcess && !state.isInChildProcess) {
// Note: When transitioning into the child-process after `phase2`,
// the updated working directory needs to be preserved.
return (0, spawn_child_1.callInChild)(state);
}
}
if (!state.phase3Result) {
state.phase3Result = phase3(state);
if (state.shouldUseChildProcess && !state.isInChildProcess) {
// Note: When transitioning into the child-process after `phase2`,
// the updated working directory needs to be preserved.
return (0, spawn_child_1.callInChild)(state);
}
}
return phase4(state);
}
exports.bootstrap = bootstrap;
function parseArgv(argv, entrypointArgs) {
arg !== null && arg !== void 0 ? arg : (arg = require('arg'));
// HACK: technically, this function is not marked @internal so it's possible
// that libraries in the wild are doing `require('ts-node/dist/bin').main({'--transpile-only': true})`
// We can mark this function @internal in next major release.
// For now, rewrite args to avoid a breaking change.
entrypointArgs = { ...entrypointArgs };
for (const key of Object.keys(entrypointArgs)) {
entrypointArgs[key.replace(/([a-z])-([a-z])/g, (_$0, $1, $2) => `${$1}${$2.toUpperCase()}`)] = entrypointArgs[key];
}
const args = {
...entrypointArgs,
...arg({
// Node.js-like options.
'--eval': String,
'--interactive': Boolean,
'--print': Boolean,
'--require': [String],
// CLI options.
'--help': Boolean,
'--cwdMode': Boolean,
'--scriptMode': Boolean,
'--version': arg.COUNT,
'--showConfig': Boolean,
'--esm': Boolean,
// Project options.
'--cwd': String,
'--files': Boolean,
'--compiler': String,
'--compilerOptions': util_2.parse,
'--project': String,
'--ignoreDiagnostics': [String],
'--ignore': [String],
'--transpileOnly': Boolean,
'--transpiler': String,
'--swc': Boolean,
'--typeCheck': Boolean,
'--compilerHost': Boolean,
'--pretty': Boolean,
'--skipProject': Boolean,
'--skipIgnore': Boolean,
'--preferTsExts': Boolean,
'--logError': Boolean,
'--emit': Boolean,
'--scope': Boolean,
'--scopeDir': String,
'--noExperimentalReplAwait': Boolean,
'--experimentalSpecifierResolution': String,
// Aliases.
'-e': '--eval',
'-i': '--interactive',
'-p': '--print',
'-r': '--require',
'-h': '--help',
'-s': '--script-mode',
'-v': '--version',
'-T': '--transpileOnly',
'-H': '--compilerHost',
'-I': '--ignore',
'-P': '--project',
'-C': '--compiler',
'-D': '--ignoreDiagnostics',
'-O': '--compilerOptions',
'--dir': '--cwd',
// Support both tsc-style camelCase and node-style hypen-case for *all* flags
'--cwd-mode': '--cwdMode',
'--script-mode': '--scriptMode',
'--show-config': '--showConfig',
'--compiler-options': '--compilerOptions',
'--ignore-diagnostics': '--ignoreDiagnostics',
'--transpile-only': '--transpileOnly',
'--type-check': '--typeCheck',
'--compiler-host': '--compilerHost',
'--skip-project': '--skipProject',
'--skip-ignore': '--skipIgnore',
'--prefer-ts-exts': '--preferTsExts',
'--log-error': '--logError',
'--scope-dir': '--scopeDir',
'--no-experimental-repl-await': '--noExperimentalReplAwait',
'--experimental-specifier-resolution': '--experimentalSpecifierResolution',
}, {
argv,
stopAtPositional: true,
}),
};
// Only setting defaults for CLI-specific flags
// Anything passed to `register()` can be `undefined`; `create()` will apply
// defaults.
const { '--cwd': cwdArg, '--help': help = false, '--scriptMode': scriptMode, '--cwdMode': cwdMode, '--version': version = 0, '--showConfig': showConfig, '--require': argsRequire = [], '--eval': code = undefined, '--print': print = false, '--interactive': interactive = false, '--files': files, '--compiler': compiler, '--compilerOptions': compilerOptions, '--project': project, '--ignoreDiagnostics': ignoreDiagnostics, '--ignore': ignore, '--transpileOnly': transpileOnly, '--typeCheck': typeCheck, '--transpiler': transpiler, '--swc': swc, '--compilerHost': compilerHost, '--pretty': pretty, '--skipProject': skipProject, '--skipIgnore': skipIgnore, '--preferTsExts': preferTsExts, '--logError': logError, '--emit': emit, '--scope': scope = undefined, '--scopeDir': scopeDir = undefined, '--noExperimentalReplAwait': noExperimentalReplAwait, '--experimentalSpecifierResolution': experimentalSpecifierResolution, '--esm': esm, _: restArgs, } = args;
return {
// Note: argv and restArgs may be overwritten by child process
argv: process.argv,
restArgs,
cwdArg,
help,
scriptMode,
cwdMode,
version,
showConfig,
argsRequire,
code,
print,
interactive,
files,
compiler,
compilerOptions,
project,
ignoreDiagnostics,
ignore,
transpileOnly,
typeCheck,
transpiler,
swc,
compilerHost,
pretty,
skipProject,
skipIgnore,
preferTsExts,
logError,
emit,
scope,
scopeDir,
noExperimentalReplAwait,
experimentalSpecifierResolution,
esm,
};
}
function phase2(payload) {
const { help, version, cwdArg, esm } = payload.parseArgvResult;
if (help) {
console.log(`
Usage: ts-node [options] [ -e script | script.ts ] [arguments]
Options:
-e, --eval [code] Evaluate code
-p, --print Print result of \`--eval\`
-r, --require [path] Require a node module before execution
-i, --interactive Opens the REPL even if stdin does not appear to be a terminal
--esm Bootstrap with the ESM loader, enabling full ESM support
--swc Use the faster swc transpiler
-h, --help Print CLI usage
-v, --version Print module version information. -vvv to print additional information
--showConfig Print resolved configuration and exit
-T, --transpileOnly Use TypeScript's faster \`transpileModule\` or a third-party transpiler
-H, --compilerHost Use TypeScript's compiler host API
-I, --ignore [pattern] Override the path patterns to skip compilation
-P, --project [path] Path to TypeScript JSON project file
-C, --compiler [name] Specify a custom TypeScript compiler
--transpiler [name] Specify a third-party, non-typechecking transpiler
-D, --ignoreDiagnostics [code] Ignore TypeScript warnings by diagnostic code
-O, --compilerOptions [opts] JSON object to merge with compiler options
--cwd Behave as if invoked within this working directory.
--files Load \`files\`, \`include\` and \`exclude\` from \`tsconfig.json\` on startup
--pretty Use pretty diagnostic formatter (usually enabled by default)
--cwdMode Use current directory instead of <script.ts> for config resolution
--skipProject Skip reading \`tsconfig.json\`
--skipIgnore Skip \`--ignore\` checks
--emit Emit output files into \`.ts-node\` directory
--scope Scope compiler to files within \`scopeDir\`. Anything outside this directory is ignored.
--scopeDir Directory for \`--scope\`
--preferTsExts Prefer importing TypeScript files over JavaScript files
--logError Logs TypeScript errors to stderr instead of throwing exceptions
--noExperimentalReplAwait Disable top-level await in REPL. Equivalent to node's --no-experimental-repl-await
--experimentalSpecifierResolution [node|explicit]
Equivalent to node's --experimental-specifier-resolution
`);
process.exit(0);
}
// Output project information.
if (version === 1) {
console.log(`v${index_1.VERSION}`);
process.exit(0);
}
const cwd = cwdArg ? (0, path_1.resolve)(cwdArg) : process.cwd();
// If ESM is explicitly enabled through the flag, stage3 should be run in a child process
// with the ESM loaders configured.
if (esm)
payload.shouldUseChildProcess = true;
return {
cwd,
};
}
function phase3(payload) {
const { emit, files, pretty, transpileOnly, transpiler, noExperimentalReplAwait, typeCheck, swc, compilerHost, ignore, preferTsExts, logError, scriptMode, cwdMode, project, skipProject, skipIgnore, compiler, ignoreDiagnostics, compilerOptions, argsRequire, scope, scopeDir, esm, experimentalSpecifierResolution, } = payload.parseArgvResult;
const { cwd } = payload.phase2Result;
// NOTE: When we transition to a child process for ESM, the entry-point script determined
// here might not be the one used later in `phase4`. This can happen when we execute the
// original entry-point but then the process forks itself using e.g. `child_process.fork`.
// We will always use the original TS project in forked processes anyway, so it is
// expected and acceptable to retrieve the entry-point information here in `phase2`.
// See: https://github.com/TypeStrong/ts-node/issues/1812.
const { entryPointPath } = getEntryPointInfo(payload);
const preloadedConfig = (0, configuration_1.findAndReadConfig)({
cwd,
emit,
files,
pretty,
transpileOnly: (transpileOnly !== null && transpileOnly !== void 0 ? transpileOnly : transpiler != null) ? true : undefined,
experimentalReplAwait: noExperimentalReplAwait ? false : undefined,
typeCheck,
transpiler,
swc,
compilerHost,
ignore,
logError,
projectSearchDir: getProjectSearchDir(cwd, scriptMode, cwdMode, entryPointPath),
project,
skipProject,
skipIgnore,
compiler,
ignoreDiagnostics,
compilerOptions,
require: argsRequire,
scope,
scopeDir,
preferTsExts,
esm,
experimentalSpecifierResolution: experimentalSpecifierResolution,
});
// If ESM is enabled through the parsed tsconfig, stage4 should be run in a child
// process with the ESM loaders configured.
if (preloadedConfig.options.esm)
payload.shouldUseChildProcess = true;
return { preloadedConfig };
}
/**
* Determines the entry-point information from the argv and phase2 result. This
* method will be invoked in two places:
*
* 1. In phase 3 to be able to find a project from the potential entry-point script.
* 2. In phase 4 to determine the actual entry-point script.
*
* Note that we need to explicitly re-resolve the entry-point information in the final
* stage because the previous stage information could be modified when the bootstrap
* invocation transitioned into a child process for ESM.
*
* Stages before (phase 4) can and will be cached by the child process through the Brotli
* configuration and entry-point information is only reliable in the final phase. More
* details can be found in here: https://github.com/TypeStrong/ts-node/issues/1812.
*/
function getEntryPointInfo(state) {
const { code, interactive, restArgs } = state.parseArgvResult;
const { cwd } = state.phase2Result;
const { isCli } = state;
// Figure out which we are executing: piped stdin, --eval, REPL, and/or entrypoint
// This is complicated because node's behavior is complicated
// `node -e code -i ./script.js` ignores -e
const executeEval = code != null && !(interactive && restArgs.length);
const executeEntrypoint = !executeEval && restArgs.length > 0;
const executeRepl = !executeEntrypoint &&
(interactive || (process.stdin.isTTY && !executeEval));
const executeStdin = !executeEval && !executeRepl && !executeEntrypoint;
/**
* Unresolved. May point to a symlink, not realpath. May be missing file extension
* NOTE: resolution relative to cwd option (not `process.cwd()`) is legacy backwards-compat; should be changed in next major: https://github.com/TypeStrong/ts-node/issues/1834
*/
const entryPointPath = executeEntrypoint
? isCli
? (0, path_1.resolve)(cwd, restArgs[0])
: (0, path_1.resolve)(restArgs[0])
: undefined;
return {
executeEval,
executeEntrypoint,
executeRepl,
executeStdin,
entryPointPath,
};
}
function phase4(payload) {
var _a, _b, _c, _d, _e, _f, _g;
const { isInChildProcess, tsNodeScript } = payload;
const { version, showConfig, restArgs, code, print, argv } = payload.parseArgvResult;
const { cwd } = payload.phase2Result;
const { preloadedConfig } = payload.phase3Result;
const { entryPointPath, executeEntrypoint, executeEval, executeRepl, executeStdin, } = getEntryPointInfo(payload);
let evalStuff;
let replStuff;
let stdinStuff;
let evalAwarePartialHost = undefined;
if (executeEval) {
const state = new repl_1.EvalState((0, path_1.join)(cwd, repl_1.EVAL_FILENAME));
evalStuff = {
state,
repl: (0, repl_1.createRepl)({
state,
composeWithEvalAwarePartialHost: evalAwarePartialHost,
ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl: false,
}),
};
({ evalAwarePartialHost } = evalStuff.repl);
// Create a local module instance based on `cwd`.
const module = (evalStuff.module = new Module(repl_1.EVAL_NAME));
module.filename = evalStuff.state.path;
module.paths = Module._nodeModulePaths(cwd);
}
if (executeStdin) {
const state = new repl_1.EvalState((0, path_1.join)(cwd, repl_1.STDIN_FILENAME));
stdinStuff = {
state,
repl: (0, repl_1.createRepl)({
state,
composeWithEvalAwarePartialHost: evalAwarePartialHost,
ignoreDiagnosticsThatAreAnnoyingInInteractiveRepl: false,
}),
};
({ evalAwarePartialHost } = stdinStuff.repl);
// Create a local module instance based on `cwd`.
const module = (stdinStuff.module = new Module(repl_1.STDIN_NAME));
module.filename = stdinStuff.state.path;
module.paths = Module._nodeModulePaths(cwd);
}
if (executeRepl) {
const state = new repl_1.EvalState((0, path_1.join)(cwd, repl_1.REPL_FILENAME));
replStuff = {
state,
repl: (0, repl_1.createRepl)({
state,
composeWithEvalAwarePartialHost: evalAwarePartialHost,
}),
};
({ evalAwarePartialHost } = replStuff.repl);
}
// Register the TypeScript compiler instance.
const service = (0, index_1.createFromPreloadedConfig)({
// Since this struct may have been marshalled across thread or process boundaries, we must restore
// un-marshall-able values.
...preloadedConfig,
options: {
...preloadedConfig.options,
readFile: (_a = evalAwarePartialHost === null || evalAwarePartialHost === void 0 ? void 0 : evalAwarePartialHost.readFile) !== null && _a !== void 0 ? _a : undefined,
fileExists: (_b = evalAwarePartialHost === null || evalAwarePartialHost === void 0 ? void 0 : evalAwarePartialHost.fileExists) !== null && _b !== void 0 ? _b : undefined,
tsTrace: index_1.DEFAULTS.tsTrace,
},
});
(0, index_1.register)(service);
if (isInChildProcess)
require('./child/child-loader').lateBindHooks((0, index_1.createEsmHooks)(service));
// Bind REPL service to ts-node compiler service (chicken-and-egg problem)
replStuff === null || replStuff === void 0 ? void 0 : replStuff.repl.setService(service);
evalStuff === null || evalStuff === void 0 ? void 0 : evalStuff.repl.setService(service);
stdinStuff === null || stdinStuff === void 0 ? void 0 : stdinStuff.repl.setService(service);
// Output project information.
if (version === 2) {
console.log(`ts-node v${index_1.VERSION}`);
console.log(`node ${process.version}`);
console.log(`compiler v${service.ts.version}`);
process.exit(0);
}
if (version >= 3) {
console.log(`ts-node v${index_1.VERSION} ${(0, path_1.dirname)(__dirname)}`);
console.log(`node ${process.version}`);
console.log(`compiler v${service.ts.version} ${(_c = service.compilerPath) !== null && _c !== void 0 ? _c : ''}`);
process.exit(0);
}
if (showConfig) {
const ts = service.ts;
if (typeof ts.convertToTSConfig !== 'function') {
console.error('Error: --showConfig requires a typescript versions >=3.2 that support --showConfig');
process.exit(1);
}
let moduleTypes = undefined;
if (service.options.moduleTypes) {
// Assumption: this codepath requires CLI invocation, so moduleTypes must have come from a tsconfig, not API.
const showRelativeTo = (0, path_1.dirname)(service.configFilePath);
moduleTypes = {};
for (const [key, value] of Object.entries(service.options.moduleTypes)) {
moduleTypes[(0, path_1.relative)(showRelativeTo, (0, path_1.resolve)((_d = service.options.optionBasePaths) === null || _d === void 0 ? void 0 : _d.moduleTypes, key))] = value;
}
}
const json = {
['ts-node']: {
...service.options,
require: ((_e = service.options.require) === null || _e === void 0 ? void 0 : _e.length)
? service.options.require
: undefined,
moduleTypes,
optionBasePaths: undefined,
compilerOptions: undefined,
project: (_f = service.configFilePath) !== null && _f !== void 0 ? _f : service.options.project,
},
...ts.convertToTSConfig(service.config, (_g = service.configFilePath) !== null && _g !== void 0 ? _g : (0, path_1.join)(cwd, 'ts-node-implicit-tsconfig.json'), service.ts.sys),
};
console.log(
// Assumes that all configuration options which can possibly be specified via the CLI are JSON-compatible.
// If, in the future, we must log functions, for example readFile and fileExists, then we can implement a JSON
// replacer function.
JSON.stringify(json, null, 2));
process.exit(0);
}
// Prepend `ts-node` arguments to CLI for child processes.
process.execArgv.push(tsNodeScript, ...argv.slice(2, argv.length - restArgs.length));
// TODO this comes from BootstrapState
process.argv = [process.argv[1]]
.concat(executeEntrypoint ? [entryPointPath] : [])
.concat(restArgs.slice(executeEntrypoint ? 1 : 0));
// Execute the main contents (either eval, script or piped).
if (executeEntrypoint) {
if (payload.isInChildProcess &&
(0, util_2.versionGteLt)(process.versions.node, '18.6.0')) {
// HACK workaround node regression
require('../dist-raw/runmain-hack.js').run(entryPointPath);
}
else {
Module.runMain();
}
}
else {
// Note: eval and repl may both run, but never with stdin.
// If stdin runs, eval and repl will not.
if (executeEval) {
(0, node_internal_modules_cjs_helpers_1.addBuiltinLibsToObject)(global);
evalAndExitOnTsError(evalStuff.repl, evalStuff.module, code, print, 'eval');
}
if (executeRepl) {
replStuff.repl.start();
}
if (executeStdin) {
let buffer = code || '';
process.stdin.on('data', (chunk) => (buffer += chunk));
process.stdin.on('end', () => {
evalAndExitOnTsError(stdinStuff.repl, stdinStuff.module, buffer,
// `echo 123 | node -p` still prints 123
print, 'stdin');
});
}
}
}
/**
* Get project search path from args.
*/
function getProjectSearchDir(cwd, scriptMode, cwdMode, scriptPath) {
// Validate `--script-mode` / `--cwd-mode` / `--cwd` usage is correct.
if (scriptMode && cwdMode) {
throw new TypeError('--cwd-mode cannot be combined with --script-mode');
}
if (scriptMode && !scriptPath) {
throw new TypeError('--script-mode must be used with a script name, e.g. `ts-node --script-mode <script.ts>`');
}
const doScriptMode = scriptMode === true ? true : cwdMode === true ? false : !!scriptPath;
if (doScriptMode) {
// Use node's own resolution behavior to ensure we follow symlinks.
// scriptPath may omit file extension or point to a directory with or without package.json.
// This happens before we are registered, so we tell node's resolver to consider ts, tsx, and jsx files.
// In extremely rare cases, is is technically possible to resolve the wrong directory,
// because we do not yet know preferTsExts, jsx, nor allowJs.
// See also, justification why this will not happen in real-world situations:
// https://github.com/TypeStrong/ts-node/pull/1009#issuecomment-613017081
const exts = ['.js', '.jsx', '.ts', '.tsx'];
const extsTemporarilyInstalled = [];
for (const ext of exts) {
if (!(0, util_2.hasOwnProperty)(require.extensions, ext)) {
extsTemporarilyInstalled.push(ext);
require.extensions[ext] = function () { };
}
}
try {
return (0, path_1.dirname)(requireResolveNonCached(scriptPath));
}
finally {
for (const ext of extsTemporarilyInstalled) {
delete require.extensions[ext];
}
}
}
return cwd;
}
const guaranteedNonexistentDirectoryPrefix = (0, path_1.resolve)(__dirname, 'doesnotexist');
let guaranteedNonexistentDirectorySuffix = 0;
/**
* require.resolve an absolute path, tricking node into *not* caching the results.
* Necessary so that we do not pollute require.resolve cache prior to installing require.extensions
*
* Is a terrible hack, because node does not expose the necessary cache invalidation APIs
* https://stackoverflow.com/questions/59865584/how-to-invalidate-cached-require-resolve-results
*/
function requireResolveNonCached(absoluteModuleSpecifier) {
// node <= 12.1.x fallback: The trick below triggers a node bug on old versions.
// On these old versions, pollute the require cache instead. This is a deliberate
// ts-node limitation that will *rarely* manifest, and will not matter once node 12
// is end-of-life'd on 2022-04-30
const isSupportedNodeVersion = (0, util_2.versionGteLt)(process.versions.node, '12.2.0');
if (!isSupportedNodeVersion)
return require.resolve(absoluteModuleSpecifier);
const { dir, base } = (0, path_1.parse)(absoluteModuleSpecifier);
const relativeModuleSpecifier = `./${base}`;
const req = (0, util_2.createRequire)((0, path_1.join)(dir, 'imaginaryUncacheableRequireResolveScript'));
return req.resolve(relativeModuleSpecifier, {
paths: [
`${guaranteedNonexistentDirectoryPrefix}${guaranteedNonexistentDirectorySuffix++}`,
...(req.resolve.paths(relativeModuleSpecifier) || []),
],
});
}
/**
* Evaluate an [eval] or [stdin] script
*/
function evalAndExitOnTsError(replService, module, code, isPrinted, filenameAndDirname) {
let result;
(0, repl_1.setupContext)(global, module, filenameAndDirname);
try {
result = replService.evalCode(code);
}
catch (error) {
if (error instanceof index_1.TSError) {
console.error(error);
process.exit(1);
}
throw error;
}
if (isPrinted) {
console.log(typeof result === 'string'
? result
: (0, util_1.inspect)(result, { colors: process.stdout.isTTY }));
}
}
if (require.main === module) {
main();
}
//# sourceMappingURL=bin.js.map

6
node_modules/.bin/ts-node-cwd generated vendored
View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--cwdMode': true });
//# sourceMappingURL=bin-cwd.js.map

6
node_modules/.bin/ts-node-esm generated vendored
View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--esm': true });
//# sourceMappingURL=bin-esm.js.map

6
node_modules/.bin/ts-node-script generated vendored
View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--scriptMode': true });
//# sourceMappingURL=bin-script.js.map

View file

@ -1,6 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
(0, bin_1.main)(undefined, { '--transpileOnly': true });
//# sourceMappingURL=bin-transpile.js.map

7
node_modules/.bin/ts-script generated vendored
View file

@ -1,7 +0,0 @@
#!/usr/bin/env node
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const bin_1 = require("./bin");
console.warn('ts-script has been deprecated and will be removed in the next major release.', 'Please use ts-node-script instead');
(0, bin_1.main)(undefined, { '--scriptMode': true });
//# sourceMappingURL=bin-script-deprecated.js.map

2
node_modules/.bin/tsc generated vendored
View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../lib/tsc.js')

2
node_modules/.bin/tsserver generated vendored
View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../lib/tsserver.js')

81
node_modules/.bin/typechain generated vendored
View file

@ -1,81 +0,0 @@
#!/usr/bin/env node
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
const prettier = __importStar(require("prettier"));
const runTypeChain_1 = require("../typechain/runTypeChain");
const files_1 = require("../utils/files");
const glob_1 = require("../utils/glob");
const logger_1 = require("../utils/logger");
const parseArgs_1 = require("./parseArgs");
async function main() {
;
global.IS_CLI = true;
const cliConfig = (0, parseArgs_1.parseArgs)();
const cwd = process.cwd();
const files = getFilesToProcess(cwd, cliConfig.files);
if (files.length === 0) {
throw new Error('No files passed.' + '\n' + `\`${cliConfig.files}\` didn't match any input files in ${cwd}`);
}
const config = {
cwd,
target: cliConfig.target,
outDir: cliConfig.outDir,
allFiles: files,
filesToProcess: files,
inputDir: cliConfig.inputDir || (0, files_1.detectInputsRoot)(files),
prettier,
flags: {
...cliConfig.flags,
environment: undefined,
},
};
const result = await (0, runTypeChain_1.runTypeChain)(config);
// eslint-disable-next-line no-console
console.log(`Successfully generated ${result.filesGenerated} typings!`);
}
main().catch((e) => {
logger_1.logger.error('Error occured: ', e.message);
const stackTracesEnabled = process.argv.includes('--show-stack-traces');
if (stackTracesEnabled) {
logger_1.logger.error('Stack trace: ', e.stack);
}
else {
logger_1.logger.error('Run with --show-stack-traces to see the full stacktrace');
}
process.exit(1);
});
function getFilesToProcess(cwd, filesOrPattern) {
var _a;
let res = (0, glob_1.glob)(cwd, filesOrPattern);
if (res.length === 0) {
// If there are no files found, but first parameter is surrounded with single quotes, we try again without quotes
const match = (_a = filesOrPattern[0].match(/'([\s\S]*)'/)) === null || _a === void 0 ? void 0 : _a[1];
if (match)
res = (0, glob_1.glob)(cwd, [match]);
}
return res;
}
//# sourceMappingURL=cli.js.map

621
node_modules/.bin/uglifyjs generated vendored
View file

@ -1,621 +0,0 @@
#! /usr/bin/env node
// -*- js -*-
"use strict";
require("../tools/tty");
var fs = require("fs");
var info = require("../package.json");
var path = require("path");
var UglifyJS = require("../tools/node");
var skip_keys = [ "cname", "fixed", "in_arg", "inlined", "length_read", "parent_scope", "redef", "scope", "unused" ];
var truthy_keys = [ "optional", "pure", "terminal", "uses_arguments", "uses_eval", "uses_with" ];
var files = {};
var options = {};
var short_forms = {
b: "beautify",
c: "compress",
d: "define",
e: "enclose",
h: "help",
m: "mangle",
o: "output",
O: "output-opts",
p: "parse",
v: "version",
V: "version",
};
var args = process.argv.slice(2);
var paths = [];
var output, nameCache;
var specified = {};
while (args.length) {
var arg = args.shift();
if (arg[0] != "-") {
paths.push(arg);
} else if (arg == "--") {
paths = paths.concat(args);
break;
} else if (arg[1] == "-") {
process_option(arg.slice(2));
} else [].forEach.call(arg.slice(1), function(letter, index, arg) {
if (!(letter in short_forms)) fatal("invalid option -" + letter);
process_option(short_forms[letter], index + 1 < arg.length);
});
}
function process_option(name, no_value) {
specified[name] = true;
switch (name) {
case "help":
switch (read_value()) {
case "ast":
print(UglifyJS.describe_ast());
break;
case "options":
var text = [];
var toplevels = [];
var padding = "";
var defaults = UglifyJS.default_options();
for (var name in defaults) {
var option = defaults[name];
if (option && typeof option == "object") {
text.push("--" + ({
output: "beautify",
sourceMap: "source-map",
}[name] || name) + " options:");
text.push(format_object(option));
text.push("");
} else {
if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
toplevels.push([ {
keep_fargs: "keep-fargs",
keep_fnames: "keep-fnames",
nameCache: "name-cache",
}[name] || name, option ]);
}
}
toplevels.forEach(function(tokens) {
text.push("--" + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
});
print(text.join("\n"));
break;
default:
print([
"Usage: uglifyjs [files...] [options]",
"",
"Options:",
" -h, --help Print usage information.",
" `--help options` for details on available options.",
" -v, -V, --version Print version number.",
" -p, --parse <options> Specify parser options.",
" -c, --compress [options] Enable compressor/specify compressor options.",
" -m, --mangle [options] Mangle names/specify mangler options.",
" --mangle-props [options] Mangle properties/specify mangler options.",
" -b, --beautify [options] Beautify output/specify output options.",
" -O, --output-opts <options> Output options (beautify disabled).",
" -o, --output <file> Output file (default STDOUT).",
" --annotations Process and preserve comment annotations.",
" --no-annotations Ignore and discard comment annotations.",
" --comments [filter] Preserve copyright comments in the output.",
" --config-file <file> Read minify() options from JSON file.",
" -d, --define <expr>[=value] Global definitions.",
" -e, --enclose [arg[,...][:value[,...]]] Embed everything in a big function, with configurable argument(s) & value(s).",
" --expression Parse a single expression, rather than a program.",
" --ie Support non-standard Internet Explorer.",
" --keep-fargs Do not mangle/drop function arguments.",
" --keep-fnames Do not mangle/drop function names. Useful for code relying on Function.prototype.name.",
" --module Process input as ES module (implies --toplevel).",
" --no-module Process input with improved JavaScript compatibility.",
" --name-cache <file> File to hold mangled name mappings.",
" --rename Force symbol expansion.",
" --no-rename Disable symbol expansion.",
" --self Build UglifyJS as a library (implies --wrap UglifyJS)",
" --source-map [options] Enable source map/specify source map options.",
" --timings Display operations run time on STDERR.",
" --toplevel Compress and/or mangle variables in toplevel scope.",
" --v8 Support non-standard Chrome & Node.js.",
" --validate Perform validation during AST manipulations.",
" --verbose Print diagnostic messages.",
" --warn Print warning messages.",
" --webkit Support non-standard Safari/Webkit.",
" --wrap <name> Embed everything as a function with “exports” corresponding to “name” globally.",
"",
"(internal debug use only)",
" --in-situ Warning: replaces original source files with minified output.",
" --reduce-test Reduce a standalone test case (assumes cloned repository).",
].join("\n"));
}
process.exit();
case "version":
print(info.name + " " + info.version);
process.exit();
case "config-file":
var config = JSON.parse(read_file(read_value(true)));
if (config.mangle && config.mangle.properties && config.mangle.properties.regex) {
config.mangle.properties.regex = UglifyJS.parse(config.mangle.properties.regex, {
expression: true,
}).value;
}
for (var key in config) if (!(key in options)) options[key] = config[key];
break;
case "compress":
case "mangle":
options[name] = parse_js(read_value(), options[name]);
break;
case "source-map":
options.sourceMap = parse_js(read_value(), options.sourceMap);
break;
case "enclose":
options[name] = read_value();
break;
case "annotations":
case "expression":
case "ie":
case "ie8":
case "timings":
case "toplevel":
case "v8":
case "validate":
case "webkit":
options[name] = true;
break;
case "no-annotations":
options.annotations = false;
break;
case "keep-fargs":
options.keep_fargs = true;
break;
case "keep-fnames":
options.keep_fnames = true;
break;
case "wrap":
options[name] = read_value(true);
break;
case "verbose":
options.warnings = "verbose";
break;
case "warn":
if (!options.warnings) options.warnings = true;
break;
case "beautify":
options.output = parse_js(read_value(), options.output);
if (!("beautify" in options.output)) options.output.beautify = true;
break;
case "output-opts":
options.output = parse_js(read_value(true), options.output);
break;
case "comments":
if (typeof options.output != "object") options.output = {};
options.output.comments = read_value();
if (options.output.comments === true) options.output.comments = "some";
break;
case "define":
if (typeof options.compress != "object") options.compress = {};
options.compress.global_defs = parse_js(read_value(true), options.compress.global_defs, "define");
break;
case "mangle-props":
if (typeof options.mangle != "object") options.mangle = {};
options.mangle.properties = parse_js(read_value(), options.mangle.properties);
break;
case "module":
options.module = true;
break;
case "no-module":
options.module = false;
break;
case "name-cache":
nameCache = read_value(true);
options.nameCache = JSON.parse(read_file(nameCache, "{}"));
break;
case "output":
output = read_value(true);
break;
case "parse":
options.parse = parse_js(read_value(true), options.parse);
break;
case "rename":
options.rename = true;
break;
case "no-rename":
options.rename = false;
break;
case "in-situ":
case "reduce-test":
case "self":
break;
default:
fatal("invalid option --" + name);
}
function read_value(required) {
if (no_value || !args.length || args[0][0] == "-") {
if (required) fatal("missing option argument for --" + name);
return true;
}
return args.shift();
}
}
if (!output && options.sourceMap && options.sourceMap.url != "inline") fatal("cannot write source map to STDOUT");
if (specified["beautify"] && specified["output-opts"]) fatal("--beautify cannot be used with --output-opts");
[ "compress", "mangle" ].forEach(function(name) {
if (!(name in options)) options[name] = false;
});
if (/^ast|spidermonkey$/.test(output)) {
if (typeof options.output != "object") options.output = {};
options.output.ast = true;
options.output.code = false;
}
if (options.parse && (options.parse.acorn || options.parse.spidermonkey)
&& options.sourceMap && options.sourceMap.content == "inline") {
fatal("inline source map only works with built-in parser");
}
if (options.warnings) {
UglifyJS.AST_Node.log_function(print_error, options.warnings == "verbose");
delete options.warnings;
}
var convert_path = function(name) {
return name;
};
if (typeof options.sourceMap == "object" && "base" in options.sourceMap) {
convert_path = function() {
var base = options.sourceMap.base;
delete options.sourceMap.base;
return function(name) {
return path.relative(base, name);
};
}();
}
if (specified["self"]) {
if (paths.length) UglifyJS.AST_Node.warn("Ignoring input files since --self was passed");
if (!options.wrap) options.wrap = "UglifyJS";
paths = UglifyJS.FILES;
} else if (paths.length) {
paths = simple_glob(paths);
}
if (specified["in-situ"]) {
if (output && output != "spidermonkey" || specified["reduce-test"] || specified["self"]) {
fatal("incompatible options specified");
}
paths.forEach(function(name) {
print(name);
if (/^ast|spidermonkey$/.test(name)) fatal("invalid file name specified");
files = {};
files[convert_path(name)] = read_file(name);
output = name;
run();
});
} else if (paths.length) {
paths.forEach(function(name) {
files[convert_path(name)] = read_file(name);
});
run();
} else {
var timerId = process.stdin.isTTY && process.argv.length < 3 && setTimeout(function() {
print_error("Waiting for input... (use `--help` to print usage information)");
}, 1500);
var chunks = [];
process.stdin.setEncoding("utf8");
process.stdin.once("data", function() {
clearTimeout(timerId);
}).on("data", process.stdin.isTTY ? function(chunk) {
// emulate console input termination via Ctrl+D / Ctrl+Z
var match = /[\x04\x1a]\r?\n?$/.exec(chunk);
if (match) {
chunks.push(chunk.slice(0, -match[0].length));
process.stdin.pause();
process.stdin.emit("end");
} else {
chunks.push(chunk);
}
} : function(chunk) {
chunks.push(chunk);
}).once("end", function() {
files = { STDIN: chunks.join("") };
run();
});
process.stdin.resume();
}
function convert_ast(fn) {
return UglifyJS.AST_Node.from_mozilla_ast(Object.keys(files).reduce(fn, null));
}
function run() {
var content = options.sourceMap && options.sourceMap.content;
if (content && content != "inline") {
UglifyJS.AST_Node.info("Using input source map: {content}", {
content : content,
});
options.sourceMap.content = read_file(content, content);
}
try {
if (options.parse) {
if (options.parse.acorn) {
var annotations = Object.create(null);
files = convert_ast(function(toplevel, name) {
var content = files[name];
var list = annotations[name] = [];
var prev = -1;
return require("acorn").parse(content, {
allowHashBang: true,
ecmaVersion: "latest",
locations: true,
onComment: function(block, text, start, end) {
var match = /[@#]__PURE__/.exec(text);
if (!match) {
if (start != prev) return;
match = [ list[prev] ];
}
while (/\s/.test(content[end])) end++;
list[end] = match[0];
prev = end;
},
preserveParens: true,
program: toplevel,
sourceFile: name,
sourceType: "module",
});
});
files.walk(new UglifyJS.TreeWalker(function(node) {
if (!(node instanceof UglifyJS.AST_Call)) return;
var list = annotations[node.start.file];
var pure = list[node.start.pos];
if (!pure) {
var tokens = node.start.parens;
if (tokens) for (var i = 0; !pure && i < tokens.length; i++) {
pure = list[tokens[i].pos];
}
}
if (pure) node.pure = pure;
}));
} else if (options.parse.spidermonkey) {
files = convert_ast(function(toplevel, name) {
var obj = JSON.parse(files[name]);
if (!toplevel) return obj;
toplevel.body = toplevel.body.concat(obj.body);
return toplevel;
});
}
}
} catch (ex) {
fatal(ex);
}
var result;
if (specified["reduce-test"]) {
// load on demand - assumes cloned repository
var reduce_test = require("../test/reduce");
if (Object.keys(files).length != 1) fatal("can only test on a single file");
result = reduce_test(files[Object.keys(files)[0]], options, {
log: print_error,
verbose: true,
});
} else {
result = UglifyJS.minify(files, options);
}
if (result.error) {
var ex = result.error;
if (ex.name == "SyntaxError") {
print_error("Parse error at " + ex.filename + ":" + ex.line + "," + ex.col);
var file = files[ex.filename];
if (file) {
var col = ex.col;
var lines = file.split(/\r?\n/);
var line = lines[ex.line - 1];
if (!line && !col) {
line = lines[ex.line - 2];
col = line.length;
}
if (line) {
var limit = 70;
if (col > limit) {
line = line.slice(col - limit);
col = limit;
}
print_error(line.slice(0, 80));
print_error(line.slice(0, col).replace(/\S/g, " ") + "^");
}
}
} else if (ex.defs) {
print_error("Supported options:");
print_error(format_object(ex.defs));
}
fatal(ex);
} else if (output == "ast") {
if (!options.compress && !options.mangle) {
var toplevel = result.ast;
if (!(toplevel instanceof UglifyJS.AST_Toplevel)) {
if (!(toplevel instanceof UglifyJS.AST_Statement)) toplevel = new UglifyJS.AST_SimpleStatement({
body: toplevel,
});
toplevel = new UglifyJS.AST_Toplevel({
body: [ toplevel ],
});
}
toplevel.figure_out_scope({});
}
print(JSON.stringify(result.ast, function(key, value) {
if (value) switch (key) {
case "enclosed":
return value.length ? value.map(symdef) : undefined;
case "functions":
case "globals":
case "variables":
return value.size() ? value.map(symdef) : undefined;
case "thedef":
return symdef(value);
}
if (skip_property(key, value)) return;
if (value instanceof UglifyJS.AST_Token) return;
if (value instanceof UglifyJS.Dictionary) return;
if (value instanceof UglifyJS.AST_Node) {
var result = {
_class: "AST_" + value.TYPE
};
value.CTOR.PROPS.forEach(function(prop) {
result[prop] = value[prop];
});
return result;
}
return value;
}, 2));
} else if (output == "spidermonkey") {
print(JSON.stringify(result.ast.to_mozilla_ast(), null, 2));
} else if (output) {
var code;
if (result.ast) {
var opts = {};
for (var name in options.output) {
if (!/^ast|code$/.test(name)) opts[name] = options.output[name];
}
code = UglifyJS.AST_Node.from_mozilla_ast(result.ast.to_mozilla_ast()).print_to_string(opts);
} else {
code = result.code;
}
fs.writeFileSync(output, code);
if (result.map) fs.writeFileSync(output + ".map", result.map);
} else {
print(result.code);
}
if (nameCache) fs.writeFileSync(nameCache, JSON.stringify(options.nameCache));
if (result.timings) for (var phase in result.timings) {
print_error("- " + phase + ": " + result.timings[phase].toFixed(3) + "s");
}
}
function fatal(message) {
if (message instanceof Error) {
message = message.stack.replace(/^\S*?Error:/, "ERROR:")
} else {
message = "ERROR: " + message;
}
print_error(message);
process.exit(1);
}
// A file glob function that only supports "*" and "?" wildcards in the basename.
// Example: "foo/bar/*baz??.*.js"
// Argument `paths` must be an array of strings.
// Returns an array of strings. Garbage in, garbage out.
function simple_glob(paths) {
return paths.reduce(function(paths, glob) {
if (/\*|\?/.test(glob)) {
var dir = path.dirname(glob);
try {
var entries = fs.readdirSync(dir).filter(function(name) {
try {
return fs.statSync(path.join(dir, name)).isFile();
} catch (ex) {
return false;
}
});
} catch (ex) {}
if (entries) {
var pattern = "^" + path.basename(glob)
.replace(/[.+^$[\]\\(){}]/g, "\\$&")
.replace(/\*/g, "[^/\\\\]*")
.replace(/\?/g, "[^/\\\\]") + "$";
var mod = process.platform === "win32" ? "i" : "";
var rx = new RegExp(pattern, mod);
var results = entries.filter(function(name) {
return rx.test(name);
}).sort().map(function(name) {
return path.join(dir, name);
});
if (results.length) {
[].push.apply(paths, results);
return paths;
}
}
}
paths.push(glob);
return paths;
}, []);
}
function read_file(path, default_value) {
try {
return fs.readFileSync(path, "utf8");
} catch (ex) {
if (ex.code == "ENOENT" && default_value != null) return default_value;
fatal(ex);
}
}
function parse_js(value, options, flag) {
if (!options || typeof options != "object") options = Object.create(null);
if (typeof value == "string") try {
UglifyJS.parse(value, {
expression: true
}).walk(new UglifyJS.TreeWalker(function(node) {
if (node instanceof UglifyJS.AST_Assign) {
var name = node.left.print_to_string();
var value = node.right;
if (flag) {
options[name] = value;
} else if (value instanceof UglifyJS.AST_Array) {
options[name] = value.elements.map(to_string);
} else {
options[name] = to_string(value);
}
return true;
}
if (node instanceof UglifyJS.AST_Symbol || node instanceof UglifyJS.AST_PropAccess) {
var name = node.print_to_string();
options[name] = true;
return true;
}
if (!(node instanceof UglifyJS.AST_Sequence)) throw node;
function to_string(value) {
return value instanceof UglifyJS.AST_Constant ? value.value : value.print_to_string({
quote_keys: true
});
}
}));
} catch (ex) {
if (flag) {
fatal("cannot parse arguments for '" + flag + "': " + value);
} else {
options[value] = null;
}
}
return options;
}
function skip_property(key, value) {
return skip_keys.indexOf(key) >= 0
// only skip truthy_keys if their value is falsy
|| truthy_keys.indexOf(key) >= 0 && !value;
}
function symdef(def) {
var ret = (1e6 + def.id) + " " + def.name;
if (def.mangled_name) ret += " " + def.mangled_name;
return ret;
}
function format_object(obj) {
var lines = [];
var padding = "";
Object.keys(obj).map(function(name) {
if (padding.length < name.length) padding = Array(name.length + 1).join(" ");
return [ name, JSON.stringify(obj[name]) ];
}).forEach(function(tokens) {
lines.push(" " + tokens[0] + padding.slice(tokens[0].length - 2) + tokens[1]);
});
return lines.join("\n");
}
function print_error(msg) {
process.stderr.write(msg);
process.stderr.write("\n");
}
function print(txt) {
process.stdout.write(txt);
process.stdout.write("\n");
}

2
node_modules/.bin/uuid generated vendored
View file

@ -1,2 +0,0 @@
#!/usr/bin/env node
require('../uuid-bin');

52
node_modules/.bin/which generated vendored
View file

@ -1,52 +0,0 @@
#!/usr/bin/env node
var which = require("../")
if (process.argv.length < 3)
usage()
function usage () {
console.error('usage: which [-as] program ...')
process.exit(1)
}
var all = false
var silent = false
var dashdash = false
var args = process.argv.slice(2).filter(function (arg) {
if (dashdash || !/^-/.test(arg))
return true
if (arg === '--') {
dashdash = true
return false
}
var flags = arg.substr(1).split('')
for (var f = 0; f < flags.length; f++) {
var flag = flags[f]
switch (flag) {
case 's':
silent = true
break
case 'a':
all = true
break
default:
console.error('which: illegal option -- ' + flag)
usage()
}
}
return false
})
process.exit(args.reduce(function (pv, current) {
try {
var f = which.sync(current, { all: all })
if (all)
f = f.join('\n')
if (!silent)
console.log(f)
return pv;
} catch (e) {
return 1;
}
}, 0))

96
node_modules/.bin/write-markdown generated vendored
View file

@ -1,96 +0,0 @@
#!/usr/bin/env node
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var parse_1 = require("./parse");
var path_1 = require("path");
var fs_1 = require("fs");
var helpers_1 = require("./helpers");
var write_markdown_constants_1 = require("./write-markdown.constants");
var string_format_1 = __importDefault(require("string-format"));
var chalk_1 = __importDefault(require("chalk"));
function writeMarkdown() {
return __awaiter(this, void 0, void 0, function () {
var args, markdownPath, markdownFileContent, usageGuides, modifiedFileContent, action, contentMatch, relativePath;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
args = parse_1.parse(write_markdown_constants_1.argumentConfig, write_markdown_constants_1.parseOptions);
markdownPath = path_1.resolve(args.markdownPath);
console.log("Loading existing file from '" + chalk_1.default.blue(markdownPath) + "'");
markdownFileContent = fs_1.readFileSync(markdownPath).toString();
usageGuides = helpers_1.generateUsageGuides(args);
modifiedFileContent = markdownFileContent;
if (usageGuides != null) {
modifiedFileContent = helpers_1.addContent(markdownFileContent, usageGuides, args);
if (!args.skipFooter) {
modifiedFileContent = helpers_1.addCommandLineArgsFooter(modifiedFileContent);
}
}
return [4 /*yield*/, helpers_1.insertCode({ fileContent: modifiedFileContent, filePath: markdownPath }, args)];
case 1:
modifiedFileContent = _a.sent();
action = args.verify === true ? "verify" : "write";
contentMatch = markdownFileContent === modifiedFileContent ? "match" : "nonMatch";
relativePath = path_1.relative(process.cwd(), markdownPath);
switch (action + "_" + contentMatch) {
case 'verify_match':
console.log(chalk_1.default.green("'" + relativePath + "' content as expected. No update required."));
break;
case 'verify_nonMatch':
console.warn(chalk_1.default.yellow(string_format_1.default(args.verifyMessage || "'" + relativePath + "' file out of date. Rerun write-markdown to update.", {
fileName: relativePath,
})));
return [2 /*return*/, process.exit(1)];
case 'write_match':
console.log(chalk_1.default.blue("'" + relativePath + "' content not modified, not writing to file."));
break;
case 'write_nonMatch':
console.log("Writing modified file to '" + chalk_1.default.blue(relativePath) + "'");
fs_1.writeFileSync(relativePath, modifiedFileContent);
break;
}
return [2 /*return*/];
}
});
});
}
writeMarkdown();

7796
node_modules/.package-lock.json generated vendored

File diff suppressed because it is too large Load diff

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) 2021 Andrew Raffensperger
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.

View file

@ -1,206 +0,0 @@
# ens-normalize.js
0-dependancy [Ethereum Name Service](https://ens.domains/) (ENS) Name Normalizer.
* 🏛️ Follows [ENSIP-15: ENS Name Normalization Standard](https://docs.ens.domains/ens-improvement-proposals/ensip-15-normalization-standard)
* Other implementations:
* Python — [namehash/ens-normalize-python](https://github.com/namehash/ens-normalize-python)
* C# — [adraffy/ENSNormalize.cs](https://github.com/adraffy/ENSNormalize.cs)
* Java — [adraffy/ENSNormalize.java](https://github.com/adraffy/ENSNormalize.java)
* Javascript — [ensdomains/eth-ens-namehash](https://github.com/ensdomains/eth-ens-namehash)
* [Breakdown Reports from ENSIP-1](https://adraffy.github.io/ens-norm-tests/test-breakdown/output-20230226/)
* ✅️ Passes **100%** [ENSIP-15 Validation Tests](https://adraffy.github.io/ens-normalize.js/test/validate.html)
* ✅️ Passes **100%** [Unicode Normalization Tests](https://adraffy.github.io/ens-normalize.js/test/report-nf.html)
* Minified File Sizes:
* [`28KB`](./dist/index-xnf.min.js) — native `NFC` via [nf-native.js](./src/nf-native.js) using `String.normalize()` ⚠️
* [`37KB` **Default**](./dist/index.min.js) — custom `NFC` via [nf.js](./src/nf.js)
* [`43KB`](./dist/all.min.js) *Everything!* — custom `NFC` + sub-libraries: [parts.js](./src/parts.js), [utils.js](./src/utils.js)
* Included Apps:
* [**Resolver Demo**](https://adraffy.github.io/ens-normalize.js/test/resolver.html) ⭐
* [Supported Emoji](https://adraffy.github.io/ens-normalize.js/test/emoji.html)
* [Character Viewer](https://adraffy.github.io/ens-normalize.js/test/chars.html)
* [Confused Explainer](https://adraffy.github.io/ens-normalize.js/test/confused.html)
* Related Projects:
* [Recent .eth Registrations](https://raffy.antistupid.com/eth/ens-regs.html) • [.eth Renews](https://raffy.antistupid.com/eth/ens-renews.html)
* [.eth Expirations](https://raffy.antistupid.com/eth/ens-exp.html)
* [Emoji Frequency Explorer](https://raffy.antistupid.com/eth/ens-emoji-freq.html)
* [ENS+NFT Matcher](https://raffy.antistupid.com/eth/ens-nft-matcher.html)
* [Batch Resolver](https://raffy.antistupid.com/eth/ens-batch-resolver.html)
* [Label Database](https://github.com/adraffy/ens-labels/) • [Labelhash⁻¹](https://adraffy.github.io/ens-labels/demo.html)
* [adraffy/punycode.js](https://github.com/adraffy/punycode.js/) • [Punycode Coder](https://adraffy.github.io/punycode.js/test/demo.html)
* [adraffy/keccak.js](https://github.com/adraffy/keccak.js/) • [Keccak Hasher](https://adraffy.github.io/keccak.js/test/demo.html)
* [adraffy/emoji.js](https://github.com/adraffy/emoji.js/) • [Emoji Parser](https://adraffy.github.io/emoji.js/test/demo.html)
```js
import {ens_normalize} from '@adraffy/ens-normalize'; // or require()
// npm i @adraffy/ens-normalize
// browser: https://cdn.jsdelivr.net/npm/@adraffy/ens-normalize@latest/dist/index.min.mjs (or .cjs)
// *** ALL errors thrown by this library are safe to print ***
// - characters are shown as {HEX} if should_escape()
// - potentially different bidi directions inside "quotes"
// - 200E is used near "quotes" to prevent spillover
// - an "error type" can be extracted by slicing up to the first (:)
// - labels are middle-truncated with ellipsis (…) at 63 cps
// string -> string
// throws on invalid names
// output ready for namehash
let normalized = ens_normalize('RaFFY🚴.eTh');
// => "raffy🚴♂.eth"
// note: does not enforce .eth registrar 3-character minimum
```
Format names with fully-qualified emoji:
```js
// works like ens_normalize()
// output ready for display
let pretty = ens_beautify('1⃣2⃣.eth');
// => "1⃣2⃣.eth"
// note: normalization is unchanged:
// ens_normalize(ens_beautify(x)) == ens_normalize(x)
```
Normalize name fragments for [substring search](./test/fragment.js):
```js
// these fragments fail ens_normalize()
// but will normalize fine as fragments
let frag1 = ens_normalize_fragment('AB--'); // expected error: label ext
let frag2 = ens_normalize_fragment('\u{303}'); // expected error: leading cm
let frag3 = ens_normalize_fragment('οо'); // expected error: mixture
```
Input-based tokenization:
```js
// string -> Token[]
// never throws
let tokens = ens_tokenize('_R💩\u{FE0F}a\u{FE0F}\u{304}\u{AD}./');
// [
// { type: 'valid', cp: [ 95 ] }, // valid (as-is)
// {
// type: 'mapped',
// cp: 82, // input
// cps: [ 114 ] // output
// },
// {
// type: 'emoji',
// input: Emoji(2) [ 128169, 65039 ], // input
// emoji: [ 128169, 65039 ], // fully-qualified
// cps: Emoji(1) [ 128169 ] // output (normalized)
// },
// {
// type: 'nfc',
// input: [ 97, 772 ], // input (before nfc)
// tokens0: [ // tokens (before nfc)
// { type: 'valid', cps: [ 97 ] },
// { type: 'ignored', cp: 65039 },
// { type: 'valid', cps: [ 772 ] }
// ],
// cps: [ 257 ], // output (after nfc)
// tokens: [ // tokens (after nfc)
// { type: 'valid', cps: [ 257 ] }
// ]
// },
// { type: 'ignored', cp: 173 },
// { type: 'stop', cp: 46 },
// { type: 'disallowed', cp: 47 }
// ]
// note: if name is normalizable, then:
// ens_normalize(ens_tokenize(name).map(token => {
// ** convert valid/mapped/nfc/stop to string **
// }).join('')) == ens_normalize(name)
```
Output-based tokenization:
```js
// string -> Label[]
// never throws
let labels = ens_split('💩Raffy.eth_');
// [
// {
// input: [ 128169, 82, 97, 102, 102, 121 ],
// offset: 0, // index of codepoint, not substring index!
// // (corresponding length can be inferred from input)
// tokens: [
// Emoji(2) [ 128169, 65039 ], // emoji
// [ 114, 97, 102, 102, 121 ] // nfc-text
// ],
// output: [ 128169, 114, 97, 102, 102, 121 ],
// emoji: true,
// type: 'Latin'
// },
// {
// input: [ 101, 116, 104, 95 ],
// offset: 7,
// tokens: [ [ 101, 116, 104, 95 ] ],
// output: [ 101, 116, 104, 95 ],
// error: Error('underscore allowed only at start')
// }
// ]
```
Generate a sorted array of (beautified) supported emoji codepoints:
```js
// () -> number[][]
let emojis = ens_emoji();
// [
// [ 2764 ],
// [ 128169, 65039 ],
// [ 128105, 127997, 8205, 9877, 65039 ],
// ...
// ]
```
Determine if a character shouldn't be printed directly:
```js
// number -> bool
should_escape(0x202E); // eg. RIGHT-TO-LEFT OVERRIDE => true
```
Determine if a character is a combining mark:
```js
// number -> bool
is_combining_mark(0x20E3); // eg. COMBINING ENCLOSING KEYCAP => true
```
Format codepoints as print-safe string:
```js
// number[] -> string
safe_str_from_cps([0x300, 0, 32, 97]); // "◌̀{00} a"
safe_str_from_cps(Array(100).fill(97), 4); // "aa…aa" => middle-truncated
```
## Build
* `git clone` this repo, then `npm install`
* Follow instructions in [/derive/](./derive/) to generate data files
* `npm run derive`
* [spec.json](./derive/output/spec.json)
* [nf.json](./derive/output/nf.json)
* [nf-tests.json](./derive/output/nf-tests.json)
* `npm run make` — compress data files from [/derive/output/](./derive/output/)
* [include-ens.js](./src/include-ens.js)
* [include-nf.js](./src/include-nf.js)
* [include-versions.js](./src/include-versions.js)
* Follow instructions in [/validate/](./validate/) to generate validation tests
* `npm run validate`
* [tests.json](./validate/tests.json)
* `npm run test` — perform validation tests
* `npm run build` create [/dist/](./dist/)
* `npm run rebuild` — run all the commands above
* `npm run order` — create optimal group ordering and rebuild again
### Publishing to NPM
This project uses `.js` instead of `.mjs` so [package.json](./package.json) uses `type: module`. To avoid bundling issues, `type` is [dropped during packing](./src/prepost.js). `pre/post` hooks aren't used because they're buggy.
* `npm run pack` instead of `npm pack`
* `npm run pub` instead of `npm publish`
## Security
* [Build](#build) and compare against [include-versions.js](./src/include-versions.js)
* `spec_hash` — SHA-256 of [spec.json](./derive/output/spec.json) bytes
* `base64_ens_hash` — SHA-256 of [include-ens.js](./src/include-ens.js) base64 literal
* `base64_nf_hash` — SHA-256 of [include-nf.js](./src/include-nf.js) base64 literal

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,59 +0,0 @@
interface DisallowedToken {
type: 'disallowed';
cp: number;
}
interface IgnoredToken {
type: 'ignored';
cp: number;
}
interface ValidToken {
type: 'valid';
cps: number[];
}
interface MappedToken {
type: 'mapped';
cp: number;
cps: number[];
}
type TextToken = DisallowedToken | IgnoredToken | ValidToken | MappedToken;
interface EmojiToken {
type: 'emoji';
input: number[];
emoji: number[];
cps: number[];
}
interface NFCToken {
type: 'nfc';
input: number[];
cps: number[];
tokens: TextToken[];
}
interface StopToken {
type: 'stop';
}
type Token = TextToken | EmojiToken | NFCToken | StopToken;
interface Label {
input: number[];
offset: number;
error?: Error;
tokens?: number[][];
output?: number[];
emoji?: boolean;
type?: string;
}
export function ens_normalize(name: string): string;
export function ens_normalize_fragment(frag: string, decompose?: boolean): string;
export function ens_beautify(name: string): string;
export function ens_tokenize(name: string, options?: {nf?: boolean}): Token[];
export function ens_split(name: string, preserve_emoji?: boolean): Label[];
export function ens_emoji(): number[][];
export function should_escape(cp: number): boolean;
export function is_combining_mark(cp: number): boolean;
export function safe_str_from_cps(cps: number[]): string;
export function nfd(cps: number[]): number[];
export function nfc(cps: number[]): number[];

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -1,76 +0,0 @@
{
"name": "@adraffy/ens-normalize",
"version": "1.10.1",
"description": "Ethereum Name Service (ENS) Name Normalizer",
"keywords": [
"ENS",
"ENSIP-1",
"ENSIP-15",
"Ethereum",
"UTS-46",
"UTS-51",
"IDNA",
"Name",
"Normalize",
"Normalization",
"NFC",
"NFD"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"default": "./dist/index.cjs"
},
"./xnf": {
"types": "./dist/index.d.ts",
"import": "./dist/index-xnf.mjs",
"default": "./dist/index-xnf.cjs"
}
},
"types": "./dist/index.d.ts",
"typesVersions": {
"*": {
"*": [
"./dist/index.d.ts"
]
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"files": [
"./dist"
],
"repository": {
"type": "git",
"url": "git+https://github.com/adraffy/ens-normalize.js.git"
},
"license": "MIT",
"bugs": {
"url": "https://github.com/adraffy/ens-normalize.js/issues"
},
"homepage": "https://github.com/adraffy/ens-normalize.js#readme",
"author": {
"name": "raffy.eth",
"email": "raffy@me.com",
"url": "http://raffy.antistupid.com"
},
"scripts": {
"unicode": "node derive/download.js",
"labels": "node validate/download-labels.js",
"derive": "node derive/make.js",
"make": "node src/make.js",
"validate": "node validate/make.js",
"test": "node test/coder.js && node test/nf.js && node test/validate.js && node test/init.js",
"build": "rollup -c",
"rebuild": "npm run derive && npm run make && npm run validate && npm run test && npm run build",
"order": "node validate/dump-group-order.js save && npm run rebuild",
"pack": "node ./src/prepost.js pack",
"pub": "node ./src/prepost.js publish"
},
"devDependencies": {
"@rollup/plugin-alias": "^5.0.0",
"@rollup/plugin-terser": "^0.4.0",
"rollup": "^3.24.1"
}
}

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2014 Evan Wallace
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.

View file

@ -1,289 +0,0 @@
# Source Map Support
[![NPM version](https://img.shields.io/npm/v/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support)
[![NPM downloads](https://img.shields.io/npm/dm/@cspotcode/source-map-support.svg?style=flat)](https://npmjs.org/package/@cspotcode/source-map-support)
[![Build status](https://img.shields.io/github/workflow/status/cspotcode/node-source-map-support/Continuous%20Integration)](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22)
This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
## Installation and Usage
#### Node support
```
$ npm install @cspotcode/source-map-support
```
Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
```
//# sourceMappingURL=path/to/source.map
```
If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
The path should either be absolute or relative to the compiled file.
From here you have two options.
##### CLI Usage
```bash
node -r @cspotcode/source-map-support/register compiled.js
# Or to enable hookRequire
node -r @cspotcode/source-map-support/register-hook-require compiled.js
```
##### Programmatic Usage
Put the following line at the top of the compiled file.
```js
require('@cspotcode/source-map-support').install();
```
It is also possible to install the source map support directly by
requiring the `register` module which can be handy with ES6:
```js
import '@cspotcode/source-map-support/register'
// Instead of:
import sourceMapSupport from '@cspotcode/source-map-support'
sourceMapSupport.install()
```
Note: if you're using babel-register, it includes source-map-support already.
It is also very useful with Mocha:
```
$ mocha --require @cspotcode/source-map-support/register tests/
```
#### Browser support
This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
```html
<script src="browser-source-map-support.js"></script>
<script>sourceMapSupport.install();</script>
```
This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
```html
<script>
define(['browser-source-map-support'], function(sourceMapSupport) {
sourceMapSupport.install();
});
</script>
```
## Options
This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
```js
require('@cspotcode/source-map-support').install({
handleUncaughtExceptions: false
});
```
This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
```js
require('@cspotcode/source-map-support').install({
retrieveSourceMap: function(source) {
if (source === 'compiled.js') {
return {
url: 'original.js',
map: fs.readFileSync('compiled.js.map', 'utf8')
};
}
return null;
}
});
```
The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
```js
require('@cspotcode/source-map-support').install({
environment: 'node'
});
```
To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
```js
require('@cspotcode/source-map-support').install({
hookRequire: true
});
```
This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
## Demos
#### Basic Demo
original.js:
```js
throw new Error('test'); // This is the original code
```
compiled.js:
```js
require('@cspotcode/source-map-support').install();
throw new Error('test'); // This is the compiled code
// The next line defines the sourceMapping.
//# sourceMappingURL=compiled.js.map
```
compiled.js.map:
```json
{
"version": 3,
"file": "compiled.js",
"sources": ["original.js"],
"names": [],
"mappings": ";;AAAA,MAAM,IAAI"
}
```
Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
```
$ node compiled.js
original.js:1
throw new Error('test'); // This is the original code
^
Error: test
at Object.<anonymous> (original.js:1:7)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### TypeScript Demo
demo.ts:
```typescript
declare function require(name: string);
require('@cspotcode/source-map-support').install();
class Foo {
constructor() { this.bar(); }
bar() { throw new Error('this is a demo'); }
}
new Foo();
```
Compile and run the file using the TypeScript compiler from the terminal:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base:
```
$ npm install source-map-support typescript
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
$ node -r source-map-support/register demo.js
demo.ts:5
bar() { throw new Error('this is a demo'); }
^
Error: this is a demo
at Foo.bar (demo.ts:5:17)
at new Foo (demo.ts:4:24)
at Object.<anonymous> (demo.ts:7:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
```
#### CoffeeScript Demo
demo.coffee:
```coffee
require('@cspotcode/source-map-support').install()
foo = ->
bar = -> throw new Error 'this is a demo'
bar()
foo()
```
Compile and run the file using the CoffeeScript compiler from the terminal:
```sh
$ npm install @cspotcode/source-map-support coffeescript
$ node_modules/.bin/coffee --map --compile demo.coffee
$ node demo.js
demo.coffee:3
bar = -> throw new Error 'this is a demo'
^
Error: this is a demo
at bar (demo.coffee:3:22)
at foo (demo.coffee:4:3)
at Object.<anonymous> (demo.coffee:5:1)
at Object.<anonymous> (demo.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
```
## Tests
This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
* Build the tests using `build.js`
* Launch the HTTP server (`npm run serve-tests`) and visit
* http://127.0.0.1:1336/amd-test
* http://127.0.0.1:1336/browser-test
* http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
## License
This code is available under the [MIT license](http://opensource.org/licenses/MIT).

View file

@ -1,114 +0,0 @@
/*
* Support for source maps in V8 stack traces
* https://github.com/evanw/node-source-map-support
*/
/*
The buffer module from node.js, for the browser.
@author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
license MIT
*/
(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;m<A.length;m++)p(A[m]);return p})({1:[function(C,
J,A){R=C("./source-map-support")},{"./source-map-support":21}],2:[function(C,J,A){(function(e){function p(m){m=m.charCodeAt(0);if(43===m)return 62;if(47===m)return 63;if(48>m)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0<m.length%4)throw Error("Invalid string. Length must be a multiple of 4");var c=m.length;var l="="===m.charAt(c-2)?2:"="===m.charAt(c-1)?1:0;var q=
new t(3*m.length/4-l);var r=0<l?m.length-4:m.length;var k=0;for(c=0;c<r;c+=4){var u=p(m.charAt(c))<<18|p(m.charAt(c+1))<<12|p(m.charAt(c+2))<<6|p(m.charAt(c+3));f((u&16711680)>>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q<l;q+=3){var r=(m[q]<<16)+(m[q+1]<<8)+m[q+2];r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>
18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+
m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"===
typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding');
return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0<a?a>>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string");
if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;b<y;b++)I[b]=a.readUInt8(b);else for(b=0;b<y;b++)I[b]=(a[b]%256+256)%256;else if("string"===w)I.write(a,
0,b);else if("number"===w&&!e.TYPED_ARRAY_SUPPORT&&!h)for(b=0;b<y;b++)I[b]=0}return I}function p(a,b,h){var w="";for(h=Math.min(a.length,h);b<h;b++)w+=String.fromCharCode(a[b]);return w}function t(a,b,h){if(0!==a%1||0>a)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||b<I)throw new TypeError("value is out of bounds");if(h+w>a.length)throw new TypeError("index out of range");
}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y<I;y++)a[h+y]=(b&255<<8*(w?y:1-y))>>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y<I;y++)a[h+y]=b>>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||b<I)throw new TypeError("value is out of bounds");if(h+w>a.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a,
b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h<a.length;h++){var w=a.charCodeAt(h);if(127>=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y<w.length;y++)b.push(parseInt(w[y],16))}}return b}function u(a){for(var b=[],h=0;h<a.length;h++)b.push(a.charCodeAt(h)&255);return b}function d(a,b,h,w,y){y&&(w-=w%y);for(y=0;y<w&&!(y+h>=b.length||y>=a.length);y++)b[y+
h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null==
a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y<I&&a[y]===b[y];y++);y!==I&&(h=a[y],w=b[y]);return h<w?-1:w<h?1:0};e.isEncoding=function(a){switch(String(a).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;default:return!1}};e.concat=function(a,b){if(!z(a))throw new TypeError("Usage: Buffer.concat(list[, length])");
if(0===a.length)return new e(0);if(1===a.length)return a[0];var h;if(void 0===b)for(h=b=0;h<a.length;h++)b+=a[h].length;var w=new e(b),y=0;for(h=0;h<a.length;h++){var I=a[h];I.copy(w,y);y+=I.length}return w};e.byteLength=function(a,b){a+="";switch(b||"utf8"){case "ascii":case "binary":case "raw":var h=a.length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":h=2*a.length;break;case "hex":h=a.length>>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length;
break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;h<b;h++)a=w,w=this[h],w=16>w?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b<h;b++)127>=
this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;a<b.length;a+=2)h+=String.fromCharCode(b[a]+256*b[a+1]);return h;default:if(w)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase();w=!0}};
e.prototype.equals=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return 0===e.compare(this,a)};e.prototype.inspect=function(){var a="",b=A.INSPECT_MAX_BYTES;0<this.length&&(a=this.toString("hex",0,b).match(/.{2}/g).join(" "),this.length>b&&(a+=" ... "));return"<Buffer "+a+">"};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead.");
return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/
2&&(h=w/2);for(w=0;w<h;w++){y=parseInt(a.substr(2*w,2),16);if(isNaN(y))throw Error("Invalid hex string");this[b+w]=y}a=w;break;case "utf8":case "utf-8":a=d(k(a),this,b,h);break;case "ascii":a=d(u(a),this,b,h);break;case "binary":a=d(u(a),this,b,h);break;case "base64":a=d(n.toByteArray(a),this,b,h);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":y=[];for(var I=0;I<a.length;I++){var K=a.charCodeAt(I);w=K>>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+
w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b<a&&(b=a);if(e.TYPED_ARRAY_SUPPORT)return e._augment(this.subarray(a,b));h=b-a;for(var w=new e(h,void 0,!0),y=0;y<h;y++)w[y]=this[y+a];return w};e.prototype.readUInt8=function(a,b){b||t(a,1,this.length);return this[a]};e.prototype.readUInt16LE=
function(a,b){b||t(a,2,this.length);return this[a]|this[a+1]<<8};e.prototype.readUInt16BE=function(a,b){b||t(a,2,this.length);return this[a]<<8|this[a+1]};e.prototype.readUInt32LE=function(a,b){b||t(a,4,this.length);return(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]};e.prototype.readUInt32BE=function(a,b){b||t(a,4,this.length);return 16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])};e.prototype.readInt8=function(a,b){b||t(a,1,this.length);return this[a]&128?-1*(255-this[a]+1):this[a]};
e.prototype.readInt16LE=function(a,b){b||t(a,2,this.length);var h=this[a]|this[a+1]<<8;return h&32768?h|4294901760:h};e.prototype.readInt16BE=function(a,b){b||t(a,2,this.length);var h=this[a+1]|this[a]<<8;return h&32768?h|4294901760:h};e.prototype.readInt32LE=function(a,b){b||t(a,4,this.length);return this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24};e.prototype.readInt32BE=function(a,b){b||t(a,4,this.length);return this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]};e.prototype.readFloatLE=function(a,
b){b||t(a,4,this.length);return v.read(this,a,!0,23,4)};e.prototype.readFloatBE=function(a,b){b||t(a,4,this.length);return v.read(this,a,!1,23,4)};e.prototype.readDoubleLE=function(a,b){b||t(a,8,this.length);return v.read(this,a,!0,52,8)};e.prototype.readDoubleBE=function(a,b){b||t(a,8,this.length);return v.read(this,a,!1,52,8)};e.prototype.writeUInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a,
b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a,
b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a,
b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+
2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(w<h)throw new TypeError("sourceEnd < sourceStart");if(0>b||b>=a.length)throw new TypeError("targetStart out of bounds");
if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-b<w-h&&(w=a.length-b+h);w-=h;if(1E3>w||!e.TYPED_ARRAY_SUPPORT)for(var y=0;y<w;y++)a[y+b]=this[y+h];else a._set(this.subarray(h,h+w),b)}};e.prototype.fill=function(a,b,h){a||(a=0);b||(b=0);h||(h=this.length);if(h<b)throw new TypeError("end < start");if(h!==b&&0!==this.length){if(0>b||b>=this.length)throw new TypeError("start out of bounds");
if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b<h;b++)this[b]=a;else{a=k(a.toString());for(var w=a.length;b<h;b++)this[b]=a[b%w]}return this}};e.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(e.TYPED_ARRAY_SUPPORT)return(new e(this)).buffer;for(var a=new Uint8Array(this.length),b=0,h=a.length;b<h;b+=1)a[b]=this[b];return a.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser");};var D=e.prototype;e._augment=
function(a){a.constructor=e;a._isBuffer=!0;a._get=a.get;a._set=a.set;a.get=D.get;a.set=D.set;a.write=D.write;a.toString=D.toString;a.toLocaleString=D.toString;a.toJSON=D.toJSON;a.equals=D.equals;a.compare=D.compare;a.copy=D.copy;a.slice=D.slice;a.readUInt8=D.readUInt8;a.readUInt16LE=D.readUInt16LE;a.readUInt16BE=D.readUInt16BE;a.readUInt32LE=D.readUInt32LE;a.readUInt32BE=D.readUInt32BE;a.readInt8=D.readInt8;a.readInt16LE=D.readInt16LE;a.readInt16BE=D.readInt16BE;a.readInt32LE=D.readInt32LE;a.readInt32BE=
D.readInt32BE;a.readFloatLE=D.readFloatLE;a.readFloatBE=D.readFloatBE;a.readDoubleLE=D.readDoubleLE;a.readDoubleBE=D.readDoubleBE;a.writeUInt8=D.writeUInt8;a.writeUInt16LE=D.writeUInt16LE;a.writeUInt16BE=D.writeUInt16BE;a.writeUInt32LE=D.writeUInt32LE;a.writeUInt32BE=D.writeUInt32BE;a.writeInt8=D.writeInt8;a.writeInt16LE=D.writeInt16LE;a.writeInt16BE=D.writeInt16BE;a.writeInt32LE=D.writeInt32LE;a.writeInt32BE=D.writeInt32BE;a.writeFloatLE=D.writeFloatLE;a.writeFloatBE=D.writeFloatBE;a.writeDoubleLE=
D.writeDoubleLE;a.writeDoubleBE=D.writeDoubleBE;a.fill=D.fill;a.inspect=D.inspect;a.toArrayBuffer=D.toArrayBuffer;return a};var L=/[^+\/0-9A-z]/g},{"base64-js":2,ieee754:6,"is-array":7}],6:[function(C,J,A){A.read=function(e,p,t,m,f){var c=8*f-m-1;var l=(1<<c)-1,q=l>>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0<r;t=256*t+e[p+f],f+=k,r-=8);c=t&(1<<-r)-1;t>>=-r;for(r+=m;0<r;c=256*c+e[p+f],f+=k,r-=8);if(0===t)t=1-q;else{if(t===l)return c?NaN:Infinity*(u?-1:1);c+=Math.pow(2,
m);t-=q}return(u?-1:1)*c*Math.pow(2,t-m)};A.write=function(e,p,t,m,f,c){var l,q=8*c-f-1,r=(1<<q)-1,k=r>>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+=
d,p/=256,f-=8);m=m<<f|p;for(q+=f;0<q;e[t+c]=m&255,c+=d,m/=256,q-=8);e[t+c-d]|=128*g}},{}],7:[function(C,J,A){var e=Object.prototype.toString;J.exports=Array.isArray||function(p){return!!p&&"[object Array]"==e.call(p)}},{}],8:[function(C,J,A){(function(e){function p(c,l){for(var q=0,r=c.length-1;0<=r;r--){var k=c[r];"."===k?c.splice(r,1):".."===k?(c.splice(r,1),q++):q&&(c.splice(r,1),q--)}if(l)for(;q--;q)c.unshift("..");return c}function t(c,l){if(c.filter)return c.filter(l);for(var q=[],r=0;r<c.length;r++)l(c[r],
r,c)&&q.push(c[r]);return q}var m=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;A.resolve=function(){for(var c="",l=!1,q=arguments.length-1;-1<=q&&!l;q--){var r=0<=q?arguments[q]:e.cwd();if("string"!==typeof r)throw new TypeError("Arguments to path.resolve must be strings");r&&(c=r+"/"+c,l="/"===r.charAt(0))}c=p(t(c.split("/"),function(k){return!!k}),!l).join("/");return(l?"/":"")+c||"."};A.normalize=function(c){var l=A.isAbsolute(c),q="/"===f(c,-1);(c=p(t(c.split("/"),function(r){return!!r}),
!l).join("/"))||l||(c=".");c&&q&&(c+="/");return(l?"/":"")+c};A.isAbsolute=function(c){return"/"===c.charAt(0)};A.join=function(){var c=Array.prototype.slice.call(arguments,0);return A.normalize(t(c,function(l,q){if("string"!==typeof l)throw new TypeError("Arguments to path.join must be strings");return l}).join("/"))};A.relative=function(c,l){function q(n){for(var v=0;v<n.length&&""===n[v];v++);for(var z=n.length-1;0<=z&&""===n[z];z--);return v>z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1);
for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;g<u;g++)if(r[g]!==k[g]){d=g;break}u=[];for(g=d;g<r.length;g++)u.push("..");u=u.concat(k.slice(d));return u.join("/")};A.sep="/";A.delimiter=":";A.dirname=function(c){var l=m.exec(c).slice(1);c=l[0];l=l[1];if(!c&&!l)return".";l&&(l=l.substr(0,l.length-1));return c+l};A.basename=function(c,l){var q=m.exec(c).slice(1)[2];l&&q.substr(-1*l.length)===l&&(q=q.substr(0,q.length-l.length));return q};A.extname=function(c){return m.exec(c).slice(1)[3]};
var f="b"==="ab".substr(-1)?function(c,l,q){return c.substr(l,q)}:function(c,l,q){0>l&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!==
m||"process-tick"!==t.data||(t.stopPropagation(),0<p.length&&p.shift()())},!0);return function(t){p.push(t);window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}();C.title="browser";C.browser=!0;C.env={};C.argv=[];C.on=e;C.addListener=e;C.once=e;C.off=e;C.removeListener=e;C.removeAllListeners=e;C.emit=e;C.binding=function(p){throw Error("process.binding is not supported");};C.cwd=function(){return"/"};C.chdir=function(p){throw Error("process.chdir is not supported");}},{}],
10:[function(C,J,A){function e(){this._array=[];this._set=m?new Map:Object.create(null)}var p=C("./util"),t=Object.prototype.hasOwnProperty,m="undefined"!==typeof Map;e.fromArray=function(f,c){for(var l=new e,q=0,r=f.length;q<r;q++)l.add(f[q],c);return l};e.prototype.size=function(){return m?this._set.size:Object.getOwnPropertyNames(this._set).length};e.prototype.add=function(f,c){var l=m?f:p.toSetString(f),q=m?this.has(f):t.call(this._set,l),r=this._array.length;q&&!c||this._array.push(f);q||(m?
this._set.set(f,r):this._set[l]=r)};e.prototype.has=function(f){if(m)return this._set.has(f);f=p.toSetString(f);return t.call(this._set,f)};e.prototype.indexOf=function(f){if(m){var c=this._set.get(f);if(0<=c)return c}else if(c=p.toSetString(f),t.call(this._set,c))return this._set[c];throw Error('"'+f+'" is not in the set.');};e.prototype.at=function(f){if(0<=f&&f<this._array.length)return this._array[f];throw Error("No element indexed by "+f);};e.prototype.toArray=function(){return this._array.slice()};
A.ArraySet=e},{"./util":19}],11:[function(C,J,A){var e=C("./base64");A.encode=function(p){var t="",m=0>p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0<m&&(p|=32),t+=e.encode(p);while(0<m);return t};A.decode=function(p,t,m){var f=p.length,c=0,l=0;do{if(t>=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<<l;l+=5}while(r);p=c>>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C,
J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p<e.length)return e[p];throw new TypeError("Must be between 0 and 63: "+p);};A.decode=function(p){return 65<=p&&90>=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0<r?1<t-q?e(q,t,m,f,c,l):l==A.LEAST_UPPER_BOUND?t<f.length?t:-1:q:1<q-p?e(p,q,m,f,c,l):l==
A.LEAST_UPPER_BOUND?q:0>p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine,
c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f<c){var l=f-1;e(t,Math.round(f+Math.random()*(c-f)),c);for(var q=t[c],
r=f;r<c;r++)0>=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d,
"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=
null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G<n.line||G===n.line&&D<n.column)throw Error("Section offsets must be ordered and non-overlapping.");
n=z;return{generatedOffset:{generatedLine:G+1,generatedColumn:D+1},consumer:new e(f.getArg(v,"map"),u)}})}var f=C("./util"),c=C("./binary-search"),l=C("./array-set").ArraySet,q=C("./base64-vlq"),r=C("./quick-sort").quickSort;e.fromSourceMap=function(k){return p.fromSourceMap(k)};e.prototype._version=3;e.prototype.__generatedMappings=null;Object.defineProperty(e.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){this.__generatedMappings||this._parseMappings(this._mappings,
this.sourceRoot);return this.__generatedMappings}});e.prototype.__originalMappings=null;Object.defineProperty(e.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot);return this.__originalMappings}});e.prototype._charIsMappingSeparator=function(k,u){var d=k.charAt(u);return";"===d||","===d};e.prototype._parseMappings=function(k,u){throw Error("Subclasses must implement _parseMappings");};e.GENERATED_ORDER=
1;e.ORIGINAL_ORDER=2;e.GREATEST_LOWER_BOUND=1;e.LEAST_UPPER_BOUND=2;e.prototype.eachMapping=function(k,u,d){u=u||null;switch(d||e.GENERATED_ORDER){case e.GENERATED_ORDER:d=this._generatedMappings;break;case e.ORIGINAL_ORDER:d=this._originalMappings;break;default:throw Error("Unknown order of iteration.");}var g=this.sourceRoot;d.map(function(n){var v=null===n.source?null:this._sources.at(n.source);v=f.computeSourceURL(g,v,this._sourceMapURL);return{source:v,generatedLine:n.generatedLine,generatedColumn:n.generatedColumn,
originalLine:n.originalLine,originalColumn:n.originalColumn,name:null===n.name?null:this._names.at(n.name)}},this).forEach(k,u)};e.prototype.allGeneratedPositionsFor=function(k){var u=f.getArg(k,"line"),d={source:f.getArg(k,"source"),originalLine:u,originalColumn:f.getArg(k,"column",0)};null!=this.sourceRoot&&(d.source=f.relative(this.sourceRoot,d.source));if(!this._sources.has(d.source))return[];d.source=this._sources.indexOf(d.source);var g=[];d=this._findMapping(d,this._originalMappings,"originalLine",
"originalColumn",f.compareByOriginalPositions,c.LEAST_UPPER_BOUND);if(0<=d){var n=this._originalMappings[d];if(void 0===k.column)for(u=n.originalLine;n&&n.originalLine===u;)g.push({line:f.getArg(n,"generatedLine",null),column:f.getArg(n,"generatedColumn",null),lastColumn:f.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++d];else for(k=n.originalColumn;n&&n.originalLine===u&&n.originalColumn==k;)g.push({line:f.getArg(n,"generatedLine",null),column:f.getArg(n,"generatedColumn",null),
lastColumn:f.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++d]}return g};A.SourceMapConsumer=e;p.prototype=Object.create(e.prototype);p.prototype.consumer=e;p.fromSourceMap=function(k,u){var d=Object.create(p.prototype),g=d._names=l.fromArray(k._names.toArray(),!0),n=d._sources=l.fromArray(k._sources.toArray(),!0);d.sourceRoot=k._sourceRoot;d.sourcesContent=k._generateSourcesContent(d._sources.toArray(),d.sourceRoot);d.file=k._file;d._sourceMapURL=u;for(var v=k._mappings.toArray().slice(),
z=d.__generatedMappings=[],G=d.__originalMappings=[],D=0,L=v.length;D<L;D++){var a=v[D],b=new t;b.generatedLine=a.generatedLine;b.generatedColumn=a.generatedColumn;a.source&&(b.source=n.indexOf(a.source),b.originalLine=a.originalLine,b.originalColumn=a.originalColumn,a.name&&(b.name=g.indexOf(a.name)),G.push(b));z.push(b)}r(d.__originalMappings,f.compareByOriginalPositions);return d};p.prototype._version=3;Object.defineProperty(p.prototype,"sources",{get:function(){return this._sources.toArray().map(function(k){return f.computeSourceURL(this.sourceRoot,
k,this._sourceMapURL)},this)}});p.prototype._parseMappings=function(k,u){for(var d=1,g=0,n=0,v=0,z=0,G=0,D=k.length,L=0,a={},b={},h=[],w=[],y,I,K,N,P;L<D;)if(";"===k.charAt(L))d++,L++,g=0;else if(","===k.charAt(L))L++;else{y=new t;y.generatedLine=d;for(N=L;N<D&&!this._charIsMappingSeparator(k,N);N++);I=k.slice(L,N);if(K=a[I])L+=I.length;else{for(K=[];L<N;)q.decode(k,L,b),P=b.value,L=b.rest,K.push(P);if(2===K.length)throw Error("Found a source, but no line and column");if(3===K.length)throw Error("Found a source and line, but no column");
a[I]=K}y.generatedColumn=g+K[0];g=y.generatedColumn;1<K.length&&(y.source=z+K[1],z+=K[1],y.originalLine=n+K[2],n=y.originalLine,y.originalLine+=1,y.originalColumn=v+K[3],v=y.originalColumn,4<K.length&&(y.name=G+K[4],G+=K[4]));w.push(y);"number"===typeof y.originalLine&&h.push(y)}r(w,f.compareByGeneratedPositionsDeflated);this.__generatedMappings=w;r(h,f.compareByOriginalPositions);this.__originalMappings=h};p.prototype._findMapping=function(k,u,d,g,n,v){if(0>=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+
k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k<this._generatedMappings.length;++k){var u=this._generatedMappings[k];if(k+1<this._generatedMappings.length){var d=this._generatedMappings[k+1];if(u.generatedLine===d.generatedLine){u.lastGeneratedColumn=d.generatedColumn-1;continue}}u.lastGeneratedColumn=Infinity}};p.prototype.originalPositionFor=function(k){var u={generatedLine:f.getArg(k,
"line"),generatedColumn:f.getArg(k,"column")};k=this._findMapping(u,this._generatedMappings,"generatedLine","generatedColumn",f.compareByGeneratedPositionsDeflated,f.getArg(k,"bias",e.GREATEST_LOWER_BOUND));if(0<=k&&(k=this._generatedMappings[k],k.generatedLine===u.generatedLine)){u=f.getArg(k,"source",null);null!==u&&(u=this._sources.at(u),u=f.computeSourceURL(this.sourceRoot,u,this._sourceMapURL));var d=f.getArg(k,"name",null);null!==d&&(d=this._names.at(d));return{source:u,line:f.getArg(k,"originalLine",
null),column:f.getArg(k,"originalColumn",null),name:d}}return{source:null,line:null,column:null,name:null}};p.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)];
var g=this.sources,n;for(n=0;n<g.length;++n)if(g[n]==k)return this.sourcesContent[n];var v;if(null!=this.sourceRoot&&(v=f.urlParse(this.sourceRoot))){g=d.replace(/^file:\/\//,"");if("file"==v.scheme&&this._sources.has(g))return this.sourcesContent[this._sources.indexOf(g)];if((!v.path||"/"==v.path)&&this._sources.has("/"+d))return this.sourcesContent[this._sources.indexOf("/"+d)]}if(u)return null;throw Error('"'+d+'" is not in the SourceMap.');};p.prototype.generatedPositionFor=function(k){var u=
f.getArg(k,"source");null!=this.sourceRoot&&(u=f.relative(this.sourceRoot,u));if(!this._sources.has(u))return{line:null,column:null,lastColumn:null};u=this._sources.indexOf(u);u={source:u,originalLine:f.getArg(k,"line"),originalColumn:f.getArg(k,"column")};k=this._findMapping(u,this._originalMappings,"originalLine","originalColumn",f.compareByOriginalPositions,f.getArg(k,"bias",e.GREATEST_LOWER_BOUND));return 0<=k&&(k=this._originalMappings[k],k.source===u.source)?{line:f.getArg(k,"generatedLine",
null),column:f.getArg(k,"generatedColumn",null),lastColumn:f.getArg(k,"lastGeneratedColumn",null)}:{line:null,column:null,lastColumn:null}};A.BasicSourceMapConsumer=p;m.prototype=Object.create(e.prototype);m.prototype.constructor=e;m.prototype._version=3;Object.defineProperty(m.prototype,"sources",{get:function(){for(var k=[],u=0;u<this._sections.length;u++)for(var d=0;d<this._sections[u].consumer.sources.length;d++)k.push(this._sections[u].consumer.sources[d]);return k}});m.prototype.originalPositionFor=
function(k){var u={generatedLine:f.getArg(k,"line"),generatedColumn:f.getArg(k,"column")},d=c.search(u,this._sections,function(g,n){var v=g.generatedLine-n.generatedOffset.generatedLine;return v?v:g.generatedColumn-n.generatedOffset.generatedColumn});return(d=this._sections[d])?d.consumer.originalPositionFor({line:u.generatedLine-(d.generatedOffset.generatedLine-1),column:u.generatedColumn-(d.generatedOffset.generatedLine===u.generatedLine?d.generatedOffset.generatedColumn-1:0),bias:k.bias}):{source:null,
line:null,column:null,name:null}};m.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(k){return k.consumer.hasContentsOfAllSources()})};m.prototype.sourceContentFor=function(k,u){for(var d=0;d<this._sections.length;d++){var g=this._sections[d].consumer.sourceContentFor(k,!0);if(g)return g}if(u)return null;throw Error('"'+k+'" is not in the SourceMap.');};m.prototype.generatedPositionFor=function(k){for(var u=0;u<this._sections.length;u++){var d=this._sections[u];if(-1!==
d.consumer.sources.indexOf(f.getArg(k,"source"))){var g=d.consumer.generatedPositionFor(k);if(g)return{line:g.line+(d.generatedOffset.generatedLine-1),column:g.column+(d.generatedOffset.generatedLine===g.line?d.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}};m.prototype._parseMappings=function(k,u){this.__generatedMappings=[];this.__originalMappings=[];for(var d=0;d<this._sections.length;d++)for(var g=this._sections[d],n=g.consumer._generatedMappings,v=0;v<n.length;v++){var z=
n[v],G=g.consumer._sources.at(z.source);G=f.computeSourceURL(g.consumer.sourceRoot,G,this._sourceMapURL);this._sources.add(G);G=this._sources.indexOf(G);var D=null;z.name&&(D=g.consumer._names.at(z.name),this._names.add(D),D=this._names.indexOf(D));z={source:G,generatedLine:z.generatedLine+(g.generatedOffset.generatedLine-1),generatedColumn:z.generatedColumn+(g.generatedOffset.generatedLine===z.generatedLine?g.generatedOffset.generatedColumn-1:0),originalLine:z.originalLine,originalColumn:z.originalColumn,
name:D};this.__generatedMappings.push(z);"number"===typeof z.originalLine&&this.__originalMappings.push(z)}r(this.__generatedMappings,f.compareByGeneratedPositionsDeflated);r(this.__originalMappings,f.compareByOriginalPositions)};A.IndexedSourceMapConsumer=m},{"./array-set":10,"./base64-vlq":11,"./binary-search":13,"./quick-sort":15,"./util":19}],17:[function(C,J,A){function e(c){c||(c={});this._file=t.getArg(c,"file",null);this._sourceRoot=t.getArg(c,"sourceRoot",null);this._skipValidation=t.getArg(c,
"skipValidation",!1);this._sources=new m;this._names=new m;this._mappings=new f;this._sourcesContents=null}var p=C("./base64-vlq"),t=C("./util"),m=C("./array-set").ArraySet,f=C("./mapping-list").MappingList;e.prototype._version=3;e.fromSourceMap=function(c){var l=c.sourceRoot,q=new e({file:c.file,sourceRoot:l});c.eachMapping(function(r){var k={generated:{line:r.generatedLine,column:r.generatedColumn}};null!=r.source&&(k.source=r.source,null!=l&&(k.source=t.relative(l,k.source)),k.original={line:r.originalLine,
column:r.originalColumn},null!=r.name&&(k.name=r.name));q.addMapping(k)});c.sources.forEach(function(r){var k=r;null!==l&&(k=t.relative(l,r));q._sources.has(k)||q._sources.add(k);k=c.sourceContentFor(r);null!=k&&q.setSourceContent(r,k)});return q};e.prototype.addMapping=function(c){var l=t.getArg(c,"generated"),q=t.getArg(c,"original",null),r=t.getArg(c,"source",null);c=t.getArg(c,"name",null);this._skipValidation||this._validateMapping(l,q,r,c);null!=r&&(r=String(r),this._sources.has(r)||this._sources.add(r));
null!=c&&(c=String(c),this._names.has(c)||this._names.add(c));this._mappings.add({generatedLine:l.line,generatedColumn:l.column,originalLine:null!=q&&q.line,originalColumn:null!=q&&q.column,source:r,name:c})};e.prototype.setSourceContent=function(c,l){var q=c;null!=this._sourceRoot&&(q=t.relative(this._sourceRoot,q));null!=l?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[t.toSetString(q)]=l):this._sourcesContents&&(delete this._sourcesContents[t.toSetString(q)],
0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))};e.prototype.applySourceMap=function(c,l,q){var r=l;if(null==l){if(null==c.file)throw Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');r=c.file}var k=this._sourceRoot;null!=k&&(r=t.relative(k,r));var u=new m,d=new m;this._mappings.unsortedForEach(function(g){if(g.source===r&&null!=g.originalLine){var n=c.originalPositionFor({line:g.originalLine,
column:g.originalColumn});null!=n.source&&(g.source=n.source,null!=q&&(g.source=t.join(q,g.source)),null!=k&&(g.source=t.relative(k,g.source)),g.originalLine=n.line,g.originalColumn=n.column,null!=n.name&&(g.name=n.name))}n=g.source;null==n||u.has(n)||u.add(n);g=g.name;null==g||d.has(g)||d.add(g)},this);this._sources=u;this._names=d;c.sources.forEach(function(g){var n=c.sourceContentFor(g);null!=n&&(null!=q&&(g=t.join(q,g)),null!=k&&(g=t.relative(k,g)),this.setSourceContent(g,n))},this)};e.prototype._validateMapping=
function(c,l,q,r){if(l&&"number"!==typeof l.line&&"number"!==typeof l.column)throw Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(c&&"line"in c&&"column"in c&&0<c.line&&0<=c.column&&!l&&!q&&!r||c&&"line"in c&&"column"in c&&l&&"line"in l&&"column"in l&&0<c.line&&0<=c.column&&0<l.line&&0<=l.column&&
q))throw Error("Invalid mapping: "+JSON.stringify({generated:c,source:q,original:l,name:r}));};e.prototype._serializeMappings=function(){for(var c=0,l=1,q=0,r=0,k=0,u=0,d="",g,n,v,z=this._mappings.toArray(),G=0,D=z.length;G<D;G++){n=z[G];g="";if(n.generatedLine!==l)for(c=0;n.generatedLine!==l;)g+=";",l++;else if(0<G){if(!t.compareByGeneratedPositionsInflated(n,z[G-1]))continue;g+=","}g+=p.encode(n.generatedColumn-c);c=n.generatedColumn;null!=n.source&&(v=this._sources.indexOf(n.source),g+=p.encode(v-
u),u=v,g+=p.encode(n.originalLine-1-r),r=n.originalLine-1,g+=p.encode(n.originalColumn-q),q=n.originalColumn,null!=n.name&&(n=this._names.indexOf(n.name),g+=p.encode(n-k),k=n));d+=g}return d};e.prototype._generateSourcesContent=function(c,l){return c.map(function(q){if(!this._sourcesContents)return null;null!=l&&(q=t.relative(l,q));q=t.toSetString(q);return Object.prototype.hasOwnProperty.call(this._sourcesContents,q)?this._sourcesContents[q]:null},this)};e.prototype.toJSON=function(){var c={version:this._version,
sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};null!=this._file&&(c.file=this._file);null!=this._sourceRoot&&(c.sourceRoot=this._sourceRoot);this._sourcesContents&&(c.sourcesContent=this._generateSourcesContent(c.sources,c.sourceRoot));return c};e.prototype.toString=function(){return JSON.stringify(this.toJSON())};A.SourceMapGenerator=e},{"./array-set":10,"./base64-vlq":11,"./mapping-list":14,"./util":19}],18:[function(C,J,A){function e(f,c,l,q,r){this.children=
[];this.sourceContents={};this.line=null==f?null:f;this.column=null==c?null:c;this.source=null==l?null:l;this.name=null==r?null:r;this.$$$isSourceNode$$$=!0;null!=q&&this.add(q)}var p=C("./source-map-generator").SourceMapGenerator,t=C("./util"),m=/(\r?\n)/;e.fromStringWithSourceMap=function(f,c,l){function q(z,G){if(null===z||void 0===z.source)r.add(G);else{var D=l?t.join(l,z.source):z.source;r.add(new e(z.originalLine,z.originalColumn,D,G,z.name))}}var r=new e,k=f.split(m),u=0,d=function(){var z=
u<k.length?k[u++]:void 0,G=(u<k.length?k[u++]:void 0)||"";return z+G},g=1,n=0,v=null;c.eachMapping(function(z){if(null!==v)if(g<z.generatedLine)q(v,d()),g++,n=0;else{var G=k[u]||"",D=G.substr(0,z.generatedColumn-n);k[u]=G.substr(z.generatedColumn-n);n=z.generatedColumn;q(v,D);v=z;return}for(;g<z.generatedLine;)r.add(d()),g++;n<z.generatedColumn&&(G=k[u]||"",r.add(G.substr(0,z.generatedColumn)),k[u]=G.substr(z.generatedColumn),n=z.generatedColumn);v=z},this);u<k.length&&(v&&q(v,d()),r.add(k.splice(u).join("")));
c.sources.forEach(function(z){var G=c.sourceContentFor(z);null!=G&&(null!=l&&(z=t.join(l,z)),r.setSourceContent(z,G))});return r};e.prototype.add=function(f){if(Array.isArray(f))f.forEach(function(c){this.add(c)},this);else if(f.$$$isSourceNode$$$||"string"===typeof f)f&&this.children.push(f);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+f);return this};e.prototype.prepend=function(f){if(Array.isArray(f))for(var c=f.length-1;0<=c;c--)this.prepend(f[c]);
else if(f.$$$isSourceNode$$$||"string"===typeof f)this.children.unshift(f);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+f);return this};e.prototype.walk=function(f){for(var c,l=0,q=this.children.length;l<q;l++)c=this.children[l],c.$$$isSourceNode$$$?c.walk(f):""!==c&&f(c,{source:this.source,line:this.line,column:this.column,name:this.name})};e.prototype.join=function(f){var c,l=this.children.length;if(0<l){var q=[];for(c=0;c<l-1;c++)q.push(this.children[c]),
q.push(f);q.push(this.children[c]);this.children=q}return this};e.prototype.replaceRight=function(f,c){var l=this.children[this.children.length-1];l.$$$isSourceNode$$$?l.replaceRight(f,c):"string"===typeof l?this.children[this.children.length-1]=l.replace(f,c):this.children.push("".replace(f,c));return this};e.prototype.setSourceContent=function(f,c){this.sourceContents[t.toSetString(f)]=c};e.prototype.walkSourceContents=function(f){for(var c=0,l=this.children.length;c<l;c++)this.children[c].$$$isSourceNode$$$&&
this.children[c].walkSourceContents(f);var q=Object.keys(this.sourceContents);c=0;for(l=q.length;c<l;c++)f(t.fromSetString(q[c]),this.sourceContents[q[c]])};e.prototype.toString=function(){var f="";this.walk(function(c){f+=c});return f};e.prototype.toStringWithSourceMap=function(f){var c="",l=1,q=0,r=new p(f),k=!1,u=null,d=null,g=null,n=null;this.walk(function(v,z){c+=v;null!==z.source&&null!==z.line&&null!==z.column?(u===z.source&&d===z.line&&g===z.column&&n===z.name||r.addMapping({source:z.source,
original:{line:z.line,column:z.column},generated:{line:l,column:q},name:z.name}),u=z.source,d=z.line,g=z.column,n=z.name,k=!0):k&&(r.addMapping({generated:{line:l,column:q}}),u=null,k=!1);for(var G=0,D=v.length;G<D;G++)10===v.charCodeAt(G)?(l++,q=0,G+1===D?(u=null,k=!1):k&&r.addMapping({source:z.source,original:{line:z.line,column:z.column},generated:{line:l,column:q},name:z.name})):q++});this.walkSourceContents(function(v,z){r.setSourceContent(v,z)});return{code:c,map:r}};A.SourceNode=e},{"./source-map-generator":17,
"./util":19}],19:[function(C,J,A){function e(d){return(d=d.match(k))?{scheme:d[1],auth:d[2],host:d[3],port:d[4],path:d[5]}:null}function p(d){var g="";d.scheme&&(g+=d.scheme+":");g+="//";d.auth&&(g+=d.auth+"@");d.host&&(g+=d.host);d.port&&(g+=":"+d.port);d.path&&(g+=d.path);return g}function t(d){var g=d,n=e(d);if(n){if(!n.path)return d;g=n.path}d=A.isAbsolute(g);g=g.split(/\/+/);for(var v,z=0,G=g.length-1;0<=G;G--)v=g[G],"."===v?g.splice(G,1):".."===v?z++:0<z&&(""===v?(g.splice(G+1,z),z=0):(g.splice(G,
2),z--));g=g.join("/");""===g&&(g=d?"/":".");return n?(n.path=g,p(n)):g}function m(d,g){""===d&&(d=".");""===g&&(g=".");var n=e(g),v=e(d);v&&(d=v.path||"/");if(n&&!n.scheme)return v&&(n.scheme=v.scheme),p(n);if(n||g.match(u))return g;if(v&&!v.host&&!v.path)return v.host=g,p(v);n="/"===g.charAt(0)?g:t(d.replace(/\/+$/,"")+"/"+g);return v?(v.path=n,p(v)):n}function f(d){return d}function c(d){return q(d)?"$"+d:d}function l(d){return q(d)?d.slice(1):d}function q(d){if(!d)return!1;var g=d.length;if(9>
g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,
u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d,
g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-
g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/,
""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16,
"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F<x.length;F++){var E=x[F](B);if(E)return E}return null}}function m(x,B){if(!x)return B;var F=n.dirname(x),E=/^\w+:\/\/[^\/]*/.exec(F);E=E?E[0]:"";var H=F.slice(E.length);
return E&&/^\/\w:/.test(H)?(E+="/",E+n.resolve(F.slice(E.length),B).replace(/\\/g,"/")):E+n.resolve(F.slice(E.length),B)}function f(x){var B=h[x.source];if(!B){var F=N(x.source);F?(B=h[x.source]={url:F.url,map:new g(F.map)},B.map.sourcesContent&&B.map.sources.forEach(function(E,H){var M=B.map.sourcesContent[H];if(M){var S=m(B.url,E);b[S]=M}})):B=h[x.source]={url:null,map:null}}return B&&B.map&&"function"===typeof B.map.originalPositionFor&&(F=B.map.originalPositionFor(x),null!==F.source)?(F.source=
m(B.url,F.source),F):x}function c(x){var B=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(x);return B?(x=f({source:B[2],line:+B[3],column:B[4]-1}),"eval at "+B[1]+" ("+x.source+":"+x.line+":"+(x.column+1)+")"):(B=/^eval at ([^(]+) \((.+)\)$/.exec(x))?"eval at "+B[1]+" ("+c(B[2])+")":x}function l(){var x="";if(this.isNative())x="native";else{var B=this.getScriptNameOrSourceURL();!B&&this.isEval()&&(x=this.getEvalOrigin(),x+=", ");x=B?x+B:x+"<anonymous>";B=this.getLineNumber();null!=B&&(x+=":"+B,(B=
this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||"<anonymous>"):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"<anonymous>")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]=
/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O=
f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F=
(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+
"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0<this.listeners(B).length;if(F&&!E){F=arguments[1];E=u(F);var H="object"===typeof e&&null!==e?e.stderr:void 0;H&&H._handle&&H._handle.setBlocking&&H._handle.setBlocking(!0);E&&(console.error(),console.error(E));console.error(F.stack);"object"===typeof e&&null!==e&&"function"===typeof e.exit&&e.exit(1);return}}return x.apply(this,arguments)}}var g=C("source-map").SourceMapConsumer,
n=C("path");try{var v=C("fs");v.existsSync&&v.readFileSync||(v=null)}catch(x){}var z=C("buffer-from"),G=!1,D=!1,L=!1,a="auto",b={},h={},w=/^data:application\/json[^,]+base64,/,y=[],I=[],K=t(y);y.push(function(x){x=x.trim();/^file:/.test(x)&&(x=x.replace(/file:\/\/\/(\w:)?/,function(E,H){return H?"":"/"}));if(x in b)return b[x];var B="";try{if(v)v.existsSync(x)&&(B=v.readFileSync(x,"utf8"));else{var F=new XMLHttpRequest;F.open("GET",x,!1);F.send(null);4===F.readyState&&200===F.status&&(B=F.responseText)}}catch(E){}return b[x]=
B});var N=t(I);I.push(function(x){a:{if(p())try{var B=new XMLHttpRequest;B.open("GET",x,!1);B.send(null);var F=B.getResponseHeader("SourceMap")||B.getResponseHeader("X-SourceMap");if(F){var E=F;break a}}catch(M){}E=K(x);B=/(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;for(var H;F=B.exec(E);)H=F;E=H?H[1]:null}if(!E)return null;w.test(E)?(H=E.slice(E.indexOf(",")+1),H=z(H,"base64").toString(),E=x):(E=m(x,E),H=K(E));return H?{url:E,
map:H}:null});var P=y.slice(0),W=I.slice(0);A.wrapCallSite=r;A.getErrorSource=u;A.mapSourcePosition=f;A.retrieveSourceMap=N;A.install=function(x){x=x||{};if(x.environment&&(a=x.environment,-1===["node","browser","auto"].indexOf(a)))throw Error("environment "+a+" was unknown. Available options are {auto, browser, node}");x.retrieveFile&&(x.overrideRetrieveFile&&(y.length=0),y.unshift(x.retrieveFile));x.retrieveSourceMap&&(x.overrideRetrieveSourceMap&&(I.length=0),I.unshift(x.retrieveSourceMap));if(x.hookRequire&&
!p()){var B=J.require("module"),F=B.prototype._compile;F.__sourceMapSupport||(B.prototype._compile=function(E,H){b[H]=E;h[H]=void 0;return F.call(this,E,H)},B.prototype._compile.__sourceMapSupport=!0)}L||(L="emptyCacheBetweenOperations"in x?x.emptyCacheBetweenOperations:!1);G||(G=!0,Error.prepareStackTrace=k);if(!D){x="handleUncaughtExceptions"in x?x.handleUncaughtExceptions:!0;try{!1===J.require("worker_threads").isMainThread&&(x=!1)}catch(E){}x&&"object"===typeof e&&null!==e&&"function"===typeof e.on&&
(D=!0,d())}};A.resetRetrieveHandlers=function(){y.length=0;I.length=0;y=P.slice(0);I=W.slice(0);N=t(I);K=t(y)}}).call(this,C("g5I+bs"))},{"buffer-from":4,fs:3,"g5I+bs":9,path:8,"source-map":20}]},{},[1]);return R});

View file

@ -1,50 +0,0 @@
{
"name": "@cspotcode/source-map-support",
"description": "Fixes stack traces for files with source maps",
"version": "0.8.1",
"main": "./source-map-support.js",
"types": "./source-map-support.d.ts",
"scripts": {
"build": "node build.js",
"serve-tests": "http-server -p 1336",
"test": "mocha"
},
"files": [
"/register.d.ts",
"/register.js",
"/register-hook-require.d.ts",
"/register-hook-require.js",
"/source-map-support.d.ts",
"/source-map-support.js",
"/browser-source-map-support.js"
],
"dependencies": {
"@jridgewell/trace-mapping": "0.3.9"
},
"devDependencies": {
"@types/lodash": "^4.14.182",
"browserify": "^4.2.3",
"coffeescript": "^1.12.7",
"http-server": "^0.11.1",
"lodash": "^4.17.21",
"mocha": "^3.5.3",
"semver": "^7.3.7",
"source-map": "0.6.1",
"webpack": "^1.15.0"
},
"repository": {
"type": "git",
"url": "https://github.com/cspotcode/node-source-map-support"
},
"bugs": {
"url": "https://github.com/cspotcode/node-source-map-support/issues"
},
"license": "MIT",
"engines": {
"node": ">=12"
},
"volta": {
"node": "16.11.0",
"npm": "7.24.2"
}
}

View file

@ -1,7 +0,0 @@
// tslint:disable:no-useless-files
// For following usage:
// import '@cspotcode/source-map-support/register-hook-require'
// Instead of:
// import sourceMapSupport from '@cspotcode/source-map-support'
// sourceMapSupport.install({hookRequire: true})

View file

@ -1,3 +0,0 @@
require('./').install({
hookRequire: true
});

View file

@ -1,7 +0,0 @@
// tslint:disable:no-useless-files
// For following usage:
// import '@cspotcode/source-map-support/register'
// Instead of:
// import sourceMapSupport from '@cspotcode/source-map-support'
// sourceMapSupport.install()

View file

@ -1 +0,0 @@
require('./').install();

View file

@ -1,76 +0,0 @@
// Type definitions for source-map-support 0.5
// Project: https://github.com/evanw/node-source-map-support
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
// Jason Cheatham <https://github.com/jason0x43>
// Alcedo Nathaniel De Guzman Jr <https://github.com/natealcedo>
// Griffin Yourick <https://github.com/tough-griff>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
export interface RawSourceMap {
version: 3;
sources: string[];
names: string[];
sourceRoot?: string;
sourcesContent?: string[];
mappings: string;
file: string;
}
/**
* Output of retrieveSourceMap().
* From source-map-support:
* The map field may be either a string or the parsed JSON object (i.e.,
* it must be a valid argument to the SourceMapConsumer constructor).
*/
export interface UrlAndMap {
url: string;
map: string | RawSourceMap;
}
/**
* Options to install().
*/
export interface Options {
handleUncaughtExceptions?: boolean | undefined;
hookRequire?: boolean | undefined;
emptyCacheBetweenOperations?: boolean | undefined;
environment?: 'auto' | 'browser' | 'node' | undefined;
overrideRetrieveFile?: boolean | undefined;
overrideRetrieveSourceMap?: boolean | undefined;
retrieveFile?(path: string): string;
retrieveSourceMap?(source: string): UrlAndMap | null;
/**
* Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support`
*/
redirectConflictingLibrary?: boolean;
/**
* Callback will be called every time we redirect due to `redirectConflictingLibrary`
* This allows consumers to log helpful warnings if they choose.
* @param parent NodeJS.Module which made the require() or require.resolve() call
* @param options options object internally passed to node's `_resolveFilename` hook
*/
onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void;
}
export interface Position {
source: string;
line: number;
column: number;
}
export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */;
export function getErrorSource(error: Error): string | null;
export function mapSourcePosition(position: Position): Position;
export function retrieveSourceMap(source: string): UrlAndMap | null;
export function resetRetrieveHandlers(): void;
/**
* Install SourceMap support.
* @param options Can be used to e.g. disable uncaughtException handler.
*/
export function install(options?: Options): void;
/**
* Uninstall SourceMap support.
*/
export function uninstall(): void;

View file

@ -1,938 +0,0 @@
const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping');
var path = require('path');
const { fileURLToPath, pathToFileURL } = require('url');
var util = require('util');
var fs;
try {
fs = require('fs');
if (!fs.existsSync || !fs.readFileSync) {
// fs doesn't have all methods we need
fs = null;
}
} catch (err) {
/* nop */
}
/**
* Requires a module which is protected against bundler minification.
*
* @param {NodeModule} mod
* @param {string} request
*/
function dynamicRequire(mod, request) {
return mod.require(request);
}
/**
* @typedef {{
* enabled: boolean;
* originalValue: any;
* installedValue: any;
* }} HookState
* Used for installing and uninstalling hooks
*/
// Increment this if the format of sharedData changes in a breaking way.
var sharedDataVersion = 1;
/**
* @template T
* @param {T} defaults
* @returns {T}
*/
function initializeSharedData(defaults) {
var sharedDataKey = 'source-map-support/sharedData';
if (typeof Symbol !== 'undefined') {
sharedDataKey = Symbol.for(sharedDataKey);
}
var sharedData = this[sharedDataKey];
if (!sharedData) {
sharedData = { version: sharedDataVersion };
if (Object.defineProperty) {
Object.defineProperty(this, sharedDataKey, { value: sharedData });
} else {
this[sharedDataKey] = sharedData;
}
}
if (sharedDataVersion !== sharedData.version) {
throw new Error("Multiple incompatible instances of source-map-support were loaded");
}
for (var key in defaults) {
if (!(key in sharedData)) {
sharedData[key] = defaults[key];
}
}
return sharedData;
}
// If multiple instances of source-map-support are loaded into the same
// context, they shouldn't overwrite each other. By storing handlers, caches,
// and other state on a shared object, different instances of
// source-map-support can work together in a limited way. This does require
// that future versions of source-map-support continue to support the fields on
// this object. If this internal contract ever needs to be broken, increment
// sharedDataVersion. (This version number is not the same as any of the
// package's version numbers, which should reflect the *external* API of
// source-map-support.)
var sharedData = initializeSharedData({
// Only install once if called multiple times
// Remember how the environment looked before installation so we can restore if able
/** @type {HookState} */
errorPrepareStackTraceHook: undefined,
/** @type {HookState} */
processEmitHook: undefined,
/** @type {HookState} */
moduleResolveFilenameHook: undefined,
/** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */
onConflictingLibraryRedirectArr: [],
// If true, the caches are reset before a stack trace formatting operation
emptyCacheBetweenOperations: false,
// Maps a file path to a string containing the file contents
fileContentsCache: Object.create(null),
// Maps a file path to a source map for that file
/** @type {Record<string, {url: string, map: TraceMap}} */
sourceMapCache: Object.create(null),
// Priority list of retrieve handlers
retrieveFileHandlers: [],
retrieveMapHandlers: [],
// Priority list of internally-implemented handlers.
// When resetting state, we must keep these.
internalRetrieveFileHandlers: [],
internalRetrieveMapHandlers: [],
});
// Supports {browser, node, auto}
var environment = "auto";
// Regex for detecting source maps
var reSourceMap = /^data:application\/json[^,]+base64,/;
function isInBrowser() {
if (environment === "browser")
return true;
if (environment === "node")
return false;
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
}
function hasGlobalProcessEventEmitter() {
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
}
function tryFileURLToPath(v) {
if(isFileUrl(v)) {
return fileURLToPath(v);
}
return v;
}
// TODO un-copy these from resolve-uri; see if they can be exported from that lib
function isFileUrl(input) {
return input.startsWith('file:');
}
function isAbsoluteUrl(input) {
return schemeRegex.test(input);
}
// Matches the scheme of a URL, eg "http://"
const schemeRegex = /^[\w+.-]+:\/\//;
function isSchemeRelativeUrl(input) {
return input.startsWith('//');
}
// #region Caches
/** @param {string} pathOrFileUrl */
function getCacheKey(pathOrFileUrl) {
if(pathOrFileUrl.startsWith('node:')) return pathOrFileUrl;
if(isFileUrl(pathOrFileUrl)) {
// Must normalize spaces to %20, stuff like that
return new URL(pathOrFileUrl).toString();
} else {
try {
return pathToFileURL(pathOrFileUrl).toString();
} catch {
return pathOrFileUrl;
}
}
}
function getFileContentsCache(key) {
return sharedData.fileContentsCache[getCacheKey(key)];
}
function hasFileContentsCacheFromKey(key) {
return Object.prototype.hasOwnProperty.call(sharedData.fileContentsCache, key);
}
function getFileContentsCacheFromKey(key) {
return sharedData.fileContentsCache[key];
}
function setFileContentsCache(key, value) {
return sharedData.fileContentsCache[getCacheKey(key)] = value;
}
function getSourceMapCache(key) {
return sharedData.sourceMapCache[getCacheKey(key)];
}
function setSourceMapCache(key, value) {
return sharedData.sourceMapCache[getCacheKey(key)] = value;
}
function clearCaches() {
sharedData.fileContentsCache = Object.create(null);
sharedData.sourceMapCache = Object.create(null);
}
// #endregion Caches
function handlerExec(list, internalList) {
return function(arg) {
for (var i = 0; i < list.length; i++) {
var ret = list[i](arg);
if (ret) {
return ret;
}
}
for (var i = 0; i < internalList.length; i++) {
var ret = internalList[i](arg);
if (ret) {
return ret;
}
}
return null;
};
}
var retrieveFile = handlerExec(sharedData.retrieveFileHandlers, sharedData.internalRetrieveFileHandlers);
sharedData.internalRetrieveFileHandlers.push(function(path) {
// Trim the path to make sure there is no extra whitespace.
path = path.trim();
if (/^file:/.test(path)) {
// existsSync/readFileSync can't handle file protocol, but once stripped, it works
path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
return drive ?
'' : // file:///C:/dir/file -> C:/dir/file
'/'; // file:///root-dir/file -> /root-dir/file
});
}
const key = getCacheKey(path);
if(hasFileContentsCacheFromKey(key)) {
return getFileContentsCacheFromKey(key);
}
var contents = '';
try {
if (!fs) {
// Use SJAX if we are in the browser
var xhr = new XMLHttpRequest();
xhr.open('GET', path, /** async */ false);
xhr.send(null);
if (xhr.readyState === 4 && xhr.status === 200) {
contents = xhr.responseText;
}
} else if (fs.existsSync(path)) {
// Otherwise, use the filesystem
contents = fs.readFileSync(path, 'utf8');
}
} catch (er) {
/* ignore any errors */
}
return setFileContentsCache(path, contents);
});
// Support URLs relative to a directory, but be careful about a protocol prefix
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
function supportRelativeURL(file, url) {
if(!file) return url;
// given that this happens within error formatting codepath, probably best to
// fallback instead of throwing if anything goes wrong
try {
// if should output a URL
if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) {
if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
return new URL(url, file).toString();
}
if(path.isAbsolute(url)) {
return new URL(pathToFileURL(url), file).toString();
}
// url is relative path or URL
return new URL(url.replace(/\\/g, '/'), file).toString();
}
// if should output a path (unless URL is something like https://)
if(path.isAbsolute(file)) {
if(isFileUrl(url)) {
return fileURLToPath(url);
}
if(isSchemeRelativeUrl(url)) {
return fileURLToPath(new URL(url, 'file://'));
}
if(isAbsoluteUrl(url)) {
// url is a non-file URL
// Go with the URL
return url;
}
if(path.isAbsolute(url)) {
// Normalize at all? decodeURI or normalize slashes?
return path.normalize(url);
}
// url is relative path or URL
return path.join(file, '..', decodeURI(url));
}
// If we get here, file is relative.
// Shouldn't happen since node identifies modules with absolute paths or URLs.
// But we can take a stab at returning something meaningful anyway.
if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
return url;
}
return path.join(file, '..', url);
} catch(e) {
return url;
}
}
// Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path
function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) {
try {
if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) {
if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl;
if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString();
} else if(path.isAbsolute(matchStyleOf)) {
if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) {
return fileURLToPath(new URL(pathOrUrl, 'file://'));
}
}
return pathOrUrl;
} catch(e) {
return pathOrUrl;
}
}
function retrieveSourceMapURL(source) {
var fileData;
if (isInBrowser()) {
try {
var xhr = new XMLHttpRequest();
xhr.open('GET', source, false);
xhr.send(null);
fileData = xhr.readyState === 4 ? xhr.responseText : null;
// Support providing a sourceMappingURL via the SourceMap header
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
xhr.getResponseHeader("X-SourceMap");
if (sourceMapHeader) {
return sourceMapHeader;
}
} catch (e) {
}
}
// Get the URL of the source map
fileData = retrieveFile(tryFileURLToPath(source));
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
// Keep executing the search to find the *last* sourceMappingURL to avoid
// picking up sourceMappingURLs from comments, strings, etc.
var lastMatch, match;
while (match = re.exec(fileData)) lastMatch = match;
if (!lastMatch) return null;
return lastMatch[1];
};
// Can be overridden by the retrieveSourceMap option to install. Takes a
// generated source filename; returns a {map, optional url} object, or null if
// there is no source map. The map field may be either a string or the parsed
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
// constructor).
/** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */
var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers);
sharedData.internalRetrieveMapHandlers.push(function(source) {
var sourceMappingURL = retrieveSourceMapURL(source);
if (!sourceMappingURL) return null;
// Read the contents of the source map
var sourceMapData;
if (reSourceMap.test(sourceMappingURL)) {
// Support source map URL as a data url
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
sourceMapData = Buffer.from(rawData, "base64").toString();
sourceMappingURL = source;
} else {
// Support source map URLs relative to the source URL
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL));
}
if (!sourceMapData) {
return null;
}
return {
url: sourceMappingURL,
map: sourceMapData
};
});
function mapSourcePosition(position) {
var sourceMap = getSourceMapCache(position.source);
if (!sourceMap) {
// Call the (overrideable) retrieveSourceMap function to get the source map.
var urlAndMap = retrieveSourceMap(position.source);
if (urlAndMap) {
sourceMap = setSourceMapCache(position.source, {
url: urlAndMap.url,
map: new AnyMap(urlAndMap.map, urlAndMap.url)
});
// Overwrite trace-mapping's resolutions, because they do not handle
// Windows paths the way we want.
// TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping?
sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s));
// Load all sources stored inline with the source map into the file cache
// to pretend like they are already loaded. They may not exist on disk.
if (sourceMap.map.sourcesContent) {
sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) {
var contents = sourceMap.map.sourcesContent[i];
if (contents) {
setFileContentsCache(resolvedSource, contents);
}
});
}
} else {
sourceMap = setSourceMapCache(position.source, {
url: null,
map: null
});
}
}
// Resolve the source URL relative to the URL of the source map
if (sourceMap && sourceMap.map) {
var originalPosition = originalPositionFor(sourceMap.map, position);
// Only return the original position if a matching line was found. If no
// matching line is found then we return position instead, which will cause
// the stack trace to print the path and line for the compiled file. It is
// better to give a precise location in the compiled file than a vague
// location in the original file.
if (originalPosition.source !== null) {
// originalPosition.source has *already* been resolved against sourceMap.url
// so is *already* as absolute as possible.
// However, we want to ensure we output in same format as input: URL or native path
originalPosition.source = matchStyleOfPathOrUrl(
position.source, originalPosition.source);
return originalPosition;
}
}
return position;
}
// Parses code generated by FormatEvalOrigin(), a function inside V8:
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
function mapEvalOrigin(origin) {
// Most eval() calls are in this format
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
if (match) {
var position = mapSourcePosition({
source: match[2],
line: +match[3],
column: match[4] - 1
});
return 'eval at ' + match[1] + ' (' + position.source + ':' +
position.line + ':' + (position.column + 1) + ')';
}
// Parse nested eval() calls using recursion
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
if (match) {
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
}
// Make sure we still return useful information if we didn't find anything
return origin;
}
// This is copied almost verbatim from the V8 source code at
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
// Update 2022-04-29:
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750
// The implementation of wrapCallSite() used to just forward to the actual source
// code of CallSite.prototype.toString but unfortunately a new release of V8
// did something to the prototype chain and broke the shim. The only fix I
// could find was copy/paste.
function CallSiteToString() {
var fileName;
var fileLocation = "";
if (this.isNative()) {
fileLocation = "native";
} else {
fileName = this.getScriptNameOrSourceURL();
if (!fileName && this.isEval()) {
fileLocation = this.getEvalOrigin();
fileLocation += ", "; // Expecting source position to follow.
}
if (fileName) {
fileLocation += fileName;
} else {
// Source code does not originate from a file and is not native, but we
// can still get the source position inside the source string, e.g. in
// an eval string.
fileLocation += "<anonymous>";
}
var lineNumber = this.getLineNumber();
if (lineNumber != null) {
fileLocation += ":" + lineNumber;
var columnNumber = this.getColumnNumber();
if (columnNumber) {
fileLocation += ":" + columnNumber;
}
}
}
var line = "";
var isAsync = this.isAsync ? this.isAsync() : false;
if(isAsync) {
line += 'async ';
var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false;
var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false;
if(isPromiseAny || isPromiseAll) {
line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index ';
var promiseIndex = this.getPromiseIndex();
line += promiseIndex + ')';
}
}
var functionName = this.getFunctionName();
var addSuffix = true;
var isConstructor = this.isConstructor();
var isMethodCall = !(this.isToplevel() || isConstructor);
if (isMethodCall) {
var typeName = this.getTypeName();
// Fixes shim to be backward compatable with Node v0 to v4
if (typeName === "[object Object]") {
typeName = "null";
}
var methodName = this.getMethodName();
if (functionName) {
if (typeName && functionName.indexOf(typeName) != 0) {
line += typeName + ".";
}
line += functionName;
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
line += " [as " + methodName + "]";
}
} else {
line += typeName + "." + (methodName || "<anonymous>");
}
} else if (isConstructor) {
line += "new " + (functionName || "<anonymous>");
} else if (functionName) {
line += functionName;
} else {
line += fileLocation;
addSuffix = false;
}
if (addSuffix) {
line += " (" + fileLocation + ")";
}
return line;
}
function cloneCallSite(frame) {
var object = {};
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
});
object.toString = CallSiteToString;
return object;
}
function wrapCallSite(frame, state) {
// provides interface backward compatibility
if (state === undefined) {
state = { nextPosition: null, curPosition: null }
}
if(frame.isNative()) {
state.curPosition = null;
return frame;
}
// Most call sites will return the source file from getFileName(), but code
// passed to eval() ending in "//# sourceURL=..." will return the source file
// from getScriptNameOrSourceURL() instead
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
if (source) {
// v8 does not expose its internal isWasm, etc methods, so we do this instead.
if(source.startsWith('wasm://')) {
state.curPosition = null;
return frame;
}
var line = frame.getLineNumber();
var column = frame.getColumnNumber() - 1;
// Fix position in Node where some (internal) code is prepended.
// See https://github.com/evanw/node-source-map-support/issues/36
// Header removed in node at ^10.16 || >=11.11.0
// v11 is not an LTS candidate, we can just test the one version with it.
// Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
var headerLength = noHeader.test(process.version) ? 0 : 62;
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
column -= headerLength;
}
var position = mapSourcePosition({
source: source,
line: line,
column: column
});
state.curPosition = position;
frame = cloneCallSite(frame);
var originalFunctionName = frame.getFunctionName;
frame.getFunctionName = function() {
if (state.nextPosition == null) {
return originalFunctionName();
}
return state.nextPosition.name || originalFunctionName();
};
frame.getFileName = function() { return position.source; };
frame.getLineNumber = function() { return position.line; };
frame.getColumnNumber = function() { return position.column + 1; };
frame.getScriptNameOrSourceURL = function() { return position.source; };
return frame;
}
// Code called using eval() needs special handling
var origin = frame.isEval() && frame.getEvalOrigin();
if (origin) {
origin = mapEvalOrigin(origin);
frame = cloneCallSite(frame);
frame.getEvalOrigin = function() { return origin; };
return frame;
}
// If we get here then we were unable to change the source position
return frame;
}
var kIsNodeError = undefined;
try {
// Get a deliberate ERR_INVALID_ARG_TYPE
// TODO is there a better way to reliably get an instance of NodeError?
path.resolve(123);
} catch(e) {
const symbols = Object.getOwnPropertySymbols(e);
const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0});
if(symbol) kIsNodeError = symbol;
}
const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err);
/** @param {HookState} hookState */
function createPrepareStackTrace(hookState) {
return prepareStackTrace;
// This function is part of the V8 stack trace API, for more info see:
// https://v8.dev/docs/stack-trace-api
function prepareStackTrace(error, stack) {
if(!hookState.enabled) return hookState.originalValue.apply(this, arguments);
if (sharedData.emptyCacheBetweenOperations) {
clearCaches();
}
// node gives its own errors special treatment. Mimic that behavior
// https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128
// https://github.com/nodejs/node/pull/39182
var errorString;
if (kIsNodeError) {
if(kIsNodeError in error) {
errorString = `${error.name} [${error.code}]: ${error.message}`;
} else {
errorString = ErrorPrototypeToString(error);
}
} else {
var name = error.name || 'Error';
var message = error.message || '';
errorString = message ? name + ": " + message : name;
}
var state = { nextPosition: null, curPosition: null };
var processedStack = [];
for (var i = stack.length - 1; i >= 0; i--) {
processedStack.push('\n at ' + wrapCallSite(stack[i], state));
state.nextPosition = state.curPosition;
}
state.curPosition = state.nextPosition = null;
return errorString + processedStack.reverse().join('');
}
}
// Generate position and snippet of original source with pointer
function getErrorSource(error) {
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
if (match) {
var source = match[1];
var line = +match[2];
var column = +match[3];
// Support the inline sourceContents inside the source map
var contents = getFileContentsCache(source);
const sourceAsPath = tryFileURLToPath(source);
// Support files on disk
if (!contents && fs && fs.existsSync(sourceAsPath)) {
try {
contents = fs.readFileSync(sourceAsPath, 'utf8');
} catch (er) {
contents = '';
}
}
// Format the line from the original source code like node does
if (contents) {
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
if (code) {
return source + ':' + line + '\n' + code + '\n' +
new Array(column).join(' ') + '^';
}
}
}
return null;
}
function printFatalErrorUponExit (error) {
var source = getErrorSource(error);
// Ensure error is printed synchronously and not truncated
if (process.stderr._handle && process.stderr._handle.setBlocking) {
process.stderr._handle.setBlocking(true);
}
if (source) {
console.error(source);
}
// Matches node's behavior for colorized output
console.error(
util.inspect(error, {
customInspect: false,
colors: process.stderr.isTTY
})
);
}
function shimEmitUncaughtException () {
const originalValue = process.emit;
var hook = sharedData.processEmitHook = {
enabled: true,
originalValue,
installedValue: undefined
};
var isTerminatingDueToFatalException = false;
var fatalException;
process.emit = sharedData.processEmitHook.installedValue = function (type) {
const hadListeners = originalValue.apply(this, arguments);
if(hook.enabled) {
if (type === 'uncaughtException' && !hadListeners) {
isTerminatingDueToFatalException = true;
fatalException = arguments[1];
process.exit(1);
}
if (type === 'exit' && isTerminatingDueToFatalException) {
printFatalErrorUponExit(fatalException);
}
}
return hadListeners;
};
}
var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0);
var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0);
exports.wrapCallSite = wrapCallSite;
exports.getErrorSource = getErrorSource;
exports.mapSourcePosition = mapSourcePosition;
exports.retrieveSourceMap = retrieveSourceMap;
exports.install = function(options) {
options = options || {};
if (options.environment) {
environment = options.environment;
if (["node", "browser", "auto"].indexOf(environment) === -1) {
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
}
}
// Use dynamicRequire to avoid including in browser bundles
var Module = dynamicRequire(module, 'module');
// Redirect subsequent imports of "source-map-support"
// to this package
const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options;
if(redirectConflictingLibrary) {
if (!sharedData.moduleResolveFilenameHook) {
const originalValue = Module._resolveFilename;
const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = {
enabled: true,
originalValue,
installedValue: undefined,
}
Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) {
if (moduleResolveFilenameHook.enabled) {
// Match all source-map-support entrypoints: source-map-support, source-map-support/register
let requestRedirect;
if (request === 'source-map-support') {
requestRedirect = './';
} else if (request === 'source-map-support/register') {
requestRedirect = './register';
}
if (requestRedirect !== undefined) {
const newRequest = require.resolve(requestRedirect);
for (const cb of sharedData.onConflictingLibraryRedirectArr) {
cb(request, parent, isMain, options, newRequest);
}
request = newRequest;
}
}
return originalValue.call(this, request, parent, isMain, options);
}
}
if (onConflictingLibraryRedirect) {
sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect);
}
}
// Allow sources to be found by methods other than reading the files
// directly from disk.
if (options.retrieveFile) {
if (options.overrideRetrieveFile) {
sharedData.retrieveFileHandlers.length = 0;
}
sharedData.retrieveFileHandlers.unshift(options.retrieveFile);
}
// Allow source maps to be found by methods other than reading the files
// directly from disk.
if (options.retrieveSourceMap) {
if (options.overrideRetrieveSourceMap) {
sharedData.retrieveMapHandlers.length = 0;
}
sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap);
}
// Support runtime transpilers that include inline source maps
if (options.hookRequire && !isInBrowser()) {
var $compile = Module.prototype._compile;
if (!$compile.__sourceMapSupport) {
Module.prototype._compile = function(content, filename) {
setFileContentsCache(filename, content);
setSourceMapCache(filename, undefined);
return $compile.call(this, content, filename);
};
Module.prototype._compile.__sourceMapSupport = true;
}
}
// Configure options
if (!sharedData.emptyCacheBetweenOperations) {
sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
options.emptyCacheBetweenOperations : false;
}
// Install the error reformatter
if (!sharedData.errorPrepareStackTraceHook) {
const originalValue = Error.prepareStackTrace;
sharedData.errorPrepareStackTraceHook = {
enabled: true,
originalValue,
installedValue: undefined
};
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook);
}
if (!sharedData.processEmitHook) {
var installHandler = 'handleUncaughtExceptions' in options ?
options.handleUncaughtExceptions : true;
// Do not override 'uncaughtException' with our own handler in Node.js
// Worker threads. Workers pass the error to the main thread as an event,
// rather than printing something to stderr and exiting.
try {
// We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
var worker_threads = dynamicRequire(module, 'worker_threads');
if (worker_threads.isMainThread === false) {
installHandler = false;
}
} catch(e) {}
// Provide the option to not install the uncaught exception handler. This is
// to support other uncaught exception handlers (in test frameworks, for
// example). If this handler is not installed and there are no other uncaught
// exception handlers, uncaught exceptions will be caught by node's built-in
// exception handler and the process will still be terminated. However, the
// generated JavaScript code will be shown above the stack trace instead of
// the original source code.
if (installHandler && hasGlobalProcessEventEmitter()) {
shimEmitUncaughtException();
}
}
};
exports.uninstall = function() {
if(sharedData.processEmitHook) {
// Disable behavior
sharedData.processEmitHook.enabled = false;
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
if(process.emit === sharedData.processEmitHook.installedValue) {
process.emit = sharedData.processEmitHook.originalValue;
}
sharedData.processEmitHook = undefined;
}
if(sharedData.errorPrepareStackTraceHook) {
// Disable behavior
sharedData.errorPrepareStackTraceHook.enabled = false;
// If possible or necessary, remove our hook function.
// In vanilla environments, prepareStackTrace is `undefined`.
// We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function.
// If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both.
if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') {
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue;
}
sharedData.errorPrepareStackTraceHook = undefined;
}
if (sharedData.moduleResolveFilenameHook) {
// Disable behavior
sharedData.moduleResolveFilenameHook.enabled = false;
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
var Module = dynamicRequire(module, 'module');
if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) {
Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue;
}
sharedData.moduleResolveFilenameHook = undefined;
}
sharedData.onConflictingLibraryRedirectArr.length = 0;
}
exports.resetRetrieveHandlers = function() {
sharedData.retrieveFileHandlers.length = 0;
sharedData.retrieveMapHandlers.length = 0;
}

373
node_modules/@ethereumjs/rlp/LICENSE generated vendored
View file

@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -1,107 +0,0 @@
# @ethereumjs/rlp
[![NPM Package][rlp-npm-badge]][rlp-npm-link]
[![GitHub Issues][rlp-issues-badge]][rlp-issues-link]
[![Actions Status][rlp-actions-badge]][rlp-actions-link]
[![Code Coverage][rlp-coverage-badge]][rlp-coverage-link]
[![Discord][discord-badge]][discord-link]
[Recursive Length Prefix](https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp) encoding for Node.js and the browser.
## Installation
To obtain the latest version, simply require the project using `npm`:
```shell
npm install @ethereumjs/rlp
```
Install with `-g` if you want to use the CLI.
## Usage
```typescript
import assert from 'assert'
import { RLP } from '@ethereumjs/rlp'
const nestedList = [[], [[]], [[], [[]]]]
const encoded = RLP.encode(nestedList)
const decoded = RLP.decode(encoded)
assert.deepEqual(nestedList, decoded)
```
## API
`RLP.encode(plain)` - RLP encodes an `Array`, `Uint8Array` or `String` and returns a `Uint8Array`.
`RLP.decode(encoded, [stream=false])` - Decodes an RLP encoded `Uint8Array`, `Array` or `String` and returns a `Uint8Array` or `NestedUint8Array`. If `stream` is enabled, it will just decode the first rlp sequence in the Uint8Array. By default, it would throw an error if there are more bytes in Uint8Array than used by the rlp sequence.
### Buffer compatibility
If you would like to continue using Buffers like in rlp v2, you can use:
```typescript
import assert from 'assert'
import { arrToBufArr, bufArrToArr } from '@ethereumjs/util'
import { RLP } from '@ethereumjs/rlp'
const bufferList = [Buffer.from('123', 'hex'), Buffer.from('456', 'hex')]
const encoded = RLP.encode(bufArrToArr(bufferList))
const encodedAsBuffer = Buffer.from(encoded)
const decoded = RLP.decode(Uint8Array.from(encodedAsBuffer)) // or RLP.decode(encoded)
const decodedAsBuffers = arrToBufArr(decoded)
assert.deepEqual(bufferList, decodedAsBuffers)
```
### BigInt Support
Starting with v4 the usage of [BN.js](https://github.com/indutny/bn.js/) for big numbers has been removed from the library and replaced with the usage of the native JS [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) data type (introduced in `ES2020`).
Please note that number-related API signatures have changed along with this version update and the minimal build target has been updated to `ES2020`.
## CLI
`rlp encode <JSON string>`\
`rlp decode <0x-prefixed hex string>`
### Examples
- `rlp encode '5'` -> `0x05`
- `rlp encode '[5]'` -> `0xc105`
- `rlp encode '["cat", "dog"]'` -> `0xc88363617483646f67`
- `rlp decode 0xc88363617483646f67` -> `["cat","dog"]`
## Tests
Tests use mocha.
To run tests and linting: `npm test`
To auto-fix linting problems run: `npm run lint:fix`
## Code Coverage
Install dev dependencies: `npm install`
Run coverage: `npm run coverage`
The results will be at: `coverage/lcov-report/index.html`
## EthereumJS
See our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices. If you want to join for work or carry out improvements on the libraries, please review our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html) first.
## License
[MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)
[discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue
[discord-link]: https://discord.gg/TNwARpR
[rlp-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/rlp.svg
[rlp-npm-link]: https://www.npmjs.com/package/@ethereumjs/rlp
[rlp-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20rlp?label=issues
[rlp-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+rlp"
[rlp-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/rlp/badge.svg
[rlp-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22rlp%22
[rlp-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=rlp
[rlp-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp

58
node_modules/@ethereumjs/rlp/bin/rlp generated vendored
View file

@ -1,58 +0,0 @@
#!/usr/bin/env node
const RLP = require('../dist/index.js')
const method = process.argv[2]
const strInput = process.argv[3]
const { bytesToHex } = RLP.utils
if (typeof strInput !== 'string') {
return console.error(`Expected JSON string input, received type: ${typeof strInput}`)
}
if (method === 'encode') {
// Parse JSON
let json
try {
json = JSON.parse(strInput)
} catch (error) {
const errorMsg = error.message ? error.message : error
return console.error(`Error could not parse JSON: ${errorMsg}`)
}
// Encode RLP
try {
const encoded = RLP.encode(json)
console.log('0x' + bytesToHex(encoded))
} catch (error) {
const errorMsg = error.message ? error.message : error
console.error(`Error encoding RLP: ${errorMsg}`)
}
} else if (method === 'decode') {
// Decode
try {
const decoded = RLP.decode(strInput)
const json = JSON.stringify(arrToJSON(decoded))
console.log(json)
} catch (error) {
const errorMsg = error.message ? error.message : error
console.error(`Error decoding RLP: ${errorMsg}`)
}
} else {
console.error('Unsupported method')
}
/**
* Uint8Array or Array<Uint8Array> to JSON
*/
function arrToJSON(ba) {
if (ba instanceof Uint8Array) {
return bytesToHex(ba)
} else if (ba instanceof Array) {
const arr = []
for (let i = 0; i < ba.length; i++) {
arr.push(arrToJSON(ba[i]))
}
return arr
}
}

View file

@ -1,39 +0,0 @@
export declare type Input = string | number | bigint | Uint8Array | Array<Input> | null | undefined;
export declare type NestedUint8Array = Array<Uint8Array | NestedUint8Array>;
export interface Decoded {
data: Uint8Array | NestedUint8Array;
remainder: Uint8Array;
}
/**
* RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
* This function takes in data, converts it to Uint8Array if not,
* and adds a length for recursion.
* @param input Will be converted to Uint8Array
* @returns Uint8Array of encoded data
**/
export declare function encode(input: Input): Uint8Array;
/**
* RLP Decoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
* @param input Will be converted to Uint8Array
* @param stream Is the input a stream (false by default)
* @returns decoded Array of Uint8Arrays containing the original message
**/
export declare function decode(input: Input, stream?: false): Uint8Array | NestedUint8Array;
export declare function decode(input: Input, stream?: true): Decoded;
declare function bytesToHex(uint8a: Uint8Array): string;
declare function hexToBytes(hex: string): Uint8Array;
/** Concatenates two Uint8Arrays into one. */
declare function concatBytes(...arrays: Uint8Array[]): Uint8Array;
declare function utf8ToBytes(utf: string): Uint8Array;
export declare const utils: {
bytesToHex: typeof bytesToHex;
concatBytes: typeof concatBytes;
hexToBytes: typeof hexToBytes;
utf8ToBytes: typeof utf8ToBytes;
};
export declare const RLP: {
encode: typeof encode;
decode: typeof decode;
};
export {};
//# sourceMappingURL=index.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,oBAAY,KAAK,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,UAAU,GAAG,KAAK,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,SAAS,CAAA;AAE3F,oBAAY,gBAAgB,GAAG,KAAK,CAAC,UAAU,GAAG,gBAAgB,CAAC,CAAA;AAEnE,MAAM,WAAW,OAAO;IACtB,IAAI,EAAE,UAAU,GAAG,gBAAgB,CAAA;IACnC,SAAS,EAAE,UAAU,CAAA;CACtB;AAED;;;;;;IAMI;AACJ,wBAAgB,MAAM,CAAC,KAAK,EAAE,KAAK,GAAG,UAAU,CAgB/C;AAqCD;;;;;IAKI;AACJ,wBAAgB,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,KAAK,GAAG,UAAU,GAAG,gBAAgB,CAAA;AACnF,wBAAgB,MAAM,CAAC,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,EAAE,IAAI,GAAG,OAAO,CAAA;AA8G5D,iBAAS,UAAU,CAAC,MAAM,EAAE,UAAU,GAAG,MAAM,CAO9C;AASD,iBAAS,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAW3C;AAED,6CAA6C;AAC7C,iBAAS,WAAW,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,GAAG,UAAU,CAUxD;AAOD,iBAAS,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAE5C;AAoDD,eAAO,MAAM,KAAK;;;;;CAKjB,CAAA;AAED,eAAO,MAAM,GAAG;;;CAAqB,CAAA"}

View file

@ -1,258 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RLP = exports.utils = exports.decode = exports.encode = void 0;
/**
* RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
* This function takes in data, converts it to Uint8Array if not,
* and adds a length for recursion.
* @param input Will be converted to Uint8Array
* @returns Uint8Array of encoded data
**/
function encode(input) {
if (Array.isArray(input)) {
const output = [];
let outputLength = 0;
for (let i = 0; i < input.length; i++) {
const encoded = encode(input[i]);
output.push(encoded);
outputLength += encoded.length;
}
return concatBytes(encodeLength(outputLength, 192), ...output);
}
const inputBuf = toBytes(input);
if (inputBuf.length === 1 && inputBuf[0] < 128) {
return inputBuf;
}
return concatBytes(encodeLength(inputBuf.length, 128), inputBuf);
}
exports.encode = encode;
/**
* Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array.
* E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw.
* @param input
* @param start
* @param end
*/
function safeSlice(input, start, end) {
if (end > input.length) {
throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds');
}
return input.slice(start, end);
}
/**
* Parse integers. Check if there is no leading zeros
* @param v The value to parse
*/
function decodeLength(v) {
if (v[0] === 0) {
throw new Error('invalid RLP: extra zeros');
}
return parseHexByte(bytesToHex(v));
}
function encodeLength(len, offset) {
if (len < 56) {
return Uint8Array.from([len + offset]);
}
const hexLength = numberToHex(len);
const lLength = hexLength.length / 2;
const firstByte = numberToHex(offset + 55 + lLength);
return Uint8Array.from(hexToBytes(firstByte + hexLength));
}
function decode(input, stream = false) {
if (typeof input === 'undefined' || input === null || input.length === 0) {
return Uint8Array.from([]);
}
const inputBytes = toBytes(input);
const decoded = _decode(inputBytes);
if (stream) {
return decoded;
}
if (decoded.remainder.length !== 0) {
throw new Error('invalid RLP: remainder must be zero');
}
return decoded.data;
}
exports.decode = decode;
/** Decode an input with RLP */
function _decode(input) {
let length, llength, data, innerRemainder, d;
const decoded = [];
const firstByte = input[0];
if (firstByte <= 0x7f) {
// a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding.
return {
data: input.slice(0, 1),
remainder: input.slice(1),
};
}
else if (firstByte <= 0xb7) {
// string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string
// The range of the first byte is [0x80, 0xb7]
length = firstByte - 0x7f;
// set 0x80 null to 0
if (firstByte === 0x80) {
data = Uint8Array.from([]);
}
else {
data = safeSlice(input, 1, length);
}
if (length === 2 && data[0] < 0x80) {
throw new Error('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed');
}
return {
data,
remainder: input.slice(length),
};
}
else if (firstByte <= 0xbf) {
// string is greater than 55 bytes long. A single byte with the value (0xb7 plus the length of the length),
// followed by the length, followed by the string
llength = firstByte - 0xb6;
if (input.length - 1 < llength) {
throw new Error('invalid RLP: not enough bytes for string length');
}
length = decodeLength(safeSlice(input, 1, llength));
if (length <= 55) {
throw new Error('invalid RLP: expected string length to be greater than 55');
}
data = safeSlice(input, llength, length + llength);
return {
data,
remainder: input.slice(length + llength),
};
}
else if (firstByte <= 0xf7) {
// a list between 0-55 bytes long
length = firstByte - 0xbf;
innerRemainder = safeSlice(input, 1, length);
while (innerRemainder.length) {
d = _decode(innerRemainder);
decoded.push(d.data);
innerRemainder = d.remainder;
}
return {
data: decoded,
remainder: input.slice(length),
};
}
else {
// a list over 55 bytes long
llength = firstByte - 0xf6;
length = decodeLength(safeSlice(input, 1, llength));
if (length < 56) {
throw new Error('invalid RLP: encoded list too short');
}
const totalLength = llength + length;
if (totalLength > input.length) {
throw new Error('invalid RLP: total length is larger than the data');
}
innerRemainder = safeSlice(input, llength, totalLength);
while (innerRemainder.length) {
d = _decode(innerRemainder);
decoded.push(d.data);
innerRemainder = d.remainder;
}
return {
data: decoded,
remainder: input.slice(totalLength),
};
}
}
const cachedHexes = Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));
function bytesToHex(uint8a) {
// Pre-caching chars with `cachedHexes` speeds this up 6x
let hex = '';
for (let i = 0; i < uint8a.length; i++) {
hex += cachedHexes[uint8a[i]];
}
return hex;
}
function parseHexByte(hexByte) {
const byte = Number.parseInt(hexByte, 16);
if (Number.isNaN(byte))
throw new Error('Invalid byte sequence');
return byte;
}
// Caching slows it down 2-3x
function hexToBytes(hex) {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex);
}
if (hex.length % 2)
throw new Error('hexToBytes: received invalid unpadded hex');
const array = new Uint8Array(hex.length / 2);
for (let i = 0; i < array.length; i++) {
const j = i * 2;
array[i] = parseHexByte(hex.slice(j, j + 2));
}
return array;
}
/** Concatenates two Uint8Arrays into one. */
function concatBytes(...arrays) {
if (arrays.length === 1)
return arrays[0];
const length = arrays.reduce((a, arr) => a + arr.length, 0);
const result = new Uint8Array(length);
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i];
result.set(arr, pad);
pad += arr.length;
}
return result;
}
function utf8ToBytes(utf) {
return new TextEncoder().encode(utf);
}
/** Transform an integer into its hexadecimal value */
function numberToHex(integer) {
if (integer < 0) {
throw new Error('Invalid integer as argument, must be unsigned!');
}
const hex = integer.toString(16);
return hex.length % 2 ? `0${hex}` : hex;
}
/** Pad a string to be even */
function padToEven(a) {
return a.length % 2 ? `0${a}` : a;
}
/** Check if a string is prefixed by 0x */
function isHexPrefixed(str) {
return str.length >= 2 && str[0] === '0' && str[1] === 'x';
}
/** Removes 0x from a given String */
function stripHexPrefix(str) {
if (typeof str !== 'string') {
return str;
}
return isHexPrefixed(str) ? str.slice(2) : str;
}
/** Transform anything into a Uint8Array */
function toBytes(v) {
if (v instanceof Uint8Array) {
return v;
}
if (typeof v === 'string') {
if (isHexPrefixed(v)) {
return hexToBytes(padToEven(stripHexPrefix(v)));
}
return utf8ToBytes(v);
}
if (typeof v === 'number' || typeof v === 'bigint') {
if (!v) {
return Uint8Array.from([]);
}
return hexToBytes(numberToHex(v));
}
if (v === null || v === undefined) {
return Uint8Array.from([]);
}
throw new Error('toBytes: received unsupported type ' + typeof v);
}
exports.utils = {
bytesToHex,
concatBytes,
hexToBytes,
utf8ToBytes,
};
exports.RLP = { encode, decode };
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,54 +0,0 @@
{
"name": "@ethereumjs/rlp",
"version": "4.0.1",
"description": "Recursive Length Prefix Encoding Module",
"keywords": [
"rlp",
"ethereum"
],
"homepage": "https://github.com/ethereumjs/ethereumjs-monorepo/tree/master/packages/rlp#readme",
"bugs": {
"url": "https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aissue+label%3A%22package%3A+rlp%22"
},
"repository": {
"type": "git",
"url": "https://github.com/ethereumjs/ethereumjs-monorepo.git"
},
"license": "MPL-2.0",
"author": {
"name": "martin becze",
"email": "mjbecze@gmail.com"
},
"contributors": [
"Alex Beregszaszi <alex@rtfs.hu>",
"Holger Drewes <Holger.Drewes@gmail.com>",
"Paul Miller <pkg@paulmillr.com>"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"bin": {
"rlp": "bin/rlp"
},
"files": [
"dist",
"bin",
"src"
],
"scripts": {
"build": "../../config/cli/ts-build.sh node",
"clean": "../../config/cli/clean-package.sh",
"coverage": "../../config/cli/coverage.sh",
"lint": "../../config/cli/lint.sh",
"lint:diff": "../../config/cli/lint-diff.sh",
"lint:fix": "../../config/cli/lint-fix.sh",
"prepublishOnly": "../../config/cli/prepublish.sh",
"tape": "tape -r ts-node/register",
"test": "npm run test:node && npm run test:browser",
"test:browser": "karma start karma.conf.js",
"test:node": "npm run tape -- test/*.spec.ts",
"tsc": "../../config/cli/ts-compile.sh"
},
"engines": {
"node": ">=14"
}
}

View file

@ -1,295 +0,0 @@
export type Input = string | number | bigint | Uint8Array | Array<Input> | null | undefined
export type NestedUint8Array = Array<Uint8Array | NestedUint8Array>
export interface Decoded {
data: Uint8Array | NestedUint8Array
remainder: Uint8Array
}
/**
* RLP Encoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
* This function takes in data, converts it to Uint8Array if not,
* and adds a length for recursion.
* @param input Will be converted to Uint8Array
* @returns Uint8Array of encoded data
**/
export function encode(input: Input): Uint8Array {
if (Array.isArray(input)) {
const output: Uint8Array[] = []
let outputLength = 0
for (let i = 0; i < input.length; i++) {
const encoded = encode(input[i])
output.push(encoded)
outputLength += encoded.length
}
return concatBytes(encodeLength(outputLength, 192), ...output)
}
const inputBuf = toBytes(input)
if (inputBuf.length === 1 && inputBuf[0] < 128) {
return inputBuf
}
return concatBytes(encodeLength(inputBuf.length, 128), inputBuf)
}
/**
* Slices a Uint8Array, throws if the slice goes out-of-bounds of the Uint8Array.
* E.g. `safeSlice(hexToBytes('aa'), 1, 2)` will throw.
* @param input
* @param start
* @param end
*/
function safeSlice(input: Uint8Array, start: number, end: number) {
if (end > input.length) {
throw new Error('invalid RLP (safeSlice): end slice of Uint8Array out-of-bounds')
}
return input.slice(start, end)
}
/**
* Parse integers. Check if there is no leading zeros
* @param v The value to parse
*/
function decodeLength(v: Uint8Array): number {
if (v[0] === 0) {
throw new Error('invalid RLP: extra zeros')
}
return parseHexByte(bytesToHex(v))
}
function encodeLength(len: number, offset: number): Uint8Array {
if (len < 56) {
return Uint8Array.from([len + offset])
}
const hexLength = numberToHex(len)
const lLength = hexLength.length / 2
const firstByte = numberToHex(offset + 55 + lLength)
return Uint8Array.from(hexToBytes(firstByte + hexLength))
}
/**
* RLP Decoding based on https://ethereum.org/en/developers/docs/data-structures-and-encoding/rlp/
* @param input Will be converted to Uint8Array
* @param stream Is the input a stream (false by default)
* @returns decoded Array of Uint8Arrays containing the original message
**/
export function decode(input: Input, stream?: false): Uint8Array | NestedUint8Array
export function decode(input: Input, stream?: true): Decoded
export function decode(input: Input, stream = false): Uint8Array | NestedUint8Array | Decoded {
if (typeof input === 'undefined' || input === null || (input as any).length === 0) {
return Uint8Array.from([])
}
const inputBytes = toBytes(input)
const decoded = _decode(inputBytes)
if (stream) {
return decoded
}
if (decoded.remainder.length !== 0) {
throw new Error('invalid RLP: remainder must be zero')
}
return decoded.data
}
/** Decode an input with RLP */
function _decode(input: Uint8Array): Decoded {
let length: number, llength: number, data: Uint8Array, innerRemainder: Uint8Array, d: Decoded
const decoded = []
const firstByte = input[0]
if (firstByte <= 0x7f) {
// a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding.
return {
data: input.slice(0, 1),
remainder: input.slice(1),
}
} else if (firstByte <= 0xb7) {
// string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string
// The range of the first byte is [0x80, 0xb7]
length = firstByte - 0x7f
// set 0x80 null to 0
if (firstByte === 0x80) {
data = Uint8Array.from([])
} else {
data = safeSlice(input, 1, length)
}
if (length === 2 && data[0] < 0x80) {
throw new Error('invalid RLP encoding: invalid prefix, single byte < 0x80 are not prefixed')
}
return {
data,
remainder: input.slice(length),
}
} else if (firstByte <= 0xbf) {
// string is greater than 55 bytes long. A single byte with the value (0xb7 plus the length of the length),
// followed by the length, followed by the string
llength = firstByte - 0xb6
if (input.length - 1 < llength) {
throw new Error('invalid RLP: not enough bytes for string length')
}
length = decodeLength(safeSlice(input, 1, llength))
if (length <= 55) {
throw new Error('invalid RLP: expected string length to be greater than 55')
}
data = safeSlice(input, llength, length + llength)
return {
data,
remainder: input.slice(length + llength),
}
} else if (firstByte <= 0xf7) {
// a list between 0-55 bytes long
length = firstByte - 0xbf
innerRemainder = safeSlice(input, 1, length)
while (innerRemainder.length) {
d = _decode(innerRemainder)
decoded.push(d.data)
innerRemainder = d.remainder
}
return {
data: decoded,
remainder: input.slice(length),
}
} else {
// a list over 55 bytes long
llength = firstByte - 0xf6
length = decodeLength(safeSlice(input, 1, llength))
if (length < 56) {
throw new Error('invalid RLP: encoded list too short')
}
const totalLength = llength + length
if (totalLength > input.length) {
throw new Error('invalid RLP: total length is larger than the data')
}
innerRemainder = safeSlice(input, llength, totalLength)
while (innerRemainder.length) {
d = _decode(innerRemainder)
decoded.push(d.data)
innerRemainder = d.remainder
}
return {
data: decoded,
remainder: input.slice(totalLength),
}
}
}
const cachedHexes = Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'))
function bytesToHex(uint8a: Uint8Array): string {
// Pre-caching chars with `cachedHexes` speeds this up 6x
let hex = ''
for (let i = 0; i < uint8a.length; i++) {
hex += cachedHexes[uint8a[i]]
}
return hex
}
function parseHexByte(hexByte: string): number {
const byte = Number.parseInt(hexByte, 16)
if (Number.isNaN(byte)) throw new Error('Invalid byte sequence')
return byte
}
// Caching slows it down 2-3x
function hexToBytes(hex: string): Uint8Array {
if (typeof hex !== 'string') {
throw new TypeError('hexToBytes: expected string, got ' + typeof hex)
}
if (hex.length % 2) throw new Error('hexToBytes: received invalid unpadded hex')
const array = new Uint8Array(hex.length / 2)
for (let i = 0; i < array.length; i++) {
const j = i * 2
array[i] = parseHexByte(hex.slice(j, j + 2))
}
return array
}
/** Concatenates two Uint8Arrays into one. */
function concatBytes(...arrays: Uint8Array[]): Uint8Array {
if (arrays.length === 1) return arrays[0]
const length = arrays.reduce((a, arr) => a + arr.length, 0)
const result = new Uint8Array(length)
for (let i = 0, pad = 0; i < arrays.length; i++) {
const arr = arrays[i]
result.set(arr, pad)
pad += arr.length
}
return result
}
// Global symbols in both browsers and Node.js since v11
// See https://github.com/microsoft/TypeScript/issues/31535
declare const TextEncoder: any
declare const TextDecoder: any
function utf8ToBytes(utf: string): Uint8Array {
return new TextEncoder().encode(utf)
}
/** Transform an integer into its hexadecimal value */
function numberToHex(integer: number | bigint): string {
if (integer < 0) {
throw new Error('Invalid integer as argument, must be unsigned!')
}
const hex = integer.toString(16)
return hex.length % 2 ? `0${hex}` : hex
}
/** Pad a string to be even */
function padToEven(a: string): string {
return a.length % 2 ? `0${a}` : a
}
/** Check if a string is prefixed by 0x */
function isHexPrefixed(str: string): boolean {
return str.length >= 2 && str[0] === '0' && str[1] === 'x'
}
/** Removes 0x from a given String */
function stripHexPrefix(str: string): string {
if (typeof str !== 'string') {
return str
}
return isHexPrefixed(str) ? str.slice(2) : str
}
/** Transform anything into a Uint8Array */
function toBytes(v: Input): Uint8Array {
if (v instanceof Uint8Array) {
return v
}
if (typeof v === 'string') {
if (isHexPrefixed(v)) {
return hexToBytes(padToEven(stripHexPrefix(v)))
}
return utf8ToBytes(v)
}
if (typeof v === 'number' || typeof v === 'bigint') {
if (!v) {
return Uint8Array.from([])
}
return hexToBytes(numberToHex(v))
}
if (v === null || v === undefined) {
return Uint8Array.from([])
}
throw new Error('toBytes: received unsupported type ' + typeof v)
}
export const utils = {
bytesToHex,
concatBytes,
hexToBytes,
utf8ToBytes,
}
export const RLP = { encode, decode }

373
node_modules/@ethereumjs/util/LICENSE generated vendored
View file

@ -1,373 +0,0 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

View file

@ -1,104 +0,0 @@
# @ethereumjs/util
[![NPM Package][util-npm-badge]][util-npm-link]
[![GitHub Issues][util-issues-badge]][util-issues-link]
[![Actions Status][util-actions-badge]][util-actions-link]
[![Code Coverage][util-coverage-badge]][util-coverage-link]
[![Discord][discord-badge]][discord-link]
A collection of utility functions for Ethereum. It can be used in Node.js and in the browser with [browserify](http://browserify.org/).
## Installation
To obtain the latest version, simply require the project using `npm`:
```shell
npm install @ethereumjs/util
```
## Usage
```js
import assert from 'assert'
import { isValidChecksumAddress, unpadBuffer } from '@ethereumjs/util'
assert.ok(isValidChecksumAddress('0x2F015C60E0be116B1f0CD534704Db9c92118FB6A'))
assert.ok(unpadBuffer(Buffer.from('000000006600', 'hex')).equals(Buffer.from('6600', 'hex')))
```
## API
### Documentation
Read the [API docs](docs/).
### Modules
- [account](src/account.ts)
- Account class
- Private/public key and address-related functionality (creation, validation, conversion)
- [address](src/address.ts)
- Address class and type
- [bytes](src/bytes.ts)
- Byte-related helper and conversion functions
- [constants](src/constants.ts)
- Exposed constants
- e.g. `KECCAK256_NULL_S` for string representation of Keccak-256 hash of null
- hash
- This module has been removed with `v8`, please use [ethereum-cryptography](https://github.com/ethereum/js-ethereum-cryptography) directly instead
- [signature](src/signature.ts)
- Signing, signature validation, conversion, recovery
- [types](src/types.ts)
- Helpful TypeScript types
- [internal](src/internal.ts)
- Internalized helper methods
- [withdrawal](src/withdrawal.ts)
- Withdrawal class (EIP-4895)
### BigInt Support
Starting with v8 the usage of [BN.js](https://github.com/indutny/bn.js/) for big numbers has been removed from the library and replaced with the usage of the native JS [BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) data type (introduced in `ES2020`).
Please note that number-related API signatures have changed along with this version update and the minimal build target has been updated to `ES2020`.
### ethjs-util methods
The following methods are available by an internalized version of the [ethjs-util](https://github.com/ethjs/ethjs-util) package (`MIT` license), see [internal.ts](src/internal.ts). The original package is not maintained any more and the original functionality will be replaced by own implementations over time (starting with the `v7.1.3` release, October 2021).
- arrayContainsArray
- getBinarySize
- stripHexPrefix
- isHexPrefixed
- isHexString
- padToEven
- fromAscii
- fromUtf8
- toUtf8
- toAscii
- getKeys
They can be imported by name:
```typescript
import { stripHexPrefix } from '@ethereumjs/util'
```
## EthereumJS
See our organizational [documentation](https://ethereumjs.readthedocs.io) for an introduction to `EthereumJS` as well as information on current standards and best practices. If you want to join for work or carry out improvements on the libraries, please review our [contribution guidelines](https://ethereumjs.readthedocs.io/en/latest/contributing.html) first.
## License
[MPL-2.0](<https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)>)
[util-npm-badge]: https://img.shields.io/npm/v/@ethereumjs/util.svg
[util-npm-link]: https://www.npmjs.org/package/@ethereumjs/util
[util-issues-badge]: https://img.shields.io/github/issues/ethereumjs/ethereumjs-monorepo/package:%20util?label=issues
[util-issues-link]: https://github.com/ethereumjs/ethereumjs-monorepo/issues?q=is%3Aopen+is%3Aissue+label%3A"package%3A+util"
[util-actions-badge]: https://github.com/ethereumjs/ethereumjs-monorepo/workflows/Util/badge.svg
[util-actions-link]: https://github.com/ethereumjs/ethereumjs-monorepo/actions?query=workflow%3A%22Util%22
[util-coverage-badge]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/branch/master/graph/badge.svg?flag=util
[util-coverage-link]: https://codecov.io/gh/ethereumjs/ethereumjs-monorepo/tree/master/packages/util
[discord-badge]: https://img.shields.io/static/v1?logo=discord&label=discord&message=Join&color=blue
[discord-link]: https://discord.gg/TNwARpR

View file

@ -1,128 +0,0 @@
/// <reference types="node" />
import type { BigIntLike, BufferLike } from './types';
export interface AccountData {
nonce?: BigIntLike;
balance?: BigIntLike;
storageRoot?: BufferLike;
codeHash?: BufferLike;
}
export declare type AccountBodyBuffer = [Buffer, Buffer, Buffer | Uint8Array, Buffer | Uint8Array];
export declare class Account {
nonce: bigint;
balance: bigint;
storageRoot: Buffer;
codeHash: Buffer;
static fromAccountData(accountData: AccountData): Account;
static fromRlpSerializedAccount(serialized: Buffer): Account;
static fromValuesArray(values: Buffer[]): Account;
/**
* This constructor assigns and validates the values.
* Use the static factory methods to assist in creating an Account from varying data types.
*/
constructor(nonce?: bigint, balance?: bigint, storageRoot?: Buffer, codeHash?: Buffer);
private _validate;
/**
* Returns a Buffer Array of the raw Buffers for the account, in order.
*/
raw(): Buffer[];
/**
* Returns the RLP serialization of the account as a `Buffer`.
*/
serialize(): Buffer;
/**
* Returns a `Boolean` determining if the account is a contract.
*/
isContract(): boolean;
/**
* Returns a `Boolean` determining if the account is empty complying to the definition of
* account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161):
* "An account is considered empty when it has no code and zero nonce and zero balance."
*/
isEmpty(): boolean;
}
/**
* Checks if the address is a valid. Accepts checksummed addresses too.
*/
export declare const isValidAddress: (hexAddress: string) => boolean;
/**
* Returns a checksummed address.
*
* If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This
* has the effect of checksummed addresses for one chain having invalid checksums for others.
* For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191).
*
* WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not
* backwards compatible to the original widely adopted checksum format standard introduced in
* [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications.
* Usage of this EIP is therefore discouraged unless you have a very targeted use case.
*/
export declare const toChecksumAddress: (hexAddress: string, eip1191ChainId?: BigIntLike) => string;
/**
* Checks if the address is a valid checksummed address.
*
* See toChecksumAddress' documentation for details about the eip1191ChainId parameter.
*/
export declare const isValidChecksumAddress: (hexAddress: string, eip1191ChainId?: BigIntLike) => boolean;
/**
* Generates an address of a newly created contract.
* @param from The address which is creating this new address
* @param nonce The nonce of the from account
*/
export declare const generateAddress: (from: Buffer, nonce: Buffer) => Buffer;
/**
* Generates an address for a contract created using CREATE2.
* @param from The address which is creating this new address
* @param salt A salt
* @param initCode The init code of the contract being created
*/
export declare const generateAddress2: (from: Buffer, salt: Buffer, initCode: Buffer) => Buffer;
/**
* Checks if the private key satisfies the rules of the curve secp256k1.
*/
export declare const isValidPrivate: (privateKey: Buffer) => boolean;
/**
* Checks if the public key satisfies the rules of the curve secp256k1
* and the requirements of Ethereum.
* @param publicKey The two points of an uncompressed key, unless sanitize is enabled
* @param sanitize Accept public keys in other formats
*/
export declare const isValidPublic: (publicKey: Buffer, sanitize?: boolean) => boolean;
/**
* Returns the ethereum address of a given public key.
* Accepts "Ethereum public keys" and SEC1 encoded keys.
* @param pubKey The two points of an uncompressed key, unless sanitize is enabled
* @param sanitize Accept public keys in other formats
*/
export declare const pubToAddress: (pubKey: Buffer, sanitize?: boolean) => Buffer;
export declare const publicToAddress: (pubKey: Buffer, sanitize?: boolean) => Buffer;
/**
* Returns the ethereum public key of a given private key.
* @param privateKey A private key must be 256 bits wide
*/
export declare const privateToPublic: (privateKey: Buffer) => Buffer;
/**
* Returns the ethereum address of a given private key.
* @param privateKey A private key must be 256 bits wide
*/
export declare const privateToAddress: (privateKey: Buffer) => Buffer;
/**
* Converts a public key to the Ethereum format.
*/
export declare const importPublic: (publicKey: Buffer) => Buffer;
/**
* Returns the zero address.
*/
export declare const zeroAddress: () => string;
/**
* Checks if a given address is the zero address.
*/
export declare const isZeroAddress: (hexAddress: string) => boolean;
export declare function accountBodyFromSlim(body: AccountBodyBuffer): (Uint8Array | Buffer)[];
export declare function accountBodyToSlim(body: AccountBodyBuffer): (Uint8Array | Buffer)[];
/**
* Converts a slim account (per snap protocol spec) to the RLP encoded version of the account
* @param body Array of 4 Buffer-like items to represent the account
* @returns RLP encoded version of the account
*/
export declare function accountBodyToRLP(body: AccountBodyBuffer, couldBeSlim?: boolean): Buffer;
//# sourceMappingURL=account.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../src/account.ts"],"names":[],"mappings":";AAkBA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AAIrD,MAAM,WAAW,WAAW;IAC1B,KAAK,CAAC,EAAE,UAAU,CAAA;IAClB,OAAO,CAAC,EAAE,UAAU,CAAA;IACpB,WAAW,CAAC,EAAE,UAAU,CAAA;IACxB,QAAQ,CAAC,EAAE,UAAU,CAAA;CACtB;AAED,oBAAY,iBAAiB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,UAAU,EAAE,MAAM,GAAG,UAAU,CAAC,CAAA;AAE1F,qBAAa,OAAO;IAClB,KAAK,EAAE,MAAM,CAAA;IACb,OAAO,EAAE,MAAM,CAAA;IACf,WAAW,EAAE,MAAM,CAAA;IACnB,QAAQ,EAAE,MAAM,CAAA;IAEhB,MAAM,CAAC,eAAe,CAAC,WAAW,EAAE,WAAW;WAWjC,wBAAwB,CAAC,UAAU,EAAE,MAAM;WAU3C,eAAe,CAAC,MAAM,EAAE,MAAM,EAAE;IAM9C;;;OAGG;gBACS,KAAK,SAAM,EAAE,OAAO,SAAM,EAAE,WAAW,SAAgB,EAAE,QAAQ,SAAiB;IAS9F,OAAO,CAAC,SAAS;IAejB;;OAEG;IACH,GAAG,IAAI,MAAM,EAAE;IASf;;OAEG;IACH,SAAS,IAAI,MAAM;IAInB;;OAEG;IACH,UAAU,IAAI,OAAO;IAIrB;;;;OAIG;IACH,OAAO,IAAI,OAAO;CAGnB;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,eAAyB,MAAM,KAAG,OAQ5D,CAAA;AAED;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,iBAAiB,eAChB,MAAM,mBACD,UAAU,KAC1B,MAuBF,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,sBAAsB,eACrB,MAAM,mBACD,UAAU,KAC1B,OAEF,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,eAAe,SAAmB,MAAM,SAAS,MAAM,KAAG,MAYtE,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,gBAAgB,SAAmB,MAAM,QAAQ,MAAM,YAAY,MAAM,KAAG,MAiBxF,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,cAAc,eAAyB,MAAM,KAAG,OAE5D,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,aAAa,cAAwB,MAAM,aAAY,OAAO,KAAW,OAuBrF,CAAA;AAED;;;;;GAKG;AACH,eAAO,MAAM,YAAY,WAAqB,MAAM,aAAY,OAAO,KAAW,MAUjF,CAAA;AACD,eAAO,MAAM,eAAe,WAXkB,MAAM,aAAY,OAAO,KAAW,MAWvC,CAAA;AAE3C;;;GAGG;AACH,eAAO,MAAM,eAAe,eAAyB,MAAM,KAAG,MAM7D,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,gBAAgB,eAAyB,MAAM,KAAG,MAE9D,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,cAAwB,MAAM,KAAG,MAMzD,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,WAAW,QAAgB,MAIvC,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,aAAa,eAAyB,MAAM,KAAG,OAS3D,CAAA;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,iBAAiB,2BAQ1D;AAGD,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,iBAAiB,2BAQxD;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,iBAAiB,EAAE,WAAW,UAAO,UAG3E"}

View file

@ -1,320 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.accountBodyToRLP = exports.accountBodyToSlim = exports.accountBodyFromSlim = exports.isZeroAddress = exports.zeroAddress = exports.importPublic = exports.privateToAddress = exports.privateToPublic = exports.publicToAddress = exports.pubToAddress = exports.isValidPublic = exports.isValidPrivate = exports.generateAddress2 = exports.generateAddress = exports.isValidChecksumAddress = exports.toChecksumAddress = exports.isValidAddress = exports.Account = void 0;
const rlp_1 = require("@ethereumjs/rlp");
const keccak_1 = require("ethereum-cryptography/keccak");
const secp256k1_1 = require("ethereum-cryptography/secp256k1");
const utils_1 = require("ethereum-cryptography/utils");
const bytes_1 = require("./bytes");
const constants_1 = require("./constants");
const helpers_1 = require("./helpers");
const internal_1 = require("./internal");
const _0n = BigInt(0);
class Account {
/**
* This constructor assigns and validates the values.
* Use the static factory methods to assist in creating an Account from varying data types.
*/
constructor(nonce = _0n, balance = _0n, storageRoot = constants_1.KECCAK256_RLP, codeHash = constants_1.KECCAK256_NULL) {
this.nonce = nonce;
this.balance = balance;
this.storageRoot = storageRoot;
this.codeHash = codeHash;
this._validate();
}
static fromAccountData(accountData) {
const { nonce, balance, storageRoot, codeHash } = accountData;
return new Account(nonce !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(nonce)) : undefined, balance !== undefined ? (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(balance)) : undefined, storageRoot !== undefined ? (0, bytes_1.toBuffer)(storageRoot) : undefined, codeHash !== undefined ? (0, bytes_1.toBuffer)(codeHash) : undefined);
}
static fromRlpSerializedAccount(serialized) {
const values = (0, bytes_1.arrToBufArr)(rlp_1.RLP.decode(Uint8Array.from(serialized)));
if (!Array.isArray(values)) {
throw new Error('Invalid serialized account input. Must be array');
}
return this.fromValuesArray(values);
}
static fromValuesArray(values) {
const [nonce, balance, storageRoot, codeHash] = values;
return new Account((0, bytes_1.bufferToBigInt)(nonce), (0, bytes_1.bufferToBigInt)(balance), storageRoot, codeHash);
}
_validate() {
if (this.nonce < _0n) {
throw new Error('nonce must be greater than zero');
}
if (this.balance < _0n) {
throw new Error('balance must be greater than zero');
}
if (this.storageRoot.length !== 32) {
throw new Error('storageRoot must have a length of 32');
}
if (this.codeHash.length !== 32) {
throw new Error('codeHash must have a length of 32');
}
}
/**
* Returns a Buffer Array of the raw Buffers for the account, in order.
*/
raw() {
return [
(0, bytes_1.bigIntToUnpaddedBuffer)(this.nonce),
(0, bytes_1.bigIntToUnpaddedBuffer)(this.balance),
this.storageRoot,
this.codeHash,
];
}
/**
* Returns the RLP serialization of the account as a `Buffer`.
*/
serialize() {
return Buffer.from(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)(this.raw())));
}
/**
* Returns a `Boolean` determining if the account is a contract.
*/
isContract() {
return !this.codeHash.equals(constants_1.KECCAK256_NULL);
}
/**
* Returns a `Boolean` determining if the account is empty complying to the definition of
* account emptiness in [EIP-161](https://eips.ethereum.org/EIPS/eip-161):
* "An account is considered empty when it has no code and zero nonce and zero balance."
*/
isEmpty() {
return this.balance === _0n && this.nonce === _0n && this.codeHash.equals(constants_1.KECCAK256_NULL);
}
}
exports.Account = Account;
/**
* Checks if the address is a valid. Accepts checksummed addresses too.
*/
const isValidAddress = function (hexAddress) {
try {
(0, helpers_1.assertIsString)(hexAddress);
}
catch (e) {
return false;
}
return /^0x[0-9a-fA-F]{40}$/.test(hexAddress);
};
exports.isValidAddress = isValidAddress;
/**
* Returns a checksummed address.
*
* If an eip1191ChainId is provided, the chainId will be included in the checksum calculation. This
* has the effect of checksummed addresses for one chain having invalid checksums for others.
* For more details see [EIP-1191](https://eips.ethereum.org/EIPS/eip-1191).
*
* WARNING: Checksums with and without the chainId will differ and the EIP-1191 checksum is not
* backwards compatible to the original widely adopted checksum format standard introduced in
* [EIP-55](https://eips.ethereum.org/EIPS/eip-55), so this will break in existing applications.
* Usage of this EIP is therefore discouraged unless you have a very targeted use case.
*/
const toChecksumAddress = function (hexAddress, eip1191ChainId) {
(0, helpers_1.assertIsHexString)(hexAddress);
const address = (0, internal_1.stripHexPrefix)(hexAddress).toLowerCase();
let prefix = '';
if (eip1191ChainId !== undefined) {
const chainId = (0, bytes_1.bufferToBigInt)((0, bytes_1.toBuffer)(eip1191ChainId));
prefix = chainId.toString() + '0x';
}
const buf = Buffer.from(prefix + address, 'utf8');
const hash = (0, utils_1.bytesToHex)((0, keccak_1.keccak256)(buf));
let ret = '0x';
for (let i = 0; i < address.length; i++) {
if (parseInt(hash[i], 16) >= 8) {
ret += address[i].toUpperCase();
}
else {
ret += address[i];
}
}
return ret;
};
exports.toChecksumAddress = toChecksumAddress;
/**
* Checks if the address is a valid checksummed address.
*
* See toChecksumAddress' documentation for details about the eip1191ChainId parameter.
*/
const isValidChecksumAddress = function (hexAddress, eip1191ChainId) {
return (0, exports.isValidAddress)(hexAddress) && (0, exports.toChecksumAddress)(hexAddress, eip1191ChainId) === hexAddress;
};
exports.isValidChecksumAddress = isValidChecksumAddress;
/**
* Generates an address of a newly created contract.
* @param from The address which is creating this new address
* @param nonce The nonce of the from account
*/
const generateAddress = function (from, nonce) {
(0, helpers_1.assertIsBuffer)(from);
(0, helpers_1.assertIsBuffer)(nonce);
if ((0, bytes_1.bufferToBigInt)(nonce) === BigInt(0)) {
// in RLP we want to encode null in the case of zero nonce
// read the RLP documentation for an answer if you dare
return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, null])))).slice(-20);
}
// Only take the lower 160bits of the hash
return Buffer.from((0, keccak_1.keccak256)(rlp_1.RLP.encode((0, bytes_1.bufArrToArr)([from, nonce])))).slice(-20);
};
exports.generateAddress = generateAddress;
/**
* Generates an address for a contract created using CREATE2.
* @param from The address which is creating this new address
* @param salt A salt
* @param initCode The init code of the contract being created
*/
const generateAddress2 = function (from, salt, initCode) {
(0, helpers_1.assertIsBuffer)(from);
(0, helpers_1.assertIsBuffer)(salt);
(0, helpers_1.assertIsBuffer)(initCode);
if (from.length !== 20) {
throw new Error('Expected from to be of length 20');
}
if (salt.length !== 32) {
throw new Error('Expected salt to be of length 32');
}
const address = (0, keccak_1.keccak256)(Buffer.concat([Buffer.from('ff', 'hex'), from, salt, (0, keccak_1.keccak256)(initCode)]));
return (0, bytes_1.toBuffer)(address).slice(-20);
};
exports.generateAddress2 = generateAddress2;
/**
* Checks if the private key satisfies the rules of the curve secp256k1.
*/
const isValidPrivate = function (privateKey) {
return secp256k1_1.secp256k1.utils.isValidPrivateKey(privateKey);
};
exports.isValidPrivate = isValidPrivate;
/**
* Checks if the public key satisfies the rules of the curve secp256k1
* and the requirements of Ethereum.
* @param publicKey The two points of an uncompressed key, unless sanitize is enabled
* @param sanitize Accept public keys in other formats
*/
const isValidPublic = function (publicKey, sanitize = false) {
(0, helpers_1.assertIsBuffer)(publicKey);
if (publicKey.length === 64) {
// Convert to SEC1 for secp256k1
// Automatically checks whether point is on curve
try {
secp256k1_1.secp256k1.ProjectivePoint.fromHex(Buffer.concat([Buffer.from([4]), publicKey]));
return true;
}
catch (e) {
return false;
}
}
if (!sanitize) {
return false;
}
try {
secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey);
return true;
}
catch (e) {
return false;
}
};
exports.isValidPublic = isValidPublic;
/**
* Returns the ethereum address of a given public key.
* Accepts "Ethereum public keys" and SEC1 encoded keys.
* @param pubKey The two points of an uncompressed key, unless sanitize is enabled
* @param sanitize Accept public keys in other formats
*/
const pubToAddress = function (pubKey, sanitize = false) {
(0, helpers_1.assertIsBuffer)(pubKey);
if (sanitize && pubKey.length !== 64) {
pubKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(pubKey).toRawBytes(false).slice(1));
}
if (pubKey.length !== 64) {
throw new Error('Expected pubKey to be of length 64');
}
// Only take the lower 160bits of the hash
return Buffer.from((0, keccak_1.keccak256)(pubKey)).slice(-20);
};
exports.pubToAddress = pubToAddress;
exports.publicToAddress = exports.pubToAddress;
/**
* Returns the ethereum public key of a given private key.
* @param privateKey A private key must be 256 bits wide
*/
const privateToPublic = function (privateKey) {
(0, helpers_1.assertIsBuffer)(privateKey);
// skip the type flag and use the X, Y points
return Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromPrivateKey(privateKey).toRawBytes(false).slice(1));
};
exports.privateToPublic = privateToPublic;
/**
* Returns the ethereum address of a given private key.
* @param privateKey A private key must be 256 bits wide
*/
const privateToAddress = function (privateKey) {
return (0, exports.publicToAddress)((0, exports.privateToPublic)(privateKey));
};
exports.privateToAddress = privateToAddress;
/**
* Converts a public key to the Ethereum format.
*/
const importPublic = function (publicKey) {
(0, helpers_1.assertIsBuffer)(publicKey);
if (publicKey.length !== 64) {
publicKey = Buffer.from(secp256k1_1.secp256k1.ProjectivePoint.fromHex(publicKey).toRawBytes(false).slice(1));
}
return publicKey;
};
exports.importPublic = importPublic;
/**
* Returns the zero address.
*/
const zeroAddress = function () {
const addressLength = 20;
const addr = (0, bytes_1.zeros)(addressLength);
return (0, bytes_1.bufferToHex)(addr);
};
exports.zeroAddress = zeroAddress;
/**
* Checks if a given address is the zero address.
*/
const isZeroAddress = function (hexAddress) {
try {
(0, helpers_1.assertIsString)(hexAddress);
}
catch (e) {
return false;
}
const zeroAddr = (0, exports.zeroAddress)();
return zeroAddr === hexAddress;
};
exports.isZeroAddress = isZeroAddress;
function accountBodyFromSlim(body) {
const [nonce, balance, storageRoot, codeHash] = body;
return [
nonce,
balance,
(0, bytes_1.arrToBufArr)(storageRoot).length === 0 ? constants_1.KECCAK256_RLP : storageRoot,
(0, bytes_1.arrToBufArr)(codeHash).length === 0 ? constants_1.KECCAK256_NULL : codeHash,
];
}
exports.accountBodyFromSlim = accountBodyFromSlim;
const emptyUint8Arr = new Uint8Array(0);
function accountBodyToSlim(body) {
const [nonce, balance, storageRoot, codeHash] = body;
return [
nonce,
balance,
(0, bytes_1.arrToBufArr)(storageRoot).equals(constants_1.KECCAK256_RLP) ? emptyUint8Arr : storageRoot,
(0, bytes_1.arrToBufArr)(codeHash).equals(constants_1.KECCAK256_NULL) ? emptyUint8Arr : codeHash,
];
}
exports.accountBodyToSlim = accountBodyToSlim;
/**
* Converts a slim account (per snap protocol spec) to the RLP encoded version of the account
* @param body Array of 4 Buffer-like items to represent the account
* @returns RLP encoded version of the account
*/
function accountBodyToRLP(body, couldBeSlim = true) {
const accountBody = couldBeSlim ? accountBodyFromSlim(body) : body;
return (0, bytes_1.arrToBufArr)(rlp_1.RLP.encode(accountBody));
}
exports.accountBodyToRLP = accountBodyToRLP;
//# sourceMappingURL=account.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,62 +0,0 @@
/// <reference types="node" />
/**
* Handling and generating Ethereum addresses
*/
export declare class Address {
readonly buf: Buffer;
constructor(buf: Buffer);
/**
* Returns the zero address.
*/
static zero(): Address;
/**
* Returns an Address object from a hex-encoded string.
* @param str - Hex-encoded address
*/
static fromString(str: string): Address;
/**
* Returns an address for a given public key.
* @param pubKey The two points of an uncompressed key
*/
static fromPublicKey(pubKey: Buffer): Address;
/**
* Returns an address for a given private key.
* @param privateKey A private key must be 256 bits wide
*/
static fromPrivateKey(privateKey: Buffer): Address;
/**
* Generates an address for a newly created contract.
* @param from The address which is creating this new address
* @param nonce The nonce of the from account
*/
static generate(from: Address, nonce: bigint): Address;
/**
* Generates an address for a contract created using CREATE2.
* @param from The address which is creating this new address
* @param salt A salt
* @param initCode The init code of the contract being created
*/
static generate2(from: Address, salt: Buffer, initCode: Buffer): Address;
/**
* Is address equal to another.
*/
equals(address: Address): boolean;
/**
* Is address zero.
*/
isZero(): boolean;
/**
* True if address is in the address range defined
* by EIP-1352
*/
isPrecompileOrSystemAddress(): boolean;
/**
* Returns hex encoding of address.
*/
toString(): string;
/**
* Returns Buffer representation of address.
*/
toBuffer(): Buffer;
}
//# sourceMappingURL=address.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"address.d.ts","sourceRoot":"","sources":["../src/address.ts"],"names":[],"mappings":";AASA;;GAEG;AACH,qBAAa,OAAO;IAClB,SAAgB,GAAG,EAAE,MAAM,CAAA;gBAEf,GAAG,EAAE,MAAM;IAOvB;;OAEG;IACH,MAAM,CAAC,IAAI,IAAI,OAAO;IAItB;;;OAGG;IACH,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO;IAOvC;;;OAGG;IACH,MAAM,CAAC,aAAa,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO;IAQ7C;;;OAGG;IACH,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,MAAM,GAAG,OAAO;IAQlD;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO;IAOtD;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO;IAUxE;;OAEG;IACH,MAAM,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO;IAIjC;;OAEG;IACH,MAAM,IAAI,OAAO;IAIjB;;;OAGG;IACH,2BAA2B,IAAI,OAAO;IAOtC;;OAEG;IACH,QAAQ,IAAI,MAAM;IAIlB;;OAEG;IACH,QAAQ,IAAI,MAAM;CAGnB"}

View file

@ -1,116 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Address = void 0;
const account_1 = require("./account");
const bytes_1 = require("./bytes");
/**
* Handling and generating Ethereum addresses
*/
class Address {
constructor(buf) {
if (buf.length !== 20) {
throw new Error('Invalid address length');
}
this.buf = buf;
}
/**
* Returns the zero address.
*/
static zero() {
return new Address((0, bytes_1.zeros)(20));
}
/**
* Returns an Address object from a hex-encoded string.
* @param str - Hex-encoded address
*/
static fromString(str) {
if (!(0, account_1.isValidAddress)(str)) {
throw new Error('Invalid address');
}
return new Address((0, bytes_1.toBuffer)(str));
}
/**
* Returns an address for a given public key.
* @param pubKey The two points of an uncompressed key
*/
static fromPublicKey(pubKey) {
if (!Buffer.isBuffer(pubKey)) {
throw new Error('Public key should be Buffer');
}
const buf = (0, account_1.pubToAddress)(pubKey);
return new Address(buf);
}
/**
* Returns an address for a given private key.
* @param privateKey A private key must be 256 bits wide
*/
static fromPrivateKey(privateKey) {
if (!Buffer.isBuffer(privateKey)) {
throw new Error('Private key should be Buffer');
}
const buf = (0, account_1.privateToAddress)(privateKey);
return new Address(buf);
}
/**
* Generates an address for a newly created contract.
* @param from The address which is creating this new address
* @param nonce The nonce of the from account
*/
static generate(from, nonce) {
if (typeof nonce !== 'bigint') {
throw new Error('Expected nonce to be a bigint');
}
return new Address((0, account_1.generateAddress)(from.buf, (0, bytes_1.bigIntToBuffer)(nonce)));
}
/**
* Generates an address for a contract created using CREATE2.
* @param from The address which is creating this new address
* @param salt A salt
* @param initCode The init code of the contract being created
*/
static generate2(from, salt, initCode) {
if (!Buffer.isBuffer(salt)) {
throw new Error('Expected salt to be a Buffer');
}
if (!Buffer.isBuffer(initCode)) {
throw new Error('Expected initCode to be a Buffer');
}
return new Address((0, account_1.generateAddress2)(from.buf, salt, initCode));
}
/**
* Is address equal to another.
*/
equals(address) {
return this.buf.equals(address.buf);
}
/**
* Is address zero.
*/
isZero() {
return this.equals(Address.zero());
}
/**
* True if address is in the address range defined
* by EIP-1352
*/
isPrecompileOrSystemAddress() {
const address = (0, bytes_1.bufferToBigInt)(this.buf);
const rangeMin = BigInt(0);
const rangeMax = BigInt('0xffff');
return address >= rangeMin && address <= rangeMax;
}
/**
* Returns hex encoding of address.
*/
toString() {
return '0x' + this.buf.toString('hex');
}
/**
* Returns Buffer representation of address.
*/
toBuffer() {
return Buffer.from(this.buf);
}
}
exports.Address = Address;
//# sourceMappingURL=address.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"address.js","sourceRoot":"","sources":["../src/address.ts"],"names":[],"mappings":";;;AAAA,uCAMkB;AAClB,mCAAyE;AAEzE;;GAEG;AACH,MAAa,OAAO;IAGlB,YAAY,GAAW;QACrB,IAAI,GAAG,CAAC,MAAM,KAAK,EAAE,EAAE;YACrB,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAA;SAC1C;QACD,IAAI,CAAC,GAAG,GAAG,GAAG,CAAA;IAChB,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,IAAI;QACT,OAAO,IAAI,OAAO,CAAC,IAAA,aAAK,EAAC,EAAE,CAAC,CAAC,CAAA;IAC/B,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,UAAU,CAAC,GAAW;QAC3B,IAAI,CAAC,IAAA,wBAAc,EAAC,GAAG,CAAC,EAAE;YACxB,MAAM,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAA;SACnC;QACD,OAAO,IAAI,OAAO,CAAC,IAAA,gBAAQ,EAAC,GAAG,CAAC,CAAC,CAAA;IACnC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,aAAa,CAAC,MAAc;QACjC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,EAAE;YAC5B,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAA;SAC/C;QACD,MAAM,GAAG,GAAG,IAAA,sBAAY,EAAC,MAAM,CAAC,CAAA;QAChC,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,cAAc,CAAC,UAAkB;QACtC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,UAAU,CAAC,EAAE;YAChC,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;SAChD;QACD,MAAM,GAAG,GAAG,IAAA,0BAAgB,EAAC,UAAU,CAAC,CAAA;QACxC,OAAO,IAAI,OAAO,CAAC,GAAG,CAAC,CAAA;IACzB,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,QAAQ,CAAC,IAAa,EAAE,KAAa;QAC1C,IAAI,OAAO,KAAK,KAAK,QAAQ,EAAE;YAC7B,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAA;SACjD;QACD,OAAO,IAAI,OAAO,CAAC,IAAA,yBAAe,EAAC,IAAI,CAAC,GAAG,EAAE,IAAA,sBAAc,EAAC,KAAK,CAAC,CAAC,CAAC,CAAA;IACtE,CAAC;IAED;;;;;OAKG;IACH,MAAM,CAAC,SAAS,CAAC,IAAa,EAAE,IAAY,EAAE,QAAgB;QAC5D,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE;YAC1B,MAAM,IAAI,KAAK,CAAC,8BAA8B,CAAC,CAAA;SAChD;QACD,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE;YAC9B,MAAM,IAAI,KAAK,CAAC,kCAAkC,CAAC,CAAA;SACpD;QACD,OAAO,IAAI,OAAO,CAAC,IAAA,0BAAgB,EAAC,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,QAAQ,CAAC,CAAC,CAAA;IAChE,CAAC;IAED;;OAEG;IACH,MAAM,CAAC,OAAgB;QACrB,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IACrC,CAAC;IAED;;OAEG;IACH,MAAM;QACJ,OAAO,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;IACpC,CAAC;IAED;;;OAGG;IACH,2BAA2B;QACzB,MAAM,OAAO,GAAG,IAAA,sBAAc,EAAC,IAAI,CAAC,GAAG,CAAC,CAAA;QACxC,MAAM,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC,CAAA;QAC1B,MAAM,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAA;QACjC,OAAO,OAAO,IAAI,QAAQ,IAAI,OAAO,IAAI,QAAQ,CAAA;IACnD,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,IAAI,GAAG,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAA;IACxC,CAAC;IAED;;OAEG;IACH,QAAQ;QACN,OAAO,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,CAAA;IAC9B,CAAC;CACF;AAtHD,0BAsHC"}

View file

@ -1,35 +0,0 @@
/**
* Ported to Typescript from original implementation below:
* https://github.com/ahultgren/async-eventemitter -- MIT licensed
*
* Type Definitions based on work by: patarapolw <https://github.com/patarapolw> -- MIT licensed
* that was contributed to Definitely Typed below:
* https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter
*/
/// <reference types="node" />
import { EventEmitter } from 'events';
declare type AsyncListener<T, R> = ((data: T, callback?: (result?: R) => void) => Promise<R>) | ((data: T, callback?: (result?: R) => void) => void);
export interface EventMap {
[event: string]: AsyncListener<any, any>;
}
export declare class AsyncEventEmitter<T extends EventMap> extends EventEmitter {
emit<E extends keyof T>(event: E & string, ...args: Parameters<T[E]>): boolean;
once<E extends keyof T>(event: E & string, listener: T[E]): this;
first<E extends keyof T>(event: E & string, listener: T[E]): this;
before<E extends keyof T>(event: E & string, target: T[E], listener: T[E]): this;
after<E extends keyof T>(event: E & string, target: T[E], listener: T[E]): this;
private beforeOrAfter;
on<E extends keyof T>(event: E & string, listener: T[E]): this;
addListener<E extends keyof T>(event: E & string, listener: T[E]): this;
prependListener<E extends keyof T>(event: E & string, listener: T[E]): this;
prependOnceListener<E extends keyof T>(event: E & string, listener: T[E]): this;
removeAllListeners(event?: keyof T & string): this;
removeListener<E extends keyof T>(event: E & string, listener: T[E]): this;
eventNames(): Array<keyof T & string>;
listeners<E extends keyof T>(event: E & string): Array<T[E]>;
listenerCount(event: keyof T & string): number;
getMaxListeners(): number;
setMaxListeners(maxListeners: number): this;
}
export {};
//# sourceMappingURL=asyncEventEmitter.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"asyncEventEmitter.d.ts","sourceRoot":"","sources":["../src/asyncEventEmitter.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;;AAEH,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AACrC,aAAK,aAAa,CAAC,CAAC,EAAE,CAAC,IACnB,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,GAC1D,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,QAAQ,CAAC,EAAE,CAAC,MAAM,CAAC,EAAE,CAAC,KAAK,IAAI,KAAK,IAAI,CAAC,CAAA;AACxD,MAAM,WAAW,QAAQ;IACvB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAAC,GAAG,EAAE,GAAG,CAAC,CAAA;CACzC;AAiCD,qBAAa,iBAAiB,CAAC,CAAC,SAAS,QAAQ,CAAE,SAAQ,YAAY;IACrE,IAAI,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,GAAG,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IA6BpE,IAAI,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IA0BhE,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAkBjE,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAIhF,KAAK,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI/E,OAAO,CAAC,aAAa;IAsCrB,EAAE,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI9D,WAAW,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAIvE,eAAe,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI3E,mBAAmB,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI/E,kBAAkB,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI;IAIlD,cAAc,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,IAAI;IAI1E,UAAU,IAAI,KAAK,CAAC,MAAM,CAAC,GAAG,MAAM,CAAC;IAIrC,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,GAAG,MAAM,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IAI5D,aAAa,CAAC,KAAK,EAAE,MAAM,CAAC,GAAG,MAAM,GAAG,MAAM;IAI9C,eAAe,IAAI,MAAM;IAIzB,eAAe,CAAC,YAAY,EAAE,MAAM,GAAG,IAAI;CAG5C"}

View file

@ -1,169 +0,0 @@
"use strict";
/**
* Ported to Typescript from original implementation below:
* https://github.com/ahultgren/async-eventemitter -- MIT licensed
*
* Type Definitions based on work by: patarapolw <https://github.com/patarapolw> -- MIT licensed
* that was contributed to Definitely Typed below:
* https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/async-eventemitter
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncEventEmitter = void 0;
const events_1 = require("events");
async function runInSeries(context, tasks, data) {
let error;
for await (const task of tasks) {
try {
if (task.length < 2) {
//sync
task.call(context, data);
}
else {
await new Promise((resolve, reject) => {
task.call(context, data, (error) => {
if (error) {
reject(error);
}
else {
resolve();
}
});
});
}
}
catch (e) {
error = e;
}
}
if (error) {
throw error;
}
}
class AsyncEventEmitter extends events_1.EventEmitter {
emit(event, ...args) {
let [data, callback] = args;
const self = this;
let listeners = self._events[event] ?? [];
// Optional data argument
if (callback === undefined && typeof data === 'function') {
callback = data;
data = undefined;
}
// Special treatment of internal newListener and removeListener events
if (event === 'newListener' || event === 'removeListener') {
data = {
event: data,
fn: callback,
};
callback = undefined;
}
// A single listener is just a function not an array...
listeners = Array.isArray(listeners) ? listeners : [listeners];
runInSeries(self, listeners.slice(), data).then(callback).catch(callback);
return self.listenerCount(event) > 0;
}
once(event, listener) {
const self = this;
let g;
if (typeof listener !== 'function') {
throw new TypeError('listener must be a function');
}
// Hack to support set arity
if (listener.length >= 2) {
g = function (e, next) {
self.removeListener(event, g);
void listener(e, next);
};
}
else {
g = function (e) {
self.removeListener(event, g);
void listener(e, g);
};
}
self.on(event, g);
return self;
}
first(event, listener) {
let listeners = this._events[event] ?? [];
// Contract
if (typeof listener !== 'function') {
throw new TypeError('listener must be a function');
}
// Listeners are not always an array
if (!Array.isArray(listeners)) {
;
this._events[event] = listeners = [listeners];
}
listeners.unshift(listener);
return this;
}
before(event, target, listener) {
return this.beforeOrAfter(event, target, listener);
}
after(event, target, listener) {
return this.beforeOrAfter(event, target, listener, 'after');
}
beforeOrAfter(event, target, listener, beforeOrAfter) {
let listeners = this._events[event] ?? [];
let i;
let index;
const add = beforeOrAfter === 'after' ? 1 : 0;
// Contract
if (typeof listener !== 'function') {
throw new TypeError('listener must be a function');
}
if (typeof target !== 'function') {
throw new TypeError('target must be a function');
}
// Listeners are not always an array
if (!Array.isArray(listeners)) {
;
this._events[event] = listeners = [listeners];
}
index = listeners.length;
for (i = listeners.length; i--;) {
if (listeners[i] === target) {
index = i + add;
break;
}
}
listeners.splice(index, 0, listener);
return this;
}
on(event, listener) {
return super.on(event, listener);
}
addListener(event, listener) {
return super.addListener(event, listener);
}
prependListener(event, listener) {
return super.prependListener(event, listener);
}
prependOnceListener(event, listener) {
return super.prependOnceListener(event, listener);
}
removeAllListeners(event) {
return super.removeAllListeners(event);
}
removeListener(event, listener) {
return super.removeListener(event, listener);
}
eventNames() {
return super.eventNames();
}
listeners(event) {
return super.listeners(event);
}
listenerCount(event) {
return super.listenerCount(event);
}
getMaxListeners() {
return super.getMaxListeners();
}
setMaxListeners(maxListeners) {
return super.setMaxListeners(maxListeners);
}
}
exports.AsyncEventEmitter = AsyncEventEmitter;
//# sourceMappingURL=asyncEventEmitter.js.map

View file

@ -1 +0,0 @@
{"version":3,"file":"asyncEventEmitter.js","sourceRoot":"","sources":["../src/asyncEventEmitter.ts"],"names":[],"mappings":";AAAA;;;;;;;GAOG;;;AAEH,mCAAqC;AAQrC,KAAK,UAAU,WAAW,CACxB,OAAY,EACZ,KAAyE,EACzE,IAAa;IAEb,IAAI,KAAwB,CAAA;IAC5B,IAAI,KAAK,EAAE,MAAM,IAAI,IAAI,KAAK,EAAE;QAC9B,IAAI;YACF,IAAI,IAAI,CAAC,MAAM,GAAG,CAAC,EAAE;gBACnB,MAAM;gBACN,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,CAAC,CAAA;aACzB;iBAAM;gBACL,MAAM,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;oBAC1C,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,IAAI,EAAE,CAAC,KAAK,EAAE,EAAE;wBACjC,IAAI,KAAK,EAAE;4BACT,MAAM,CAAC,KAAK,CAAC,CAAA;yBACd;6BAAM;4BACL,OAAO,EAAE,CAAA;yBACV;oBACH,CAAC,CAAC,CAAA;gBACJ,CAAC,CAAC,CAAA;aACH;SACF;QAAC,OAAO,CAAU,EAAE;YACnB,KAAK,GAAG,CAAU,CAAA;SACnB;KACF;IACD,IAAI,KAAK,EAAE;QACT,MAAM,KAAK,CAAA;KACZ;AACH,CAAC;AAED,MAAa,iBAAsC,SAAQ,qBAAY;IACrE,IAAI,CAAoB,KAAiB,EAAE,GAAG,IAAsB;QAClE,IAAI,CAAC,IAAI,EAAE,QAAQ,CAAC,GAAG,IAAI,CAAA;QAC3B,MAAM,IAAI,GAAG,IAAI,CAAA;QAEjB,IAAI,SAAS,GAAI,IAAY,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA;QAElD,yBAAyB;QACzB,IAAI,QAAQ,KAAK,SAAS,IAAI,OAAO,IAAI,KAAK,UAAU,EAAE;YACxD,QAAQ,GAAG,IAAI,CAAA;YACf,IAAI,GAAG,SAAS,CAAA;SACjB;QAED,sEAAsE;QACtE,IAAI,KAAK,KAAK,aAAa,IAAI,KAAK,KAAK,gBAAgB,EAAE;YACzD,IAAI,GAAG;gBACL,KAAK,EAAE,IAAI;gBACX,EAAE,EAAE,QAAQ;aACb,CAAA;YAED,QAAQ,GAAG,SAAS,CAAA;SACrB;QAED,uDAAuD;QACvD,SAAS,GAAG,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA;QAC9D,WAAW,CAAC,IAAI,EAAE,SAAS,CAAC,KAAK,EAAE,EAAE,IAAI,CAAC,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,CAAA;QAEzE,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,GAAG,CAAC,CAAA;IACtC,CAAC;IAED,IAAI,CAAoB,KAAiB,EAAE,QAAc;QACvD,MAAM,IAAI,GAAG,IAAI,CAAA;QACjB,IAAI,CAA2B,CAAA;QAE/B,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAA;SACnD;QAED,4BAA4B;QAC5B,IAAI,QAAQ,CAAC,MAAM,IAAI,CAAC,EAAE;YACxB,CAAC,GAAG,UAAU,CAAI,EAAE,IAAS;gBAC3B,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAS,CAAC,CAAA;gBACrC,KAAK,QAAQ,CAAC,CAAC,EAAE,IAAI,CAAC,CAAA;YACxB,CAAC,CAAA;SACF;aAAM;YACL,CAAC,GAAG,UAAU,CAAI;gBAChB,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE,CAAS,CAAC,CAAA;gBACrC,KAAK,QAAQ,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;YACrB,CAAC,CAAA;SACF;QAED,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,CAAS,CAAC,CAAA;QAEzB,OAAO,IAAI,CAAA;IACb,CAAC;IAED,KAAK,CAAoB,KAAiB,EAAE,QAAc;QACxD,IAAI,SAAS,GAAI,IAAY,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA;QAElD,WAAW;QACX,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAA;SACnD;QAED,oCAAoC;QACpC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;YAC7B,CAAC;YAAC,IAAY,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,SAAS,GAAG,CAAC,SAAS,CAAC,CAAA;SACxD;QAED,SAAS,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAA;QAE3B,OAAO,IAAI,CAAA;IACb,CAAC;IAED,MAAM,CAAoB,KAAiB,EAAE,MAAY,EAAE,QAAc;QACvE,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAA;IACpD,CAAC;IAED,KAAK,CAAoB,KAAiB,EAAE,MAAY,EAAE,QAAc;QACtE,OAAO,IAAI,CAAC,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAA;IAC7D,CAAC;IAEO,aAAa,CACnB,KAAiB,EACjB,MAAY,EACZ,QAAc,EACd,aAAsB;QAEtB,IAAI,SAAS,GAAI,IAAY,CAAC,OAAO,CAAC,KAAK,CAAC,IAAI,EAAE,CAAA;QAClD,IAAI,CAAC,CAAA;QACL,IAAI,KAAK,CAAA;QACT,MAAM,GAAG,GAAG,aAAa,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAA;QAE7C,WAAW;QACX,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE;YAClC,MAAM,IAAI,SAAS,CAAC,6BAA6B,CAAC,CAAA;SACnD;QACD,IAAI,OAAO,MAAM,KAAK,UAAU,EAAE;YAChC,MAAM,IAAI,SAAS,CAAC,2BAA2B,CAAC,CAAA;SACjD;QAED,oCAAoC;QACpC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE;YAC7B,CAAC;YAAC,IAAY,CAAC,OAAO,CAAC,KAAK,CAAC,GAAG,SAAS,GAAG,CAAC,SAAS,CAAC,CAAA;SACxD;QAED,KAAK,GAAG,SAAS,CAAC,MAAM,CAAA;QAExB,KAAK,CAAC,GAAG,SAAS,CAAC,MAAM,EAAE,CAAC,EAAE,GAAI;YAChC,IAAI,SAAS,CAAC,CAAC,CAAC,KAAK,MAAM,EAAE;gBAC3B,KAAK,GAAG,CAAC,GAAG,GAAG,CAAA;gBACf,MAAK;aACN;SACF;QAED,SAAS,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC,EAAE,QAAQ,CAAC,CAAA;QAEpC,OAAO,IAAI,CAAA;IACb,CAAC;IAED,EAAE,CAAoB,KAAiB,EAAE,QAAc;QACrD,OAAO,KAAK,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IAClC,CAAC;IAED,WAAW,CAAoB,KAAiB,EAAE,QAAc;QAC9D,OAAO,KAAK,CAAC,WAAW,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IAC3C,CAAC;IAED,eAAe,CAAoB,KAAiB,EAAE,QAAc;QAClE,OAAO,KAAK,CAAC,eAAe,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IAC/C,CAAC;IAED,mBAAmB,CAAoB,KAAiB,EAAE,QAAc;QACtE,OAAO,KAAK,CAAC,mBAAmB,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IACnD,CAAC;IAED,kBAAkB,CAAC,KAAwB;QACzC,OAAO,KAAK,CAAC,kBAAkB,CAAC,KAAK,CAAC,CAAA;IACxC,CAAC;IAED,cAAc,CAAoB,KAAiB,EAAE,QAAc;QACjE,OAAO,KAAK,CAAC,cAAc,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAA;IAC9C,CAAC;IAED,UAAU;QACR,OAAO,KAAK,CAAC,UAAU,EAAwB,CAAA;IACjD,CAAC;IAED,SAAS,CAAoB,KAAiB;QAC5C,OAAO,KAAK,CAAC,SAAS,CAAC,KAAK,CAAW,CAAA;IACzC,CAAC;IAED,aAAa,CAAC,KAAuB;QACnC,OAAO,KAAK,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;IACnC,CAAC;IAED,eAAe;QACb,OAAO,KAAK,CAAC,eAAe,EAAE,CAAA;IAChC,CAAC;IAED,eAAe,CAAC,YAAoB;QAClC,OAAO,KAAK,CAAC,eAAe,CAAC,YAAY,CAAC,CAAA;IAC5C,CAAC;CACF;AAnKD,8CAmKC"}

View file

@ -1,167 +0,0 @@
/// <reference types="node" />
import type { NestedBufferArray, NestedUint8Array, PrefixedHexString, TransformableToArray, TransformableToBuffer } from './types';
/**
* Converts a `Number` into a hex `String`
* @param {Number} i
* @return {String}
*/
export declare const intToHex: (i: number) => string;
/**
* Converts an `Number` to a `Buffer`
* @param {Number} i
* @return {Buffer}
*/
export declare const intToBuffer: (i: number) => Buffer;
/**
* Returns a buffer filled with 0s.
* @param bytes the number of bytes the buffer should be
*/
export declare const zeros: (bytes: number) => Buffer;
/**
* Left Pads a `Buffer` with leading zeros till it has `length` bytes.
* Or it truncates the beginning if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
export declare const setLengthLeft: (msg: Buffer, length: number) => Buffer;
/**
* Right Pads a `Buffer` with trailing zeros till it has `length` bytes.
* it truncates the end if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
export declare const setLengthRight: (msg: Buffer, length: number) => Buffer;
/**
* Trims leading zeros from a `Buffer`.
* @param a (Buffer)
* @return (Buffer)
*/
export declare const unpadBuffer: (a: Buffer) => Buffer;
/**
* Trims leading zeros from an `Array` (of numbers).
* @param a (number[])
* @return (number[])
*/
export declare const unpadArray: (a: number[]) => number[];
/**
* Trims leading zeros from a hex-prefixed `String`.
* @param a (String)
* @return (String)
*/
export declare const unpadHexString: (a: string) => string;
export declare type ToBufferInputTypes = PrefixedHexString | number | bigint | Buffer | Uint8Array | number[] | TransformableToArray | TransformableToBuffer | null | undefined;
/**
* Attempts to turn a value into a `Buffer`.
* Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects
* with a `toArray()` or `toBuffer()` method.
* @param v the value
*/
export declare const toBuffer: (v: ToBufferInputTypes) => Buffer;
/**
* Converts a `Buffer` into a `0x`-prefixed hex `String`.
* @param buf `Buffer` object to convert
*/
export declare const bufferToHex: (buf: Buffer) => string;
/**
* Converts a {@link Buffer} to a {@link bigint}
*/
export declare function bufferToBigInt(buf: Buffer): bigint;
/**
* Converts a {@link bigint} to a {@link Buffer}
*/
export declare function bigIntToBuffer(num: bigint): Buffer;
/**
* Converts a `Buffer` to a `Number`.
* @param buf `Buffer` object to convert
* @throws If the input number exceeds 53 bits.
*/
export declare const bufferToInt: (buf: Buffer) => number;
/**
* Interprets a `Buffer` as a signed integer and returns a `BigInt`. Assumes 256-bit numbers.
* @param num Signed integer value
*/
export declare const fromSigned: (num: Buffer) => bigint;
/**
* Converts a `BigInt` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers.
* @param num
*/
export declare const toUnsigned: (num: bigint) => Buffer;
/**
* Adds "0x" to a given `String` if it does not already start with "0x".
*/
export declare const addHexPrefix: (str: string) => string;
/**
* Shortens a string or buffer's hex string representation to maxLength (default 50).
*
* Examples:
*
* Input: '657468657265756d000000000000000000000000000000000000000000000000'
* Output: '657468657265756d0000000000000000000000000000000000…'
*/
export declare function short(buffer: Buffer | string, maxLength?: number): string;
/**
* Returns the utf8 string representation from a hex string.
*
* Examples:
*
* Input 1: '657468657265756d000000000000000000000000000000000000000000000000'
* Input 2: '657468657265756d'
* Input 3: '000000000000000000000000000000000000000000000000657468657265756d'
*
* Output (all 3 input variants): 'ethereum'
*
* Note that this method is not intended to be used with hex strings
* representing quantities in both big endian or little endian notation.
*
* @param string Hex string, should be `0x` prefixed
* @return Utf8 string
*/
export declare const toUtf8: (hex: string) => string;
/**
* Converts a `Buffer` or `Array` to JSON.
* @param ba (Buffer|Array)
* @return (Array|String|null)
*/
export declare const baToJSON: (ba: any) => any;
/**
* Checks provided Buffers for leading zeroes and throws if found.
*
* Examples:
*
* Valid values: 0x1, 0x, 0x01, 0x1234
* Invalid values: 0x0, 0x00, 0x001, 0x0001
*
* Note: This method is useful for validating that RLP encoded integers comply with the rule that all
* integer values encoded to RLP must be in the most compact form and contain no leading zero bytes
* @param values An object containing string keys and Buffer values
* @throws if any provided value is found to have leading zero bytes
*/
export declare const validateNoLeadingZeroes: (values: {
[key: string]: Buffer | undefined;
}) => void;
/**
* Converts a {@link Uint8Array} or {@link NestedUint8Array} to {@link Buffer} or {@link NestedBufferArray}
*/
export declare function arrToBufArr(arr: Uint8Array): Buffer;
export declare function arrToBufArr(arr: NestedUint8Array): NestedBufferArray;
export declare function arrToBufArr(arr: Uint8Array | NestedUint8Array): Buffer | NestedBufferArray;
/**
* Converts a {@link Buffer} or {@link NestedBufferArray} to {@link Uint8Array} or {@link NestedUint8Array}
*/
export declare function bufArrToArr(arr: Buffer): Uint8Array;
export declare function bufArrToArr(arr: NestedBufferArray): NestedUint8Array;
export declare function bufArrToArr(arr: Buffer | NestedBufferArray): Uint8Array | NestedUint8Array;
/**
* Converts a {@link bigint} to a `0x` prefixed hex string
*/
export declare const bigIntToHex: (num: bigint) => string;
/**
* Convert value from bigint to an unpadded Buffer
* (useful for RLP transport)
* @param value value to convert
*/
export declare function bigIntToUnpaddedBuffer(value: bigint): Buffer;
export declare function intToUnpaddedBuffer(value: number): Buffer;
//# sourceMappingURL=bytes.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"bytes.d.ts","sourceRoot":"","sources":["../src/bytes.ts"],"names":[],"mappings":";AAGA,OAAO,KAAK,EACV,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,oBAAoB,EACpB,qBAAqB,EACtB,MAAM,SAAS,CAAA;AAEhB;;;;GAIG;AACH,eAAO,MAAM,QAAQ,MAAgB,MAAM,WAK1C,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,WAAW,MAAgB,MAAM,WAG7C,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,KAAK,UAAoB,MAAM,KAAG,MAE9C,CAAA;AA2BD;;;;;;GAMG;AACH,eAAO,MAAM,aAAa,QAAkB,MAAM,UAAU,MAAM,WAGjE,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,QAAkB,MAAM,UAAU,MAAM,WAGlE,CAAA;AAgBD;;;;GAIG;AACH,eAAO,MAAM,WAAW,MAAgB,MAAM,KAAG,MAGhD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,UAAU,MAAgB,MAAM,EAAE,KAAG,MAAM,EAGvD,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,cAAc,MAAgB,MAAM,KAAG,MAInD,CAAA;AAED,oBAAY,kBAAkB,GAC1B,iBAAiB,GACjB,MAAM,GACN,MAAM,GACN,MAAM,GACN,UAAU,GACV,MAAM,EAAE,GACR,oBAAoB,GACpB,qBAAqB,GACrB,IAAI,GACJ,SAAS,CAAA;AAEb;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,MAAgB,kBAAkB,KAAG,MA6CzD,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,WAAW,QAAkB,MAAM,KAAG,MAGlD,CAAA;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,UAMzC;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,UAEzC;AAED;;;;GAIG;AACH,eAAO,MAAM,WAAW,QAAkB,MAAM,KAAG,MAIlD,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU,QAAkB,MAAM,KAAG,MAEjD,CAAA;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU,QAAkB,MAAM,KAAG,MAEjD,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,YAAY,QAAkB,MAAM,KAAG,MAMnD,CAAA;AAED;;;;;;;GAOG;AACH,wBAAgB,KAAK,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,SAAS,GAAE,MAAW,GAAG,MAAM,CAM7E;AAED;;;;;;;;;;;;;;;;GAgBG;AACH,eAAO,MAAM,MAAM,QAAkB,MAAM,KAAG,MAS7C,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,QAAQ,OAAiB,GAAG,KAAG,GAU3C,CAAA;AAED;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB;;UAMnC,CAAA;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,MAAM,CAAA;AACpD,wBAAgB,WAAW,CAAC,GAAG,EAAE,gBAAgB,GAAG,iBAAiB,CAAA;AACrE,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,GAAG,MAAM,GAAG,iBAAiB,CAAA;AAQ3F;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,UAAU,CAAA;AACpD,wBAAgB,WAAW,CAAC,GAAG,EAAE,iBAAiB,GAAG,gBAAgB,CAAA;AACrE,wBAAgB,WAAW,CAAC,GAAG,EAAE,MAAM,GAAG,iBAAiB,GAAG,UAAU,GAAG,gBAAgB,CAAA;AAQ3F;;GAEG;AACH,eAAO,MAAM,WAAW,QAAS,MAAM,WAEtC,CAAA;AAED;;;;GAIG;AACH,wBAAgB,sBAAsB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAE5D;AAED,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAEzD"}

View file

@ -1,354 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.intToUnpaddedBuffer = exports.bigIntToUnpaddedBuffer = exports.bigIntToHex = exports.bufArrToArr = exports.arrToBufArr = exports.validateNoLeadingZeroes = exports.baToJSON = exports.toUtf8 = exports.short = exports.addHexPrefix = exports.toUnsigned = exports.fromSigned = exports.bufferToInt = exports.bigIntToBuffer = exports.bufferToBigInt = exports.bufferToHex = exports.toBuffer = exports.unpadHexString = exports.unpadArray = exports.unpadBuffer = exports.setLengthRight = exports.setLengthLeft = exports.zeros = exports.intToBuffer = exports.intToHex = void 0;
const helpers_1 = require("./helpers");
const internal_1 = require("./internal");
/**
* Converts a `Number` into a hex `String`
* @param {Number} i
* @return {String}
*/
const intToHex = function (i) {
if (!Number.isSafeInteger(i) || i < 0) {
throw new Error(`Received an invalid integer type: ${i}`);
}
return `0x${i.toString(16)}`;
};
exports.intToHex = intToHex;
/**
* Converts an `Number` to a `Buffer`
* @param {Number} i
* @return {Buffer}
*/
const intToBuffer = function (i) {
const hex = (0, exports.intToHex)(i);
return Buffer.from((0, internal_1.padToEven)(hex.slice(2)), 'hex');
};
exports.intToBuffer = intToBuffer;
/**
* Returns a buffer filled with 0s.
* @param bytes the number of bytes the buffer should be
*/
const zeros = function (bytes) {
return Buffer.allocUnsafe(bytes).fill(0);
};
exports.zeros = zeros;
/**
* Pads a `Buffer` with zeros till it has `length` bytes.
* Truncates the beginning or end of input if its length exceeds `length`.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @param right whether to start padding form the left or right
* @return (Buffer)
*/
const setLength = function (msg, length, right) {
const buf = (0, exports.zeros)(length);
if (right) {
if (msg.length < length) {
msg.copy(buf);
return buf;
}
return msg.slice(0, length);
}
else {
if (msg.length < length) {
msg.copy(buf, length - msg.length);
return buf;
}
return msg.slice(-length);
}
};
/**
* Left Pads a `Buffer` with leading zeros till it has `length` bytes.
* Or it truncates the beginning if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
const setLengthLeft = function (msg, length) {
(0, helpers_1.assertIsBuffer)(msg);
return setLength(msg, length, false);
};
exports.setLengthLeft = setLengthLeft;
/**
* Right Pads a `Buffer` with trailing zeros till it has `length` bytes.
* it truncates the end if it exceeds.
* @param msg the value to pad (Buffer)
* @param length the number of bytes the output should be
* @return (Buffer)
*/
const setLengthRight = function (msg, length) {
(0, helpers_1.assertIsBuffer)(msg);
return setLength(msg, length, true);
};
exports.setLengthRight = setLengthRight;
/**
* Trims leading zeros from a `Buffer`, `String` or `Number[]`.
* @param a (Buffer|Array|String)
* @return (Buffer|Array|String)
*/
const stripZeros = function (a) {
let first = a[0];
while (a.length > 0 && first.toString() === '0') {
a = a.slice(1);
first = a[0];
}
return a;
};
/**
* Trims leading zeros from a `Buffer`.
* @param a (Buffer)
* @return (Buffer)
*/
const unpadBuffer = function (a) {
(0, helpers_1.assertIsBuffer)(a);
return stripZeros(a);
};
exports.unpadBuffer = unpadBuffer;
/**
* Trims leading zeros from an `Array` (of numbers).
* @param a (number[])
* @return (number[])
*/
const unpadArray = function (a) {
(0, helpers_1.assertIsArray)(a);
return stripZeros(a);
};
exports.unpadArray = unpadArray;
/**
* Trims leading zeros from a hex-prefixed `String`.
* @param a (String)
* @return (String)
*/
const unpadHexString = function (a) {
(0, helpers_1.assertIsHexString)(a);
a = (0, internal_1.stripHexPrefix)(a);
return ('0x' + stripZeros(a));
};
exports.unpadHexString = unpadHexString;
/**
* Attempts to turn a value into a `Buffer`.
* Inputs supported: `Buffer`, `String` (hex-prefixed), `Number`, null/undefined, `BigInt` and other objects
* with a `toArray()` or `toBuffer()` method.
* @param v the value
*/
const toBuffer = function (v) {
if (v === null || v === undefined) {
return Buffer.allocUnsafe(0);
}
if (Buffer.isBuffer(v)) {
return Buffer.from(v);
}
if (Array.isArray(v) || v instanceof Uint8Array) {
return Buffer.from(v);
}
if (typeof v === 'string') {
if (!(0, internal_1.isHexString)(v)) {
throw new Error(`Cannot convert string to buffer. toBuffer only supports 0x-prefixed hex strings and this string was given: ${v}`);
}
return Buffer.from((0, internal_1.padToEven)((0, internal_1.stripHexPrefix)(v)), 'hex');
}
if (typeof v === 'number') {
return (0, exports.intToBuffer)(v);
}
if (typeof v === 'bigint') {
if (v < BigInt(0)) {
throw new Error(`Cannot convert negative bigint to buffer. Given: ${v}`);
}
let n = v.toString(16);
if (n.length % 2)
n = '0' + n;
return Buffer.from(n, 'hex');
}
if (v.toArray) {
// converts a BN to a Buffer
return Buffer.from(v.toArray());
}
if (v.toBuffer) {
return Buffer.from(v.toBuffer());
}
throw new Error('invalid type');
};
exports.toBuffer = toBuffer;
/**
* Converts a `Buffer` into a `0x`-prefixed hex `String`.
* @param buf `Buffer` object to convert
*/
const bufferToHex = function (buf) {
buf = (0, exports.toBuffer)(buf);
return '0x' + buf.toString('hex');
};
exports.bufferToHex = bufferToHex;
/**
* Converts a {@link Buffer} to a {@link bigint}
*/
function bufferToBigInt(buf) {
const hex = (0, exports.bufferToHex)(buf);
if (hex === '0x') {
return BigInt(0);
}
return BigInt(hex);
}
exports.bufferToBigInt = bufferToBigInt;
/**
* Converts a {@link bigint} to a {@link Buffer}
*/
function bigIntToBuffer(num) {
return (0, exports.toBuffer)('0x' + num.toString(16));
}
exports.bigIntToBuffer = bigIntToBuffer;
/**
* Converts a `Buffer` to a `Number`.
* @param buf `Buffer` object to convert
* @throws If the input number exceeds 53 bits.
*/
const bufferToInt = function (buf) {
const res = Number(bufferToBigInt(buf));
if (!Number.isSafeInteger(res))
throw new Error('Number exceeds 53 bits');
return res;
};
exports.bufferToInt = bufferToInt;
/**
* Interprets a `Buffer` as a signed integer and returns a `BigInt`. Assumes 256-bit numbers.
* @param num Signed integer value
*/
const fromSigned = function (num) {
return BigInt.asIntN(256, bufferToBigInt(num));
};
exports.fromSigned = fromSigned;
/**
* Converts a `BigInt` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers.
* @param num
*/
const toUnsigned = function (num) {
return bigIntToBuffer(BigInt.asUintN(256, num));
};
exports.toUnsigned = toUnsigned;
/**
* Adds "0x" to a given `String` if it does not already start with "0x".
*/
const addHexPrefix = function (str) {
if (typeof str !== 'string') {
return str;
}
return (0, internal_1.isHexPrefixed)(str) ? str : '0x' + str;
};
exports.addHexPrefix = addHexPrefix;
/**
* Shortens a string or buffer's hex string representation to maxLength (default 50).
*
* Examples:
*
* Input: '657468657265756d000000000000000000000000000000000000000000000000'
* Output: '657468657265756d0000000000000000000000000000000000…'
*/
function short(buffer, maxLength = 50) {
const bufferStr = Buffer.isBuffer(buffer) ? buffer.toString('hex') : buffer;
if (bufferStr.length <= maxLength) {
return bufferStr;
}
return bufferStr.slice(0, maxLength) + '…';
}
exports.short = short;
/**
* Returns the utf8 string representation from a hex string.
*
* Examples:
*
* Input 1: '657468657265756d000000000000000000000000000000000000000000000000'
* Input 2: '657468657265756d'
* Input 3: '000000000000000000000000000000000000000000000000657468657265756d'
*
* Output (all 3 input variants): 'ethereum'
*
* Note that this method is not intended to be used with hex strings
* representing quantities in both big endian or little endian notation.
*
* @param string Hex string, should be `0x` prefixed
* @return Utf8 string
*/
const toUtf8 = function (hex) {
const zerosRegexp = /^(00)+|(00)+$/g;
hex = (0, internal_1.stripHexPrefix)(hex);
if (hex.length % 2 !== 0) {
throw new Error('Invalid non-even hex string input for toUtf8() provided');
}
const bufferVal = Buffer.from(hex.replace(zerosRegexp, ''), 'hex');
return bufferVal.toString('utf8');
};
exports.toUtf8 = toUtf8;
/**
* Converts a `Buffer` or `Array` to JSON.
* @param ba (Buffer|Array)
* @return (Array|String|null)
*/
const baToJSON = function (ba) {
if (Buffer.isBuffer(ba)) {
return `0x${ba.toString('hex')}`;
}
else if (ba instanceof Array) {
const array = [];
for (let i = 0; i < ba.length; i++) {
array.push((0, exports.baToJSON)(ba[i]));
}
return array;
}
};
exports.baToJSON = baToJSON;
/**
* Checks provided Buffers for leading zeroes and throws if found.
*
* Examples:
*
* Valid values: 0x1, 0x, 0x01, 0x1234
* Invalid values: 0x0, 0x00, 0x001, 0x0001
*
* Note: This method is useful for validating that RLP encoded integers comply with the rule that all
* integer values encoded to RLP must be in the most compact form and contain no leading zero bytes
* @param values An object containing string keys and Buffer values
* @throws if any provided value is found to have leading zero bytes
*/
const validateNoLeadingZeroes = function (values) {
for (const [k, v] of Object.entries(values)) {
if (v !== undefined && v.length > 0 && v[0] === 0) {
throw new Error(`${k} cannot have leading zeroes, received: ${v.toString('hex')}`);
}
}
};
exports.validateNoLeadingZeroes = validateNoLeadingZeroes;
function arrToBufArr(arr) {
if (!Array.isArray(arr)) {
return Buffer.from(arr);
}
return arr.map((a) => arrToBufArr(a));
}
exports.arrToBufArr = arrToBufArr;
function bufArrToArr(arr) {
if (!Array.isArray(arr)) {
return Uint8Array.from(arr ?? []);
}
return arr.map((a) => bufArrToArr(a));
}
exports.bufArrToArr = bufArrToArr;
/**
* Converts a {@link bigint} to a `0x` prefixed hex string
*/
const bigIntToHex = (num) => {
return '0x' + num.toString(16);
};
exports.bigIntToHex = bigIntToHex;
/**
* Convert value from bigint to an unpadded Buffer
* (useful for RLP transport)
* @param value value to convert
*/
function bigIntToUnpaddedBuffer(value) {
return (0, exports.unpadBuffer)(bigIntToBuffer(value));
}
exports.bigIntToUnpaddedBuffer = bigIntToUnpaddedBuffer;
function intToUnpaddedBuffer(value) {
return (0, exports.unpadBuffer)((0, exports.intToBuffer)(value));
}
exports.intToUnpaddedBuffer = intToUnpaddedBuffer;
//# sourceMappingURL=bytes.js.map

File diff suppressed because one or more lines are too long

View file

@ -1,52 +0,0 @@
/// <reference types="node" />
import { Buffer } from 'buffer';
/**
* 2^64-1
*/
export declare const MAX_UINT64: bigint;
/**
* The max integer that the evm can handle (2^256-1)
*/
export declare const MAX_INTEGER: bigint;
/**
* The max integer that the evm can handle (2^256-1) as a bigint
* 2^256-1 equals to 340282366920938463463374607431768211455
* We use literal value instead of calculated value for compatibility issue.
*/
export declare const MAX_INTEGER_BIGINT: bigint;
export declare const SECP256K1_ORDER: bigint;
export declare const SECP256K1_ORDER_DIV_2: bigint;
/**
* 2^256
*/
export declare const TWO_POW256: bigint;
/**
* Keccak-256 hash of null
*/
export declare const KECCAK256_NULL_S = "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470";
/**
* Keccak-256 hash of null
*/
export declare const KECCAK256_NULL: Buffer;
/**
* Keccak-256 of an RLP of an empty array
*/
export declare const KECCAK256_RLP_ARRAY_S = "1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347";
/**
* Keccak-256 of an RLP of an empty array
*/
export declare const KECCAK256_RLP_ARRAY: Buffer;
/**
* Keccak-256 hash of the RLP of null
*/
export declare const KECCAK256_RLP_S = "56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421";
/**
* Keccak-256 hash of the RLP of null
*/
export declare const KECCAK256_RLP: Buffer;
/**
* RLP encoded empty string
*/
export declare const RLP_EMPTY_STRING: Buffer;
export declare const MAX_WITHDRAWALS_PER_PAYLOAD = 16;
//# sourceMappingURL=constants.d.ts.map

View file

@ -1 +0,0 @@
{"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../src/constants.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAA;AAG/B;;GAEG;AACH,eAAO,MAAM,UAAU,QAA+B,CAAA;AAEtD;;GAEG;AACH,eAAO,MAAM,WAAW,QAEvB,CAAA;AAED;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,QAE9B,CAAA;AAED,eAAO,MAAM,eAAe,QAAoB,CAAA;AAChD,eAAO,MAAM,qBAAqB,QAAgC,CAAA;AAElE;;GAEG;AACH,eAAO,MAAM,UAAU,QAEtB,CAAA;AAED;;GAEG;AACH,eAAO,MAAM,gBAAgB,qEAAqE,CAAA;AAElG;;GAEG;AACH,eAAO,MAAM,cAAc,QAAuC,CAAA;AAElE;;GAEG;AACH,eAAO,MAAM,qBAAqB,qEACkC,CAAA;AAEpE;;GAEG;AACH,eAAO,MAAM,mBAAmB,QAA4C,CAAA;AAE5E;;GAEG;AACH,eAAO,MAAM,eAAe,qEAAqE,CAAA;AAEjG;;GAEG;AACH,eAAO,MAAM,aAAa,QAAsC,CAAA;AAEhE;;GAEG;AACH,eAAO,MAAM,gBAAgB,QAAsB,CAAA;AAEnD,eAAO,MAAM,2BAA2B,KAAK,CAAA"}

View file

@ -1,55 +0,0 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MAX_WITHDRAWALS_PER_PAYLOAD = exports.RLP_EMPTY_STRING = exports.KECCAK256_RLP = exports.KECCAK256_RLP_S = exports.KECCAK256_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY_S = exports.KECCAK256_NULL = exports.KECCAK256_NULL_S = exports.TWO_POW256 = exports.SECP256K1_ORDER_DIV_2 = exports.SECP256K1_ORDER = exports.MAX_INTEGER_BIGINT = exports.MAX_INTEGER = exports.MAX_UINT64 = void 0;
const buffer_1 = require("buffer");
const secp256k1_1 = require("ethereum-cryptography/secp256k1");
/**
* 2^64-1
*/
exports.MAX_UINT64 = BigInt('0xffffffffffffffff');
/**
* The max integer that the evm can handle (2^256-1)
*/
exports.MAX_INTEGER = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
/**
* The max integer that the evm can handle (2^256-1) as a bigint
* 2^256-1 equals to 340282366920938463463374607431768211455
* We use literal value instead of calculated value for compatibility issue.
*/
exports.MAX_INTEGER_BIGINT = BigInt('115792089237316195423570985008687907853269984665640564039457584007913129639935');
exports.SECP256K1_ORDER = secp256k1_1.secp256k1.CURVE.n;
exports.SECP256K1_ORDER_DIV_2 = secp256k1_1.secp256k1.CURVE.n / BigInt(2);
/**
* 2^256
*/
exports.TWO_POW256 = BigInt('0x10000000000000000000000000000000000000000000000000000000000000000');
/**
* Keccak-256 hash of null
*/
exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
/**
* Keccak-256 hash of null
*/
exports.KECCAK256_NULL = buffer_1.Buffer.from(exports.KECCAK256_NULL_S, 'hex');
/**
* Keccak-256 of an RLP of an empty array
*/
exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347';
/**
* Keccak-256 of an RLP of an empty array
*/
exports.KECCAK256_RLP_ARRAY = buffer_1.Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex');
/**
* Keccak-256 hash of the RLP of null
*/
exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421';
/**
* Keccak-256 hash of the RLP of null
*/
exports.KECCAK256_RLP = buffer_1.Buffer.from(exports.KECCAK256_RLP_S, 'hex');
/**
* RLP encoded empty string
*/
exports.RLP_EMPTY_STRING = buffer_1.Buffer.from([0x80]);
exports.MAX_WITHDRAWALS_PER_PAYLOAD = 16;
//# sourceMappingURL=constants.js.map

Some files were not shown because too many files have changed in this diff Show more